babylon.max.js 2.7 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150
  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._tempQuaternion = new Quaternion();
  2496. Matrix._xAxis = Vector3.Zero();
  2497. Matrix._yAxis = Vector3.Zero();
  2498. Matrix._zAxis = Vector3.Zero();
  2499. return Matrix;
  2500. }());
  2501. BABYLON.Matrix = Matrix;
  2502. var Plane = (function () {
  2503. function Plane(a, b, c, d) {
  2504. this.normal = new Vector3(a, b, c);
  2505. this.d = d;
  2506. }
  2507. Plane.prototype.asArray = function () {
  2508. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2509. };
  2510. // Methods
  2511. Plane.prototype.clone = function () {
  2512. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2513. };
  2514. Plane.prototype.getClassName = function () {
  2515. return "Plane";
  2516. };
  2517. Plane.prototype.getHashCode = function () {
  2518. var hash = this.normal.getHashCode();
  2519. hash = (hash * 397) ^ (this.d || 0);
  2520. return hash;
  2521. };
  2522. Plane.prototype.normalize = function () {
  2523. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2524. var magnitude = 0;
  2525. if (norm !== 0) {
  2526. magnitude = 1.0 / norm;
  2527. }
  2528. this.normal.x *= magnitude;
  2529. this.normal.y *= magnitude;
  2530. this.normal.z *= magnitude;
  2531. this.d *= magnitude;
  2532. return this;
  2533. };
  2534. Plane.prototype.transform = function (transformation) {
  2535. var transposedMatrix = Matrix.Transpose(transformation);
  2536. var x = this.normal.x;
  2537. var y = this.normal.y;
  2538. var z = this.normal.z;
  2539. var d = this.d;
  2540. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2541. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2542. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2543. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2544. return new Plane(normalX, normalY, normalZ, finalD);
  2545. };
  2546. Plane.prototype.dotCoordinate = function (point) {
  2547. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2548. };
  2549. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2550. var x1 = point2.x - point1.x;
  2551. var y1 = point2.y - point1.y;
  2552. var z1 = point2.z - point1.z;
  2553. var x2 = point3.x - point1.x;
  2554. var y2 = point3.y - point1.y;
  2555. var z2 = point3.z - point1.z;
  2556. var yz = (y1 * z2) - (z1 * y2);
  2557. var xz = (z1 * x2) - (x1 * z2);
  2558. var xy = (x1 * y2) - (y1 * x2);
  2559. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2560. var invPyth;
  2561. if (pyth !== 0) {
  2562. invPyth = 1.0 / pyth;
  2563. }
  2564. else {
  2565. invPyth = 0;
  2566. }
  2567. this.normal.x = yz * invPyth;
  2568. this.normal.y = xz * invPyth;
  2569. this.normal.z = xy * invPyth;
  2570. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2571. return this;
  2572. };
  2573. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2574. var dot = Vector3.Dot(this.normal, direction);
  2575. return (dot <= epsilon);
  2576. };
  2577. Plane.prototype.signedDistanceTo = function (point) {
  2578. return Vector3.Dot(point, this.normal) + this.d;
  2579. };
  2580. // Statics
  2581. Plane.FromArray = function (array) {
  2582. return new Plane(array[0], array[1], array[2], array[3]);
  2583. };
  2584. Plane.FromPoints = function (point1, point2, point3) {
  2585. var result = new Plane(0, 0, 0, 0);
  2586. result.copyFromPoints(point1, point2, point3);
  2587. return result;
  2588. };
  2589. Plane.FromPositionAndNormal = function (origin, normal) {
  2590. var result = new Plane(0, 0, 0, 0);
  2591. normal.normalize();
  2592. result.normal = normal;
  2593. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2594. return result;
  2595. };
  2596. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2597. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2598. return Vector3.Dot(point, normal) + d;
  2599. };
  2600. return Plane;
  2601. }());
  2602. BABYLON.Plane = Plane;
  2603. var Viewport = (function () {
  2604. function Viewport(x, y, width, height) {
  2605. this.x = x;
  2606. this.y = y;
  2607. this.width = width;
  2608. this.height = height;
  2609. }
  2610. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2611. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2612. };
  2613. return Viewport;
  2614. }());
  2615. BABYLON.Viewport = Viewport;
  2616. var Frustum = (function () {
  2617. function Frustum() {
  2618. }
  2619. Frustum.GetPlanes = function (transform) {
  2620. var frustumPlanes = [];
  2621. for (var index = 0; index < 6; index++) {
  2622. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2623. }
  2624. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2625. return frustumPlanes;
  2626. };
  2627. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2628. // Near
  2629. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2630. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2631. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2632. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2633. frustumPlanes[0].normalize();
  2634. // Far
  2635. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2636. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2637. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2638. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2639. frustumPlanes[1].normalize();
  2640. // Left
  2641. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2642. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2643. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2644. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2645. frustumPlanes[2].normalize();
  2646. // Right
  2647. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2648. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2649. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2650. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2651. frustumPlanes[3].normalize();
  2652. // Top
  2653. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2654. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2655. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2656. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2657. frustumPlanes[4].normalize();
  2658. // Bottom
  2659. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2660. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2661. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2662. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2663. frustumPlanes[5].normalize();
  2664. };
  2665. return Frustum;
  2666. }());
  2667. BABYLON.Frustum = Frustum;
  2668. (function (Space) {
  2669. Space[Space["LOCAL"] = 0] = "LOCAL";
  2670. Space[Space["WORLD"] = 1] = "WORLD";
  2671. })(BABYLON.Space || (BABYLON.Space = {}));
  2672. var Space = BABYLON.Space;
  2673. var Axis = (function () {
  2674. function Axis() {
  2675. }
  2676. Axis.X = new Vector3(1, 0, 0);
  2677. Axis.Y = new Vector3(0, 1, 0);
  2678. Axis.Z = new Vector3(0, 0, 1);
  2679. return Axis;
  2680. }());
  2681. BABYLON.Axis = Axis;
  2682. ;
  2683. var BezierCurve = (function () {
  2684. function BezierCurve() {
  2685. }
  2686. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2687. // Extract X (which is equal to time here)
  2688. var f0 = 1 - 3 * x2 + 3 * x1;
  2689. var f1 = 3 * x2 - 6 * x1;
  2690. var f2 = 3 * x1;
  2691. var refinedT = t;
  2692. for (var i = 0; i < 5; i++) {
  2693. var refinedT2 = refinedT * refinedT;
  2694. var refinedT3 = refinedT2 * refinedT;
  2695. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2696. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2697. refinedT -= (x - t) * slope;
  2698. refinedT = Math.min(1, Math.max(0, refinedT));
  2699. }
  2700. // Resolve cubic bezier for the given x
  2701. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2702. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2703. Math.pow(refinedT, 3);
  2704. };
  2705. return BezierCurve;
  2706. }());
  2707. BABYLON.BezierCurve = BezierCurve;
  2708. (function (Orientation) {
  2709. Orientation[Orientation["CW"] = 0] = "CW";
  2710. Orientation[Orientation["CCW"] = 1] = "CCW";
  2711. })(BABYLON.Orientation || (BABYLON.Orientation = {}));
  2712. var Orientation = BABYLON.Orientation;
  2713. var Angle = (function () {
  2714. function Angle(radians) {
  2715. var _this = this;
  2716. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2717. this.radians = function () { return _this._radians; };
  2718. this._radians = radians;
  2719. if (this._radians < 0)
  2720. this._radians += (2 * Math.PI);
  2721. }
  2722. Angle.BetweenTwoPoints = function (a, b) {
  2723. var delta = b.subtract(a);
  2724. var theta = Math.atan2(delta.y, delta.x);
  2725. return new Angle(theta);
  2726. };
  2727. Angle.FromRadians = function (radians) {
  2728. return new Angle(radians);
  2729. };
  2730. Angle.FromDegrees = function (degrees) {
  2731. return new Angle(degrees * Math.PI / 180);
  2732. };
  2733. return Angle;
  2734. }());
  2735. BABYLON.Angle = Angle;
  2736. var Arc2 = (function () {
  2737. function Arc2(startPoint, midPoint, endPoint) {
  2738. this.startPoint = startPoint;
  2739. this.midPoint = midPoint;
  2740. this.endPoint = endPoint;
  2741. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2742. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2743. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2744. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2745. 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);
  2746. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2747. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2748. var a1 = this.startAngle.degrees();
  2749. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2750. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2751. // angles correction
  2752. if (a2 - a1 > +180.0)
  2753. a2 -= 360.0;
  2754. if (a2 - a1 < -180.0)
  2755. a2 += 360.0;
  2756. if (a3 - a2 > +180.0)
  2757. a3 -= 360.0;
  2758. if (a3 - a2 < -180.0)
  2759. a3 += 360.0;
  2760. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2761. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2762. }
  2763. return Arc2;
  2764. }());
  2765. BABYLON.Arc2 = Arc2;
  2766. var Path2 = (function () {
  2767. function Path2(x, y) {
  2768. this._points = new Array();
  2769. this._length = 0;
  2770. this.closed = false;
  2771. this._points.push(new Vector2(x, y));
  2772. }
  2773. Path2.prototype.addLineTo = function (x, y) {
  2774. if (closed) {
  2775. //Tools.Error("cannot add lines to closed paths");
  2776. return this;
  2777. }
  2778. var newPoint = new Vector2(x, y);
  2779. var previousPoint = this._points[this._points.length - 1];
  2780. this._points.push(newPoint);
  2781. this._length += newPoint.subtract(previousPoint).length();
  2782. return this;
  2783. };
  2784. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2785. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2786. if (closed) {
  2787. //Tools.Error("cannot add arcs to closed paths");
  2788. return this;
  2789. }
  2790. var startPoint = this._points[this._points.length - 1];
  2791. var midPoint = new Vector2(midX, midY);
  2792. var endPoint = new Vector2(endX, endY);
  2793. var arc = new Arc2(startPoint, midPoint, endPoint);
  2794. var increment = arc.angle.radians() / numberOfSegments;
  2795. if (arc.orientation === Orientation.CW)
  2796. increment *= -1;
  2797. var currentAngle = arc.startAngle.radians() + increment;
  2798. for (var i = 0; i < numberOfSegments; i++) {
  2799. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2800. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2801. this.addLineTo(x, y);
  2802. currentAngle += increment;
  2803. }
  2804. return this;
  2805. };
  2806. Path2.prototype.close = function () {
  2807. this.closed = true;
  2808. return this;
  2809. };
  2810. Path2.prototype.length = function () {
  2811. var result = this._length;
  2812. if (!this.closed) {
  2813. var lastPoint = this._points[this._points.length - 1];
  2814. var firstPoint = this._points[0];
  2815. result += (firstPoint.subtract(lastPoint).length());
  2816. }
  2817. return result;
  2818. };
  2819. Path2.prototype.getPoints = function () {
  2820. return this._points;
  2821. };
  2822. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2823. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2824. //Tools.Error("normalized length position should be between 0 and 1.");
  2825. return Vector2.Zero();
  2826. }
  2827. var lengthPosition = normalizedLengthPosition * this.length();
  2828. var previousOffset = 0;
  2829. for (var i = 0; i < this._points.length; i++) {
  2830. var j = (i + 1) % this._points.length;
  2831. var a = this._points[i];
  2832. var b = this._points[j];
  2833. var bToA = b.subtract(a);
  2834. var nextOffset = (bToA.length() + previousOffset);
  2835. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2836. var dir = bToA.normalize();
  2837. var localOffset = lengthPosition - previousOffset;
  2838. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2839. }
  2840. previousOffset = nextOffset;
  2841. }
  2842. //Tools.Error("internal error");
  2843. return Vector2.Zero();
  2844. };
  2845. Path2.StartingAt = function (x, y) {
  2846. return new Path2(x, y);
  2847. };
  2848. return Path2;
  2849. }());
  2850. BABYLON.Path2 = Path2;
  2851. var Path3D = (function () {
  2852. /**
  2853. * new Path3D(path, normal, raw)
  2854. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2855. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2856. * path : an array of Vector3, the curve axis of the Path3D
  2857. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2858. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2859. */
  2860. function Path3D(path, firstNormal, raw) {
  2861. this.path = path;
  2862. this._curve = new Array();
  2863. this._distances = new Array();
  2864. this._tangents = new Array();
  2865. this._normals = new Array();
  2866. this._binormals = new Array();
  2867. for (var p = 0; p < path.length; p++) {
  2868. this._curve[p] = path[p].clone(); // hard copy
  2869. }
  2870. this._raw = raw || false;
  2871. this._compute(firstNormal);
  2872. }
  2873. /**
  2874. * Returns the Path3D array of successive Vector3 designing its curve.
  2875. */
  2876. Path3D.prototype.getCurve = function () {
  2877. return this._curve;
  2878. };
  2879. /**
  2880. * Returns an array populated with tangent vectors on each Path3D curve point.
  2881. */
  2882. Path3D.prototype.getTangents = function () {
  2883. return this._tangents;
  2884. };
  2885. /**
  2886. * Returns an array populated with normal vectors on each Path3D curve point.
  2887. */
  2888. Path3D.prototype.getNormals = function () {
  2889. return this._normals;
  2890. };
  2891. /**
  2892. * Returns an array populated with binormal vectors on each Path3D curve point.
  2893. */
  2894. Path3D.prototype.getBinormals = function () {
  2895. return this._binormals;
  2896. };
  2897. /**
  2898. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2899. */
  2900. Path3D.prototype.getDistances = function () {
  2901. return this._distances;
  2902. };
  2903. /**
  2904. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2905. * Returns the same object updated.
  2906. */
  2907. Path3D.prototype.update = function (path, firstNormal) {
  2908. for (var p = 0; p < path.length; p++) {
  2909. this._curve[p].x = path[p].x;
  2910. this._curve[p].y = path[p].y;
  2911. this._curve[p].z = path[p].z;
  2912. }
  2913. this._compute(firstNormal);
  2914. return this;
  2915. };
  2916. // private function compute() : computes tangents, normals and binormals
  2917. Path3D.prototype._compute = function (firstNormal) {
  2918. var l = this._curve.length;
  2919. // first and last tangents
  2920. this._tangents[0] = this._getFirstNonNullVector(0);
  2921. if (!this._raw) {
  2922. this._tangents[0].normalize();
  2923. }
  2924. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2925. if (!this._raw) {
  2926. this._tangents[l - 1].normalize();
  2927. }
  2928. // normals and binormals at first point : arbitrary vector with _normalVector()
  2929. var tg0 = this._tangents[0];
  2930. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2931. this._normals[0] = pp0;
  2932. if (!this._raw) {
  2933. this._normals[0].normalize();
  2934. }
  2935. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2936. if (!this._raw) {
  2937. this._binormals[0].normalize();
  2938. }
  2939. this._distances[0] = 0.0;
  2940. // normals and binormals : next points
  2941. var prev; // previous vector (segment)
  2942. var cur; // current vector (segment)
  2943. var curTang; // current tangent
  2944. // previous normal
  2945. var prevBinor; // previous binormal
  2946. for (var i = 1; i < l; i++) {
  2947. // tangents
  2948. prev = this._getLastNonNullVector(i);
  2949. if (i < l - 1) {
  2950. cur = this._getFirstNonNullVector(i);
  2951. this._tangents[i] = prev.add(cur);
  2952. this._tangents[i].normalize();
  2953. }
  2954. this._distances[i] = this._distances[i - 1] + prev.length();
  2955. // normals and binormals
  2956. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  2957. curTang = this._tangents[i];
  2958. prevBinor = this._binormals[i - 1];
  2959. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  2960. if (!this._raw) {
  2961. this._normals[i].normalize();
  2962. }
  2963. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  2964. if (!this._raw) {
  2965. this._binormals[i].normalize();
  2966. }
  2967. }
  2968. };
  2969. // private function getFirstNonNullVector(index)
  2970. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  2971. Path3D.prototype._getFirstNonNullVector = function (index) {
  2972. var i = 1;
  2973. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  2974. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  2975. i++;
  2976. nNVector = this._curve[index + i].subtract(this._curve[index]);
  2977. }
  2978. return nNVector;
  2979. };
  2980. // private function getLastNonNullVector(index)
  2981. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  2982. Path3D.prototype._getLastNonNullVector = function (index) {
  2983. var i = 1;
  2984. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  2985. while (nLVector.length() === 0 && index > i + 1) {
  2986. i++;
  2987. nLVector = this._curve[index].subtract(this._curve[index - i]);
  2988. }
  2989. return nLVector;
  2990. };
  2991. // private function normalVector(v0, vt, va) :
  2992. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  2993. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  2994. Path3D.prototype._normalVector = function (v0, vt, va) {
  2995. var normal0;
  2996. var tgl = vt.length();
  2997. if (tgl === 0.0) {
  2998. tgl = 1.0;
  2999. }
  3000. if (va === undefined || va === null) {
  3001. var point;
  3002. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3003. point = new Vector3(0.0, -1.0, 0.0);
  3004. }
  3005. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3006. point = new Vector3(1.0, 0.0, 0.0);
  3007. }
  3008. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3009. point = new Vector3(0.0, 0.0, 1.0);
  3010. }
  3011. normal0 = Vector3.Cross(vt, point);
  3012. }
  3013. else {
  3014. normal0 = Vector3.Cross(vt, va);
  3015. Vector3.CrossToRef(normal0, vt, normal0);
  3016. }
  3017. normal0.normalize();
  3018. return normal0;
  3019. };
  3020. return Path3D;
  3021. }());
  3022. BABYLON.Path3D = Path3D;
  3023. var Curve3 = (function () {
  3024. /**
  3025. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3026. * A Curve3 is designed from a series of successive Vector3.
  3027. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3028. */
  3029. function Curve3(points) {
  3030. this._length = 0.0;
  3031. this._points = points;
  3032. this._length = this._computeLength(points);
  3033. }
  3034. /**
  3035. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3036. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3037. * @param v1 (Vector3) the control point
  3038. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3039. * @param nbPoints (integer) the wanted number of points in the curve
  3040. */
  3041. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3042. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3043. var bez = new Array();
  3044. var equation = function (t, val0, val1, val2) {
  3045. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3046. return res;
  3047. };
  3048. for (var i = 0; i <= nbPoints; i++) {
  3049. 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)));
  3050. }
  3051. return new Curve3(bez);
  3052. };
  3053. /**
  3054. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3055. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3056. * @param v1 (Vector3) the first control point
  3057. * @param v2 (Vector3) the second control point
  3058. * @param v3 (Vector3) the end point of the Cubic Bezier
  3059. * @param nbPoints (integer) the wanted number of points in the curve
  3060. */
  3061. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3062. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3063. var bez = new Array();
  3064. var equation = function (t, val0, val1, val2, val3) {
  3065. 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;
  3066. return res;
  3067. };
  3068. for (var i = 0; i <= nbPoints; i++) {
  3069. 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)));
  3070. }
  3071. return new Curve3(bez);
  3072. };
  3073. /**
  3074. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3075. * @param p1 (Vector3) the origin point of the Hermite Spline
  3076. * @param t1 (Vector3) the tangent vector at the origin point
  3077. * @param p2 (Vector3) the end point of the Hermite Spline
  3078. * @param t2 (Vector3) the tangent vector at the end point
  3079. * @param nbPoints (integer) the wanted number of points in the curve
  3080. */
  3081. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3082. var hermite = new Array();
  3083. var step = 1.0 / nbPoints;
  3084. for (var i = 0; i <= nbPoints; i++) {
  3085. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3086. }
  3087. return new Curve3(hermite);
  3088. };
  3089. /**
  3090. * Returns the Curve3 stored array of successive Vector3
  3091. */
  3092. Curve3.prototype.getPoints = function () {
  3093. return this._points;
  3094. };
  3095. /**
  3096. * Returns the computed length (float) of the curve.
  3097. */
  3098. Curve3.prototype.length = function () {
  3099. return this._length;
  3100. };
  3101. /**
  3102. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3103. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3104. * curveA and curveB keep unchanged.
  3105. */
  3106. Curve3.prototype.continue = function (curve) {
  3107. var lastPoint = this._points[this._points.length - 1];
  3108. var continuedPoints = this._points.slice();
  3109. var curvePoints = curve.getPoints();
  3110. for (var i = 1; i < curvePoints.length; i++) {
  3111. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3112. }
  3113. var continuedCurve = new Curve3(continuedPoints);
  3114. return continuedCurve;
  3115. };
  3116. Curve3.prototype._computeLength = function (path) {
  3117. var l = 0;
  3118. for (var i = 1; i < path.length; i++) {
  3119. l += (path[i].subtract(path[i - 1])).length();
  3120. }
  3121. return l;
  3122. };
  3123. return Curve3;
  3124. }());
  3125. BABYLON.Curve3 = Curve3;
  3126. // SphericalHarmonics
  3127. var SphericalHarmonics = (function () {
  3128. function SphericalHarmonics() {
  3129. this.L00 = Vector3.Zero();
  3130. this.L1_1 = Vector3.Zero();
  3131. this.L10 = Vector3.Zero();
  3132. this.L11 = Vector3.Zero();
  3133. this.L2_2 = Vector3.Zero();
  3134. this.L2_1 = Vector3.Zero();
  3135. this.L20 = Vector3.Zero();
  3136. this.L21 = Vector3.Zero();
  3137. this.L22 = Vector3.Zero();
  3138. }
  3139. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3140. var colorVector = new Vector3(color.r, color.g, color.b);
  3141. var c = colorVector.scale(deltaSolidAngle);
  3142. this.L00 = this.L00.add(c.scale(0.282095));
  3143. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3144. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3145. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3146. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3147. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3148. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3149. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3150. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3151. };
  3152. SphericalHarmonics.prototype.scale = function (scale) {
  3153. this.L00 = this.L00.scale(scale);
  3154. this.L1_1 = this.L1_1.scale(scale);
  3155. this.L10 = this.L10.scale(scale);
  3156. this.L11 = this.L11.scale(scale);
  3157. this.L2_2 = this.L2_2.scale(scale);
  3158. this.L2_1 = this.L2_1.scale(scale);
  3159. this.L20 = this.L20.scale(scale);
  3160. this.L21 = this.L21.scale(scale);
  3161. this.L22 = this.L22.scale(scale);
  3162. };
  3163. return SphericalHarmonics;
  3164. }());
  3165. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3166. // SphericalPolynomial
  3167. var SphericalPolynomial = (function () {
  3168. function SphericalPolynomial() {
  3169. this.x = Vector3.Zero();
  3170. this.y = Vector3.Zero();
  3171. this.z = Vector3.Zero();
  3172. this.xx = Vector3.Zero();
  3173. this.yy = Vector3.Zero();
  3174. this.zz = Vector3.Zero();
  3175. this.xy = Vector3.Zero();
  3176. this.yz = Vector3.Zero();
  3177. this.zx = Vector3.Zero();
  3178. }
  3179. SphericalPolynomial.prototype.addAmbient = function (color) {
  3180. var colorVector = new Vector3(color.r, color.g, color.b);
  3181. this.xx = this.xx.add(colorVector);
  3182. this.yy = this.yy.add(colorVector);
  3183. this.zz = this.zz.add(colorVector);
  3184. };
  3185. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3186. var result = new SphericalPolynomial();
  3187. result.x = harmonics.L11.scale(1.02333);
  3188. result.y = harmonics.L1_1.scale(1.02333);
  3189. result.z = harmonics.L10.scale(1.02333);
  3190. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3191. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3192. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3193. result.yz = harmonics.L2_1.scale(0.858086);
  3194. result.zx = harmonics.L21.scale(0.858086);
  3195. result.xy = harmonics.L2_2.scale(0.858086);
  3196. return result;
  3197. };
  3198. return SphericalPolynomial;
  3199. }());
  3200. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3201. // Vertex formats
  3202. var PositionNormalVertex = (function () {
  3203. function PositionNormalVertex(position, normal) {
  3204. if (position === void 0) { position = Vector3.Zero(); }
  3205. if (normal === void 0) { normal = Vector3.Up(); }
  3206. this.position = position;
  3207. this.normal = normal;
  3208. }
  3209. PositionNormalVertex.prototype.clone = function () {
  3210. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3211. };
  3212. return PositionNormalVertex;
  3213. }());
  3214. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3215. var PositionNormalTextureVertex = (function () {
  3216. function PositionNormalTextureVertex(position, normal, uv) {
  3217. if (position === void 0) { position = Vector3.Zero(); }
  3218. if (normal === void 0) { normal = Vector3.Up(); }
  3219. if (uv === void 0) { uv = Vector2.Zero(); }
  3220. this.position = position;
  3221. this.normal = normal;
  3222. this.uv = uv;
  3223. }
  3224. PositionNormalTextureVertex.prototype.clone = function () {
  3225. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3226. };
  3227. return PositionNormalTextureVertex;
  3228. }());
  3229. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3230. // Temporary pre-allocated objects for engine internal use
  3231. // usage in any internal function :
  3232. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3233. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3234. var Tmp = (function () {
  3235. function Tmp() {
  3236. }
  3237. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3238. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3239. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3240. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3241. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3242. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3243. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3244. Matrix.Zero(), Matrix.Zero(),
  3245. Matrix.Zero(), Matrix.Zero(),
  3246. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3247. return Tmp;
  3248. }());
  3249. BABYLON.Tmp = Tmp;
  3250. })(BABYLON || (BABYLON = {}));
  3251. var BABYLON;
  3252. (function (BABYLON) {
  3253. function generateSerializableMember(type, sourceName) {
  3254. return function (target, propertyKey) {
  3255. if (!target.__serializableMembers) {
  3256. target.__serializableMembers = {};
  3257. }
  3258. if (!target.__serializableMembers[propertyKey]) {
  3259. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3260. }
  3261. };
  3262. }
  3263. function serialize(sourceName) {
  3264. return generateSerializableMember(0, sourceName); // value member
  3265. }
  3266. BABYLON.serialize = serialize;
  3267. function serializeAsTexture(sourceName) {
  3268. return generateSerializableMember(1, sourceName); // texture member
  3269. }
  3270. BABYLON.serializeAsTexture = serializeAsTexture;
  3271. function serializeAsColor3(sourceName) {
  3272. return generateSerializableMember(2, sourceName); // color3 member
  3273. }
  3274. BABYLON.serializeAsColor3 = serializeAsColor3;
  3275. function serializeAsFresnelParameters(sourceName) {
  3276. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3277. }
  3278. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3279. function serializeAsVector2(sourceName) {
  3280. return generateSerializableMember(4, sourceName); // vector2 member
  3281. }
  3282. BABYLON.serializeAsVector2 = serializeAsVector2;
  3283. function serializeAsVector3(sourceName) {
  3284. return generateSerializableMember(5, sourceName); // vector3 member
  3285. }
  3286. BABYLON.serializeAsVector3 = serializeAsVector3;
  3287. function serializeAsMeshReference(sourceName) {
  3288. return generateSerializableMember(6, sourceName); // mesh reference member
  3289. }
  3290. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3291. function serializeAsColorCurves(sourceName) {
  3292. return generateSerializableMember(7, sourceName); // color curves
  3293. }
  3294. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3295. var SerializationHelper = (function () {
  3296. function SerializationHelper() {
  3297. }
  3298. SerializationHelper.Serialize = function (entity, serializationObject) {
  3299. if (!serializationObject) {
  3300. serializationObject = {};
  3301. }
  3302. // Tags
  3303. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3304. // Properties
  3305. for (var property in entity.__serializableMembers) {
  3306. var propertyDescriptor = entity.__serializableMembers[property];
  3307. var targetPropertyName = propertyDescriptor.sourceName || property;
  3308. var propertyType = propertyDescriptor.type;
  3309. var sourceProperty = entity[property];
  3310. if (sourceProperty !== undefined && sourceProperty !== null) {
  3311. switch (propertyType) {
  3312. case 0:
  3313. serializationObject[targetPropertyName] = sourceProperty;
  3314. break;
  3315. case 1:
  3316. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3317. break;
  3318. case 2:
  3319. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3320. break;
  3321. case 3:
  3322. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3323. break;
  3324. case 4:
  3325. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3326. break;
  3327. case 5:
  3328. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3329. break;
  3330. case 6:
  3331. serializationObject[targetPropertyName] = sourceProperty.id;
  3332. break;
  3333. case 7:
  3334. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3335. break;
  3336. }
  3337. }
  3338. }
  3339. return serializationObject;
  3340. };
  3341. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3342. var destination = creationFunction();
  3343. // Tags
  3344. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3345. // Properties
  3346. for (var property in destination.__serializableMembers) {
  3347. var propertyDescriptor = destination.__serializableMembers[property];
  3348. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3349. var propertyType = propertyDescriptor.type;
  3350. if (sourceProperty !== undefined && sourceProperty !== null) {
  3351. switch (propertyType) {
  3352. case 0:
  3353. destination[property] = sourceProperty;
  3354. break;
  3355. case 1:
  3356. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3357. break;
  3358. case 2:
  3359. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3360. break;
  3361. case 3:
  3362. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3363. break;
  3364. case 4:
  3365. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3366. break;
  3367. case 5:
  3368. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3369. break;
  3370. case 6:
  3371. destination[property] = scene.getLastMeshByID(sourceProperty);
  3372. break;
  3373. case 7:
  3374. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3375. break;
  3376. }
  3377. }
  3378. }
  3379. return destination;
  3380. };
  3381. SerializationHelper.Clone = function (creationFunction, source) {
  3382. var destination = creationFunction();
  3383. // Tags
  3384. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3385. // Properties
  3386. for (var property in destination.__serializableMembers) {
  3387. var propertyDescriptor = destination.__serializableMembers[property];
  3388. var sourceProperty = source[property];
  3389. var propertyType = propertyDescriptor.type;
  3390. if (sourceProperty !== undefined && sourceProperty !== null) {
  3391. switch (propertyType) {
  3392. case 0: // Value
  3393. case 6:
  3394. destination[property] = sourceProperty;
  3395. break;
  3396. case 1: // Texture
  3397. case 2: // Color3
  3398. case 3: // FresnelParameters
  3399. case 4: // Vector2
  3400. case 5: // Vector3
  3401. case 7:
  3402. destination[property] = sourceProperty.clone();
  3403. break;
  3404. }
  3405. }
  3406. }
  3407. return destination;
  3408. };
  3409. return SerializationHelper;
  3410. }());
  3411. BABYLON.SerializationHelper = SerializationHelper;
  3412. })(BABYLON || (BABYLON = {}));
  3413. var BABYLON;
  3414. (function (BABYLON) {
  3415. /**
  3416. * A class serves as a medium between the observable and its observers
  3417. */
  3418. var EventState = (function () {
  3419. /**
  3420. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3421. */
  3422. function EventState(mask, skipNextObservers) {
  3423. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3424. this.initalize(mask, skipNextObservers);
  3425. }
  3426. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3427. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3428. this.mask = mask;
  3429. this.skipNextObservers = skipNextObservers;
  3430. return this;
  3431. };
  3432. return EventState;
  3433. }());
  3434. BABYLON.EventState = EventState;
  3435. /**
  3436. * Represent an Observer registered to a given Observable object.
  3437. */
  3438. var Observer = (function () {
  3439. function Observer(callback, mask) {
  3440. this.callback = callback;
  3441. this.mask = mask;
  3442. }
  3443. return Observer;
  3444. }());
  3445. BABYLON.Observer = Observer;
  3446. /**
  3447. * The Observable class is a simple implementation of the Observable pattern.
  3448. * 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.
  3449. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3450. * 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).
  3451. * 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.
  3452. */
  3453. var Observable = (function () {
  3454. function Observable() {
  3455. this._observers = new Array();
  3456. this._eventState = new EventState(0);
  3457. }
  3458. /**
  3459. * Create a new Observer with the specified callback
  3460. * @param callback the callback that will be executed for that Observer
  3461. * @param mask the mask used to filter observers
  3462. * @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.
  3463. */
  3464. Observable.prototype.add = function (callback, mask, insertFirst) {
  3465. if (mask === void 0) { mask = -1; }
  3466. if (insertFirst === void 0) { insertFirst = false; }
  3467. if (!callback) {
  3468. return null;
  3469. }
  3470. var observer = new Observer(callback, mask);
  3471. if (insertFirst) {
  3472. this._observers.unshift(observer);
  3473. }
  3474. else {
  3475. this._observers.push(observer);
  3476. }
  3477. return observer;
  3478. };
  3479. /**
  3480. * Remove an Observer from the Observable object
  3481. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3482. */
  3483. Observable.prototype.remove = function (observer) {
  3484. var index = this._observers.indexOf(observer);
  3485. if (index !== -1) {
  3486. this._observers.splice(index, 1);
  3487. return true;
  3488. }
  3489. return false;
  3490. };
  3491. /**
  3492. * Remove a callback from the Observable object
  3493. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3494. */
  3495. Observable.prototype.removeCallback = function (callback) {
  3496. for (var index = 0; index < this._observers.length; index++) {
  3497. if (this._observers[index].callback === callback) {
  3498. this._observers.splice(index, 1);
  3499. return true;
  3500. }
  3501. }
  3502. return false;
  3503. };
  3504. /**
  3505. * Notify all Observers by calling their respective callback with the given data
  3506. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3507. * @param eventData
  3508. * @param mask
  3509. */
  3510. Observable.prototype.notifyObservers = function (eventData, mask) {
  3511. if (mask === void 0) { mask = -1; }
  3512. var state = this._eventState;
  3513. state.mask = mask;
  3514. state.skipNextObservers = false;
  3515. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3516. var obs = _a[_i];
  3517. if (obs.mask & mask) {
  3518. obs.callback(eventData, state);
  3519. }
  3520. if (state.skipNextObservers) {
  3521. return false;
  3522. }
  3523. }
  3524. return true;
  3525. };
  3526. /**
  3527. * return true is the Observable has at least one Observer registered
  3528. */
  3529. Observable.prototype.hasObservers = function () {
  3530. return this._observers.length > 0;
  3531. };
  3532. /**
  3533. * Clear the list of observers
  3534. */
  3535. Observable.prototype.clear = function () {
  3536. this._observers = new Array();
  3537. };
  3538. /**
  3539. * Clone the current observable
  3540. */
  3541. Observable.prototype.clone = function () {
  3542. var result = new Observable();
  3543. result._observers = this._observers.slice(0);
  3544. return result;
  3545. };
  3546. return Observable;
  3547. }());
  3548. BABYLON.Observable = Observable;
  3549. })(BABYLON || (BABYLON = {}));
  3550. var BABYLON;
  3551. (function (BABYLON) {
  3552. var Database = (function () {
  3553. function Database(urlToScene, callbackManifestChecked) {
  3554. // Handling various flavors of prefixed version of IndexedDB
  3555. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3556. this.callbackManifestChecked = callbackManifestChecked;
  3557. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3558. this.db = null;
  3559. this.enableSceneOffline = false;
  3560. this.enableTexturesOffline = false;
  3561. this.manifestVersionFound = 0;
  3562. this.mustUpdateRessources = false;
  3563. this.hasReachedQuota = false;
  3564. if (!Database.IDBStorageEnabled) {
  3565. this.callbackManifestChecked(true);
  3566. }
  3567. else {
  3568. this.checkManifestFile();
  3569. }
  3570. }
  3571. Database.prototype.checkManifestFile = function () {
  3572. var _this = this;
  3573. function noManifestFile() {
  3574. that.enableSceneOffline = false;
  3575. that.enableTexturesOffline = false;
  3576. that.callbackManifestChecked(false);
  3577. }
  3578. var that = this;
  3579. var timeStampUsed = false;
  3580. var manifestURL = this.currentSceneUrl + ".manifest";
  3581. var xhr = new XMLHttpRequest();
  3582. if (navigator.onLine) {
  3583. // Adding a timestamp to by-pass browsers' cache
  3584. timeStampUsed = true;
  3585. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3586. }
  3587. xhr.open("GET", manifestURL, true);
  3588. xhr.addEventListener("load", function () {
  3589. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3590. try {
  3591. var manifestFile = JSON.parse(xhr.response);
  3592. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3593. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3594. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3595. _this.manifestVersionFound = manifestFile.version;
  3596. }
  3597. if (_this.callbackManifestChecked) {
  3598. _this.callbackManifestChecked(true);
  3599. }
  3600. }
  3601. catch (ex) {
  3602. noManifestFile();
  3603. }
  3604. }
  3605. else {
  3606. noManifestFile();
  3607. }
  3608. }, false);
  3609. xhr.addEventListener("error", function (event) {
  3610. if (timeStampUsed) {
  3611. timeStampUsed = false;
  3612. // Let's retry without the timeStamp
  3613. // It could fail when coupled with HTML5 Offline API
  3614. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3615. xhr.open("GET", retryManifestURL, true);
  3616. xhr.send();
  3617. }
  3618. else {
  3619. noManifestFile();
  3620. }
  3621. }, false);
  3622. try {
  3623. xhr.send();
  3624. }
  3625. catch (ex) {
  3626. BABYLON.Tools.Error("Error on XHR send request.");
  3627. that.callbackManifestChecked(false);
  3628. }
  3629. };
  3630. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3631. var _this = this;
  3632. function handleError() {
  3633. that.isSupported = false;
  3634. if (errorCallback)
  3635. errorCallback();
  3636. }
  3637. var that = this;
  3638. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3639. // Your browser doesn't support IndexedDB
  3640. this.isSupported = false;
  3641. if (errorCallback)
  3642. errorCallback();
  3643. }
  3644. else {
  3645. // If the DB hasn't been opened or created yet
  3646. if (!this.db) {
  3647. this.hasReachedQuota = false;
  3648. this.isSupported = true;
  3649. var request = this.idbFactory.open("babylonjs", 1);
  3650. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3651. request.onerror = function (event) {
  3652. handleError();
  3653. };
  3654. // executes when a version change transaction cannot complete due to other active transactions
  3655. request.onblocked = function (event) {
  3656. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3657. handleError();
  3658. };
  3659. // DB has been opened successfully
  3660. request.onsuccess = function (event) {
  3661. _this.db = request.result;
  3662. successCallback();
  3663. };
  3664. // Initialization of the DB. Creating Scenes & Textures stores
  3665. request.onupgradeneeded = function (event) {
  3666. _this.db = (event.target).result;
  3667. try {
  3668. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3669. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3670. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3671. }
  3672. catch (ex) {
  3673. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3674. handleError();
  3675. }
  3676. };
  3677. }
  3678. else {
  3679. if (successCallback)
  3680. successCallback();
  3681. }
  3682. }
  3683. };
  3684. Database.prototype.loadImageFromDB = function (url, image) {
  3685. var _this = this;
  3686. var completeURL = Database.ReturnFullUrlLocation(url);
  3687. var saveAndLoadImage = function () {
  3688. if (!_this.hasReachedQuota && _this.db !== null) {
  3689. // the texture is not yet in the DB, let's try to save it
  3690. _this._saveImageIntoDBAsync(completeURL, image);
  3691. }
  3692. else {
  3693. image.src = url;
  3694. }
  3695. };
  3696. if (!this.mustUpdateRessources) {
  3697. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3698. }
  3699. else {
  3700. saveAndLoadImage();
  3701. }
  3702. };
  3703. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3704. if (this.isSupported && this.db !== null) {
  3705. var texture;
  3706. var transaction = this.db.transaction(["textures"]);
  3707. transaction.onabort = function (event) {
  3708. image.src = url;
  3709. };
  3710. transaction.oncomplete = function (event) {
  3711. var blobTextureURL;
  3712. if (texture) {
  3713. var URL = window.URL || window.webkitURL;
  3714. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3715. image.onerror = function () {
  3716. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3717. image.src = url;
  3718. };
  3719. image.src = blobTextureURL;
  3720. }
  3721. else {
  3722. notInDBCallback();
  3723. }
  3724. };
  3725. var getRequest = transaction.objectStore("textures").get(url);
  3726. getRequest.onsuccess = function (event) {
  3727. texture = (event.target).result;
  3728. };
  3729. getRequest.onerror = function (event) {
  3730. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3731. image.src = url;
  3732. };
  3733. }
  3734. else {
  3735. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3736. image.src = url;
  3737. }
  3738. };
  3739. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3740. var _this = this;
  3741. if (this.isSupported) {
  3742. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3743. var generateBlobUrl = function () {
  3744. var blobTextureURL;
  3745. if (blob) {
  3746. var URL = window.URL || window.webkitURL;
  3747. try {
  3748. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3749. }
  3750. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3751. catch (ex) {
  3752. blobTextureURL = URL.createObjectURL(blob);
  3753. }
  3754. }
  3755. image.src = blobTextureURL;
  3756. };
  3757. if (Database.IsUASupportingBlobStorage) {
  3758. var xhr = new XMLHttpRequest(), blob;
  3759. xhr.open("GET", url, true);
  3760. xhr.responseType = "blob";
  3761. xhr.addEventListener("load", function () {
  3762. if (xhr.status === 200) {
  3763. // Blob as response (XHR2)
  3764. blob = xhr.response;
  3765. var transaction = _this.db.transaction(["textures"], "readwrite");
  3766. // the transaction could abort because of a QuotaExceededError error
  3767. transaction.onabort = function (event) {
  3768. try {
  3769. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3770. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3771. _this.hasReachedQuota = true;
  3772. }
  3773. }
  3774. catch (ex) { }
  3775. generateBlobUrl();
  3776. };
  3777. transaction.oncomplete = function (event) {
  3778. generateBlobUrl();
  3779. };
  3780. var newTexture = { textureUrl: url, data: blob };
  3781. try {
  3782. // Put the blob into the dabase
  3783. var addRequest = transaction.objectStore("textures").put(newTexture);
  3784. addRequest.onsuccess = function (event) {
  3785. };
  3786. addRequest.onerror = function (event) {
  3787. generateBlobUrl();
  3788. };
  3789. }
  3790. catch (ex) {
  3791. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3792. if (ex.code === 25) {
  3793. Database.IsUASupportingBlobStorage = false;
  3794. }
  3795. image.src = url;
  3796. }
  3797. }
  3798. else {
  3799. image.src = url;
  3800. }
  3801. }, false);
  3802. xhr.addEventListener("error", function (event) {
  3803. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3804. image.src = url;
  3805. }, false);
  3806. xhr.send();
  3807. }
  3808. else {
  3809. image.src = url;
  3810. }
  3811. }
  3812. else {
  3813. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3814. image.src = url;
  3815. }
  3816. };
  3817. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3818. var _this = this;
  3819. var updateVersion = function (event) {
  3820. // the version is not yet in the DB or we need to update it
  3821. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3822. };
  3823. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3824. };
  3825. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3826. var _this = this;
  3827. if (this.isSupported) {
  3828. var version;
  3829. try {
  3830. var transaction = this.db.transaction(["versions"]);
  3831. transaction.oncomplete = function (event) {
  3832. if (version) {
  3833. // If the version in the JSON file is > than the version in DB
  3834. if (_this.manifestVersionFound > version.data) {
  3835. _this.mustUpdateRessources = true;
  3836. updateInDBCallback();
  3837. }
  3838. else {
  3839. callback(version.data);
  3840. }
  3841. }
  3842. else {
  3843. _this.mustUpdateRessources = true;
  3844. updateInDBCallback();
  3845. }
  3846. };
  3847. transaction.onabort = function (event) {
  3848. callback(-1);
  3849. };
  3850. var getRequest = transaction.objectStore("versions").get(url);
  3851. getRequest.onsuccess = function (event) {
  3852. version = (event.target).result;
  3853. };
  3854. getRequest.onerror = function (event) {
  3855. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3856. callback(-1);
  3857. };
  3858. }
  3859. catch (ex) {
  3860. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3861. callback(-1);
  3862. }
  3863. }
  3864. else {
  3865. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3866. callback(-1);
  3867. }
  3868. };
  3869. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3870. var _this = this;
  3871. if (this.isSupported && !this.hasReachedQuota) {
  3872. try {
  3873. // Open a transaction to the database
  3874. var transaction = this.db.transaction(["versions"], "readwrite");
  3875. // the transaction could abort because of a QuotaExceededError error
  3876. transaction.onabort = function (event) {
  3877. try {
  3878. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3879. _this.hasReachedQuota = true;
  3880. }
  3881. }
  3882. catch (ex) { }
  3883. callback(-1);
  3884. };
  3885. transaction.oncomplete = function (event) {
  3886. callback(_this.manifestVersionFound);
  3887. };
  3888. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3889. // Put the scene into the database
  3890. var addRequest = transaction.objectStore("versions").put(newVersion);
  3891. addRequest.onsuccess = function (event) {
  3892. };
  3893. addRequest.onerror = function (event) {
  3894. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3895. };
  3896. }
  3897. catch (ex) {
  3898. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3899. callback(-1);
  3900. }
  3901. }
  3902. else {
  3903. callback(-1);
  3904. }
  3905. };
  3906. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3907. var _this = this;
  3908. var completeUrl = Database.ReturnFullUrlLocation(url);
  3909. var saveAndLoadFile = function (event) {
  3910. // the scene is not yet in the DB, let's try to save it
  3911. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3912. };
  3913. this._checkVersionFromDB(completeUrl, function (version) {
  3914. if (version !== -1) {
  3915. if (!_this.mustUpdateRessources) {
  3916. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3917. }
  3918. else {
  3919. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3920. }
  3921. }
  3922. else {
  3923. errorCallback();
  3924. }
  3925. });
  3926. };
  3927. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3928. if (this.isSupported) {
  3929. var targetStore;
  3930. if (url.indexOf(".babylon") !== -1) {
  3931. targetStore = "scenes";
  3932. }
  3933. else {
  3934. targetStore = "textures";
  3935. }
  3936. var file;
  3937. var transaction = this.db.transaction([targetStore]);
  3938. transaction.oncomplete = function (event) {
  3939. if (file) {
  3940. callback(file.data);
  3941. }
  3942. else {
  3943. notInDBCallback();
  3944. }
  3945. };
  3946. transaction.onabort = function (event) {
  3947. notInDBCallback();
  3948. };
  3949. var getRequest = transaction.objectStore(targetStore).get(url);
  3950. getRequest.onsuccess = function (event) {
  3951. file = (event.target).result;
  3952. };
  3953. getRequest.onerror = function (event) {
  3954. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  3955. notInDBCallback();
  3956. };
  3957. }
  3958. else {
  3959. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3960. callback();
  3961. }
  3962. };
  3963. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  3964. var _this = this;
  3965. if (this.isSupported) {
  3966. var targetStore;
  3967. if (url.indexOf(".babylon") !== -1) {
  3968. targetStore = "scenes";
  3969. }
  3970. else {
  3971. targetStore = "textures";
  3972. }
  3973. // Create XHR
  3974. var xhr = new XMLHttpRequest(), fileData;
  3975. xhr.open("GET", url, true);
  3976. if (useArrayBuffer) {
  3977. xhr.responseType = "arraybuffer";
  3978. }
  3979. xhr.onprogress = progressCallback;
  3980. xhr.addEventListener("load", function () {
  3981. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  3982. // Blob as response (XHR2)
  3983. //fileData = xhr.responseText;
  3984. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  3985. if (!_this.hasReachedQuota) {
  3986. // Open a transaction to the database
  3987. var transaction = _this.db.transaction([targetStore], "readwrite");
  3988. // the transaction could abort because of a QuotaExceededError error
  3989. transaction.onabort = function (event) {
  3990. try {
  3991. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3992. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3993. _this.hasReachedQuota = true;
  3994. }
  3995. }
  3996. catch (ex) { }
  3997. callback(fileData);
  3998. };
  3999. transaction.oncomplete = function (event) {
  4000. callback(fileData);
  4001. };
  4002. var newFile;
  4003. if (targetStore === "scenes") {
  4004. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4005. }
  4006. else {
  4007. newFile = { textureUrl: url, data: fileData };
  4008. }
  4009. try {
  4010. // Put the scene into the database
  4011. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4012. addRequest.onsuccess = function (event) {
  4013. };
  4014. addRequest.onerror = function (event) {
  4015. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4016. };
  4017. }
  4018. catch (ex) {
  4019. callback(fileData);
  4020. }
  4021. }
  4022. else {
  4023. callback(fileData);
  4024. }
  4025. }
  4026. else {
  4027. callback();
  4028. }
  4029. }, false);
  4030. xhr.addEventListener("error", function (event) {
  4031. BABYLON.Tools.Error("error on XHR request.");
  4032. callback();
  4033. }, false);
  4034. xhr.send();
  4035. }
  4036. else {
  4037. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4038. callback();
  4039. }
  4040. };
  4041. Database.IsUASupportingBlobStorage = true;
  4042. Database.IDBStorageEnabled = true;
  4043. Database.parseURL = function (url) {
  4044. var a = document.createElement('a');
  4045. a.href = url;
  4046. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4047. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4048. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4049. return absLocation;
  4050. };
  4051. Database.ReturnFullUrlLocation = function (url) {
  4052. if (url.indexOf("http:/") === -1) {
  4053. return (Database.parseURL(window.location.href) + url);
  4054. }
  4055. else {
  4056. return url;
  4057. }
  4058. };
  4059. return Database;
  4060. }());
  4061. BABYLON.Database = Database;
  4062. })(BABYLON || (BABYLON = {}));
  4063. var BABYLON;
  4064. (function (BABYLON) {
  4065. var Internals;
  4066. (function (Internals) {
  4067. /*
  4068. * Based on jsTGALoader - Javascript loader for TGA file
  4069. * By Vincent Thibault
  4070. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4071. */
  4072. var TGATools = (function () {
  4073. function TGATools() {
  4074. }
  4075. TGATools.GetTGAHeader = function (data) {
  4076. var offset = 0;
  4077. var header = {
  4078. id_length: data[offset++],
  4079. colormap_type: data[offset++],
  4080. image_type: data[offset++],
  4081. colormap_index: data[offset++] | data[offset++] << 8,
  4082. colormap_length: data[offset++] | data[offset++] << 8,
  4083. colormap_size: data[offset++],
  4084. origin: [
  4085. data[offset++] | data[offset++] << 8,
  4086. data[offset++] | data[offset++] << 8
  4087. ],
  4088. width: data[offset++] | data[offset++] << 8,
  4089. height: data[offset++] | data[offset++] << 8,
  4090. pixel_size: data[offset++],
  4091. flags: data[offset++]
  4092. };
  4093. return header;
  4094. };
  4095. TGATools.UploadContent = function (gl, data) {
  4096. // Not enough data to contain header ?
  4097. if (data.length < 19) {
  4098. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4099. return;
  4100. }
  4101. // Read Header
  4102. var offset = 18;
  4103. var header = TGATools.GetTGAHeader(data);
  4104. // Assume it's a valid Targa file.
  4105. if (header.id_length + offset > data.length) {
  4106. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4107. return;
  4108. }
  4109. // Skip not needed data
  4110. offset += header.id_length;
  4111. var use_rle = false;
  4112. var use_pal = false;
  4113. var use_rgb = false;
  4114. var use_grey = false;
  4115. // Get some informations.
  4116. switch (header.image_type) {
  4117. case TGATools._TYPE_RLE_INDEXED:
  4118. use_rle = true;
  4119. case TGATools._TYPE_INDEXED:
  4120. use_pal = true;
  4121. break;
  4122. case TGATools._TYPE_RLE_RGB:
  4123. use_rle = true;
  4124. case TGATools._TYPE_RGB:
  4125. use_rgb = true;
  4126. break;
  4127. case TGATools._TYPE_RLE_GREY:
  4128. use_rle = true;
  4129. case TGATools._TYPE_GREY:
  4130. use_grey = true;
  4131. break;
  4132. }
  4133. var pixel_data;
  4134. var numAlphaBits = header.flags & 0xf;
  4135. var pixel_size = header.pixel_size >> 3;
  4136. var pixel_total = header.width * header.height * pixel_size;
  4137. // Read palettes
  4138. var palettes;
  4139. if (use_pal) {
  4140. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4141. }
  4142. // Read LRE
  4143. if (use_rle) {
  4144. pixel_data = new Uint8Array(pixel_total);
  4145. var c, count, i;
  4146. var localOffset = 0;
  4147. var pixels = new Uint8Array(pixel_size);
  4148. while (offset < pixel_total && localOffset < pixel_total) {
  4149. c = data[offset++];
  4150. count = (c & 0x7f) + 1;
  4151. // RLE pixels
  4152. if (c & 0x80) {
  4153. // Bind pixel tmp array
  4154. for (i = 0; i < pixel_size; ++i) {
  4155. pixels[i] = data[offset++];
  4156. }
  4157. // Copy pixel array
  4158. for (i = 0; i < count; ++i) {
  4159. pixel_data.set(pixels, localOffset + i * pixel_size);
  4160. }
  4161. localOffset += pixel_size * count;
  4162. }
  4163. else {
  4164. count *= pixel_size;
  4165. for (i = 0; i < count; ++i) {
  4166. pixel_data[localOffset + i] = data[offset++];
  4167. }
  4168. localOffset += count;
  4169. }
  4170. }
  4171. }
  4172. else {
  4173. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4174. }
  4175. // Load to texture
  4176. var x_start, y_start, x_step, y_step, y_end, x_end;
  4177. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4178. default:
  4179. case TGATools._ORIGIN_UL:
  4180. x_start = 0;
  4181. x_step = 1;
  4182. x_end = header.width;
  4183. y_start = 0;
  4184. y_step = 1;
  4185. y_end = header.height;
  4186. break;
  4187. case TGATools._ORIGIN_BL:
  4188. x_start = 0;
  4189. x_step = 1;
  4190. x_end = header.width;
  4191. y_start = header.height - 1;
  4192. y_step = -1;
  4193. y_end = -1;
  4194. break;
  4195. case TGATools._ORIGIN_UR:
  4196. x_start = header.width - 1;
  4197. x_step = -1;
  4198. x_end = -1;
  4199. y_start = 0;
  4200. y_step = 1;
  4201. y_end = header.height;
  4202. break;
  4203. case TGATools._ORIGIN_BR:
  4204. x_start = header.width - 1;
  4205. x_step = -1;
  4206. x_end = -1;
  4207. y_start = header.height - 1;
  4208. y_step = -1;
  4209. y_end = -1;
  4210. break;
  4211. }
  4212. // Load the specify method
  4213. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4214. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4215. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4216. };
  4217. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4218. var image = pixel_data, colormap = palettes;
  4219. var width = header.width, height = header.height;
  4220. var color, i = 0, x, y;
  4221. var imageData = new Uint8Array(width * height * 4);
  4222. for (y = y_start; y !== y_end; y += y_step) {
  4223. for (x = x_start; x !== x_end; x += x_step, i++) {
  4224. color = image[i];
  4225. imageData[(x + width * y) * 4 + 3] = 255;
  4226. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4227. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4228. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4229. }
  4230. }
  4231. return imageData;
  4232. };
  4233. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4234. var image = pixel_data;
  4235. var width = header.width, height = header.height;
  4236. var color, i = 0, x, y;
  4237. var imageData = new Uint8Array(width * height * 4);
  4238. for (y = y_start; y !== y_end; y += y_step) {
  4239. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4240. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4241. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4242. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4243. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4244. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4245. }
  4246. }
  4247. return imageData;
  4248. };
  4249. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4250. var image = pixel_data;
  4251. var width = header.width, height = header.height;
  4252. var i = 0, x, y;
  4253. var imageData = new Uint8Array(width * height * 4);
  4254. for (y = y_start; y !== y_end; y += y_step) {
  4255. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4256. imageData[(x + width * y) * 4 + 3] = 255;
  4257. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4258. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4259. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4260. }
  4261. }
  4262. return imageData;
  4263. };
  4264. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4265. var image = pixel_data;
  4266. var width = header.width, height = header.height;
  4267. var i = 0, x, y;
  4268. var imageData = new Uint8Array(width * height * 4);
  4269. for (y = y_start; y !== y_end; y += y_step) {
  4270. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4271. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4272. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4273. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4274. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4275. }
  4276. }
  4277. return imageData;
  4278. };
  4279. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4280. var image = pixel_data;
  4281. var width = header.width, height = header.height;
  4282. var color, i = 0, x, y;
  4283. var imageData = new Uint8Array(width * height * 4);
  4284. for (y = y_start; y !== y_end; y += y_step) {
  4285. for (x = x_start; x !== x_end; x += x_step, i++) {
  4286. color = image[i];
  4287. imageData[(x + width * y) * 4 + 0] = color;
  4288. imageData[(x + width * y) * 4 + 1] = color;
  4289. imageData[(x + width * y) * 4 + 2] = color;
  4290. imageData[(x + width * y) * 4 + 3] = 255;
  4291. }
  4292. }
  4293. return imageData;
  4294. };
  4295. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4296. var image = pixel_data;
  4297. var width = header.width, height = header.height;
  4298. var i = 0, x, y;
  4299. var imageData = new Uint8Array(width * height * 4);
  4300. for (y = y_start; y !== y_end; y += y_step) {
  4301. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4302. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4303. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4304. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4305. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4306. }
  4307. }
  4308. return imageData;
  4309. };
  4310. TGATools._TYPE_NO_DATA = 0;
  4311. TGATools._TYPE_INDEXED = 1;
  4312. TGATools._TYPE_RGB = 2;
  4313. TGATools._TYPE_GREY = 3;
  4314. TGATools._TYPE_RLE_INDEXED = 9;
  4315. TGATools._TYPE_RLE_RGB = 10;
  4316. TGATools._TYPE_RLE_GREY = 11;
  4317. TGATools._ORIGIN_MASK = 0x30;
  4318. TGATools._ORIGIN_SHIFT = 0x04;
  4319. TGATools._ORIGIN_BL = 0x00;
  4320. TGATools._ORIGIN_BR = 0x01;
  4321. TGATools._ORIGIN_UL = 0x02;
  4322. TGATools._ORIGIN_UR = 0x03;
  4323. return TGATools;
  4324. }());
  4325. Internals.TGATools = TGATools;
  4326. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4327. })(BABYLON || (BABYLON = {}));
  4328. var BABYLON;
  4329. (function (BABYLON) {
  4330. var SmartArray = (function () {
  4331. function SmartArray(capacity) {
  4332. this.length = 0;
  4333. this._duplicateId = 0;
  4334. this.data = new Array(capacity);
  4335. this._id = SmartArray._GlobalId++;
  4336. }
  4337. SmartArray.prototype.push = function (value) {
  4338. this.data[this.length++] = value;
  4339. if (this.length > this.data.length) {
  4340. this.data.length *= 2;
  4341. }
  4342. if (!value.__smartArrayFlags) {
  4343. value.__smartArrayFlags = {};
  4344. }
  4345. value.__smartArrayFlags[this._id] = this._duplicateId;
  4346. };
  4347. SmartArray.prototype.pushNoDuplicate = function (value) {
  4348. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4349. return false;
  4350. }
  4351. this.push(value);
  4352. return true;
  4353. };
  4354. SmartArray.prototype.sort = function (compareFn) {
  4355. this.data.sort(compareFn);
  4356. };
  4357. SmartArray.prototype.reset = function () {
  4358. this.length = 0;
  4359. this._duplicateId++;
  4360. };
  4361. SmartArray.prototype.concat = function (array) {
  4362. if (array.length === 0) {
  4363. return;
  4364. }
  4365. if (this.length + array.length > this.data.length) {
  4366. this.data.length = (this.length + array.length) * 2;
  4367. }
  4368. for (var index = 0; index < array.length; index++) {
  4369. this.data[this.length++] = (array.data || array)[index];
  4370. }
  4371. };
  4372. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4373. if (array.length === 0) {
  4374. return;
  4375. }
  4376. if (this.length + array.length > this.data.length) {
  4377. this.data.length = (this.length + array.length) * 2;
  4378. }
  4379. for (var index = 0; index < array.length; index++) {
  4380. var item = (array.data || array)[index];
  4381. this.pushNoDuplicate(item);
  4382. }
  4383. };
  4384. SmartArray.prototype.indexOf = function (value) {
  4385. var position = this.data.indexOf(value);
  4386. if (position >= this.length) {
  4387. return -1;
  4388. }
  4389. return position;
  4390. };
  4391. // Statics
  4392. SmartArray._GlobalId = 0;
  4393. return SmartArray;
  4394. }());
  4395. BABYLON.SmartArray = SmartArray;
  4396. })(BABYLON || (BABYLON = {}));
  4397. var BABYLON;
  4398. (function (BABYLON) {
  4399. /**
  4400. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4401. * The underlying implementation relies on an associative array to ensure the best performances.
  4402. * The value can be anything including 'null' but except 'undefined'
  4403. */
  4404. var StringDictionary = (function () {
  4405. function StringDictionary() {
  4406. this._count = 0;
  4407. this._data = {};
  4408. }
  4409. /**
  4410. * This will clear this dictionary and copy the content from the 'source' one.
  4411. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4412. * @param source the dictionary to take the content from and copy to this dictionary
  4413. */
  4414. StringDictionary.prototype.copyFrom = function (source) {
  4415. var _this = this;
  4416. this.clear();
  4417. source.forEach(function (t, v) { return _this.add(t, v); });
  4418. };
  4419. /**
  4420. * Get a value based from its key
  4421. * @param key the given key to get the matching value from
  4422. * @return the value if found, otherwise undefined is returned
  4423. */
  4424. StringDictionary.prototype.get = function (key) {
  4425. var val = this._data[key];
  4426. if (val !== undefined) {
  4427. return val;
  4428. }
  4429. return undefined;
  4430. };
  4431. /**
  4432. * Get a value from its key or add it if it doesn't exist.
  4433. * This method will ensure you that a given key/data will be present in the dictionary.
  4434. * @param key the given key to get the matching value from
  4435. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4436. * The factory will only be invoked if there's no data for the given key.
  4437. * @return the value corresponding to the key.
  4438. */
  4439. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4440. var val = this.get(key);
  4441. if (val !== undefined) {
  4442. return val;
  4443. }
  4444. val = factory(key);
  4445. if (val) {
  4446. this.add(key, val);
  4447. }
  4448. return val;
  4449. };
  4450. /**
  4451. * Get a value from its key if present in the dictionary otherwise add it
  4452. * @param key the key to get the value from
  4453. * @param val if there's no such key/value pair in the dictionary add it with this value
  4454. * @return the value corresponding to the key
  4455. */
  4456. StringDictionary.prototype.getOrAdd = function (key, val) {
  4457. var curVal = this.get(key);
  4458. if (curVal !== undefined) {
  4459. return curVal;
  4460. }
  4461. this.add(key, val);
  4462. return val;
  4463. };
  4464. /**
  4465. * Check if there's a given key in the dictionary
  4466. * @param key the key to check for
  4467. * @return true if the key is present, false otherwise
  4468. */
  4469. StringDictionary.prototype.contains = function (key) {
  4470. return this._data[key] !== undefined;
  4471. };
  4472. /**
  4473. * Add a new key and its corresponding value
  4474. * @param key the key to add
  4475. * @param value the value corresponding to the key
  4476. * @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
  4477. */
  4478. StringDictionary.prototype.add = function (key, value) {
  4479. if (this._data[key] !== undefined) {
  4480. return false;
  4481. }
  4482. this._data[key] = value;
  4483. ++this._count;
  4484. return true;
  4485. };
  4486. StringDictionary.prototype.set = function (key, value) {
  4487. if (this._data[key] === undefined) {
  4488. return false;
  4489. }
  4490. this._data[key] = value;
  4491. return true;
  4492. };
  4493. /**
  4494. * Get the element of the given key and remove it from the dictionary
  4495. * @param key
  4496. */
  4497. StringDictionary.prototype.getAndRemove = function (key) {
  4498. var val = this.get(key);
  4499. if (val !== undefined) {
  4500. delete this._data[key];
  4501. --this._count;
  4502. return val;
  4503. }
  4504. return null;
  4505. };
  4506. /**
  4507. * Remove a key/value from the dictionary.
  4508. * @param key the key to remove
  4509. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4510. */
  4511. StringDictionary.prototype.remove = function (key) {
  4512. if (this.contains(key)) {
  4513. delete this._data[key];
  4514. --this._count;
  4515. return true;
  4516. }
  4517. return false;
  4518. };
  4519. /**
  4520. * Clear the whole content of the dictionary
  4521. */
  4522. StringDictionary.prototype.clear = function () {
  4523. this._data = {};
  4524. this._count = 0;
  4525. };
  4526. Object.defineProperty(StringDictionary.prototype, "count", {
  4527. get: function () {
  4528. return this._count;
  4529. },
  4530. enumerable: true,
  4531. configurable: true
  4532. });
  4533. /**
  4534. * Execute a callback on each key/val of the dictionary.
  4535. * Note that you can remove any element in this dictionary in the callback implementation
  4536. * @param callback the callback to execute on a given key/value pair
  4537. */
  4538. StringDictionary.prototype.forEach = function (callback) {
  4539. for (var cur in this._data) {
  4540. var val = this._data[cur];
  4541. callback(cur, val);
  4542. }
  4543. };
  4544. /**
  4545. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4546. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4547. * Note that you can remove any element in this dictionary in the callback implementation
  4548. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4549. */
  4550. StringDictionary.prototype.first = function (callback) {
  4551. for (var cur in this._data) {
  4552. var val = this._data[cur];
  4553. var res = callback(cur, val);
  4554. if (res) {
  4555. return res;
  4556. }
  4557. }
  4558. return null;
  4559. };
  4560. return StringDictionary;
  4561. }());
  4562. BABYLON.StringDictionary = StringDictionary;
  4563. })(BABYLON || (BABYLON = {}));
  4564. var BABYLON;
  4565. (function (BABYLON) {
  4566. // Screenshots
  4567. var screenshotCanvas;
  4568. var cloneValue = function (source, destinationObject) {
  4569. if (!source)
  4570. return null;
  4571. if (source instanceof BABYLON.Mesh) {
  4572. return null;
  4573. }
  4574. if (source instanceof BABYLON.SubMesh) {
  4575. return source.clone(destinationObject);
  4576. }
  4577. else if (source.clone) {
  4578. return source.clone();
  4579. }
  4580. return null;
  4581. };
  4582. var Tools = (function () {
  4583. function Tools() {
  4584. }
  4585. Tools.Instantiate = function (className) {
  4586. var arr = className.split(".");
  4587. var fn = (window || this);
  4588. for (var i = 0, len = arr.length; i < len; i++) {
  4589. fn = fn[arr[i]];
  4590. }
  4591. if (typeof fn !== "function") {
  4592. return null;
  4593. }
  4594. return fn;
  4595. };
  4596. Tools.SetImmediate = function (action) {
  4597. if (window.setImmediate) {
  4598. window.setImmediate(action);
  4599. }
  4600. else {
  4601. setTimeout(action, 1);
  4602. }
  4603. };
  4604. Tools.IsExponentOfTwo = function (value) {
  4605. var count = 1;
  4606. do {
  4607. count *= 2;
  4608. } while (count < value);
  4609. return count === value;
  4610. };
  4611. Tools.GetExponentOfTwo = function (value, max) {
  4612. var count = 1;
  4613. do {
  4614. count *= 2;
  4615. } while (count < value);
  4616. if (count > max)
  4617. count = max;
  4618. return count;
  4619. };
  4620. Tools.GetFilename = function (path) {
  4621. var index = path.lastIndexOf("/");
  4622. if (index < 0)
  4623. return path;
  4624. return path.substring(index + 1);
  4625. };
  4626. Tools.GetDOMTextContent = function (element) {
  4627. var result = "";
  4628. var child = element.firstChild;
  4629. while (child) {
  4630. if (child.nodeType === 3) {
  4631. result += child.textContent;
  4632. }
  4633. child = child.nextSibling;
  4634. }
  4635. return result;
  4636. };
  4637. Tools.ToDegrees = function (angle) {
  4638. return angle * 180 / Math.PI;
  4639. };
  4640. Tools.ToRadians = function (angle) {
  4641. return angle * Math.PI / 180;
  4642. };
  4643. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4644. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4645. var output = "";
  4646. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4647. var i = 0;
  4648. var bytes = new Uint8Array(buffer);
  4649. while (i < bytes.length) {
  4650. chr1 = bytes[i++];
  4651. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4652. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4653. enc1 = chr1 >> 2;
  4654. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4655. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4656. enc4 = chr3 & 63;
  4657. if (isNaN(chr2)) {
  4658. enc3 = enc4 = 64;
  4659. }
  4660. else if (isNaN(chr3)) {
  4661. enc4 = 64;
  4662. }
  4663. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4664. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4665. }
  4666. return "data:image/png;base64," + output;
  4667. };
  4668. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4669. if (bias === void 0) { bias = null; }
  4670. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4671. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4672. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4673. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4674. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4675. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4676. }
  4677. if (bias) {
  4678. minimum.x -= minimum.x * bias.x + bias.y;
  4679. minimum.y -= minimum.y * bias.x + bias.y;
  4680. minimum.z -= minimum.z * bias.x + bias.y;
  4681. maximum.x += maximum.x * bias.x + bias.y;
  4682. maximum.y += maximum.y * bias.x + bias.y;
  4683. maximum.z += maximum.z * bias.x + bias.y;
  4684. }
  4685. return {
  4686. minimum: minimum,
  4687. maximum: maximum
  4688. };
  4689. };
  4690. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4691. if (bias === void 0) { bias = null; }
  4692. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4693. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4694. if (!stride) {
  4695. stride = 3;
  4696. }
  4697. for (var index = start; index < start + count; index++) {
  4698. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4699. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4700. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4701. }
  4702. if (bias) {
  4703. minimum.x -= minimum.x * bias.x + bias.y;
  4704. minimum.y -= minimum.y * bias.x + bias.y;
  4705. minimum.z -= minimum.z * bias.x + bias.y;
  4706. maximum.x += maximum.x * bias.x + bias.y;
  4707. maximum.y += maximum.y * bias.x + bias.y;
  4708. maximum.z += maximum.z * bias.x + bias.y;
  4709. }
  4710. return {
  4711. minimum: minimum,
  4712. maximum: maximum
  4713. };
  4714. };
  4715. Tools.Vector2ArrayFeeder = function (array) {
  4716. return function (index) {
  4717. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4718. var length = isFloatArray ? array.length / 2 : array.length;
  4719. if (index >= length) {
  4720. return null;
  4721. }
  4722. if (isFloatArray) {
  4723. var fa = array;
  4724. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4725. }
  4726. var a = array;
  4727. return a[index];
  4728. };
  4729. };
  4730. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4731. if (bias === void 0) { bias = null; }
  4732. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4733. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4734. var i = 0;
  4735. var cur = feeder(i++);
  4736. while (cur) {
  4737. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4738. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4739. cur = feeder(i++);
  4740. }
  4741. if (bias) {
  4742. minimum.x -= minimum.x * bias.x + bias.y;
  4743. minimum.y -= minimum.y * bias.x + bias.y;
  4744. maximum.x += maximum.x * bias.x + bias.y;
  4745. maximum.y += maximum.y * bias.x + bias.y;
  4746. }
  4747. return {
  4748. minimum: minimum,
  4749. maximum: maximum
  4750. };
  4751. };
  4752. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4753. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4754. return undefined;
  4755. return Array.isArray(obj) ? obj : [obj];
  4756. };
  4757. // Misc.
  4758. Tools.GetPointerPrefix = function () {
  4759. var eventPrefix = "pointer";
  4760. // Check if pointer events are supported
  4761. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4762. eventPrefix = "mouse";
  4763. }
  4764. return eventPrefix;
  4765. };
  4766. /**
  4767. * @param func - the function to be called
  4768. * @param requester - the object that will request the next frame. Falls back to window.
  4769. */
  4770. Tools.QueueNewFrame = function (func, requester) {
  4771. if (requester === void 0) { requester = window; }
  4772. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4773. /*if(requester.isPresenting) {
  4774. return;
  4775. } else*/ if (requester.requestAnimationFrame)
  4776. requester.requestAnimationFrame(func);
  4777. else if (requester.msRequestAnimationFrame)
  4778. requester.msRequestAnimationFrame(func);
  4779. else if (requester.webkitRequestAnimationFrame)
  4780. requester.webkitRequestAnimationFrame(func);
  4781. else if (requester.mozRequestAnimationFrame)
  4782. requester.mozRequestAnimationFrame(func);
  4783. else if (requester.oRequestAnimationFrame)
  4784. requester.oRequestAnimationFrame(func);
  4785. else {
  4786. window.setTimeout(func, 16);
  4787. }
  4788. };
  4789. Tools.RequestFullscreen = function (element) {
  4790. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4791. if (!requestFunction)
  4792. return;
  4793. requestFunction.call(element);
  4794. };
  4795. Tools.ExitFullscreen = function () {
  4796. if (document.exitFullscreen) {
  4797. document.exitFullscreen();
  4798. }
  4799. else if (document.mozCancelFullScreen) {
  4800. document.mozCancelFullScreen();
  4801. }
  4802. else if (document.webkitCancelFullScreen) {
  4803. document.webkitCancelFullScreen();
  4804. }
  4805. else if (document.msCancelFullScreen) {
  4806. document.msCancelFullScreen();
  4807. }
  4808. };
  4809. Tools.SetCorsBehavior = function (url, img) {
  4810. if (Tools.CorsBehavior) {
  4811. switch (typeof (Tools.CorsBehavior)) {
  4812. case "function":
  4813. var result = Tools.CorsBehavior(url);
  4814. if (result) {
  4815. return result;
  4816. }
  4817. break;
  4818. case "string":
  4819. default:
  4820. img.crossOrigin = Tools.CorsBehavior;
  4821. break;
  4822. }
  4823. }
  4824. };
  4825. // External files
  4826. Tools.CleanUrl = function (url) {
  4827. url = url.replace(/#/mg, "%23");
  4828. return url;
  4829. };
  4830. Tools.LoadImage = function (url, onload, onerror, database) {
  4831. if (url instanceof ArrayBuffer) {
  4832. url = Tools.EncodeArrayBufferTobase64(url);
  4833. }
  4834. url = Tools.CleanUrl(url);
  4835. var img = new Image();
  4836. if (url.substr(0, 5) !== "data:") {
  4837. Tools.SetCorsBehavior(url, img);
  4838. }
  4839. img.onload = function () {
  4840. onload(img);
  4841. };
  4842. img.onerror = function (err) {
  4843. Tools.Error("Error while trying to load texture: " + url);
  4844. if (Tools.UseFallbackTexture) {
  4845. 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";
  4846. onload(img);
  4847. }
  4848. else {
  4849. onerror();
  4850. }
  4851. };
  4852. var noIndexedDB = function () {
  4853. img.src = url;
  4854. };
  4855. var loadFromIndexedDB = function () {
  4856. database.loadImageFromDB(url, img);
  4857. };
  4858. //ANY database to do!
  4859. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4860. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4861. }
  4862. else {
  4863. if (url.indexOf("file:") === -1) {
  4864. noIndexedDB();
  4865. }
  4866. else {
  4867. try {
  4868. var textureName = url.substring(5).toLowerCase();
  4869. var blobURL;
  4870. try {
  4871. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4872. }
  4873. catch (ex) {
  4874. // Chrome doesn't support oneTimeOnly parameter
  4875. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4876. }
  4877. img.src = blobURL;
  4878. }
  4879. catch (e) {
  4880. img.src = null;
  4881. }
  4882. }
  4883. }
  4884. return img;
  4885. };
  4886. //ANY
  4887. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4888. url = Tools.CleanUrl(url);
  4889. var noIndexedDB = function () {
  4890. var request = new XMLHttpRequest();
  4891. var loadUrl = Tools.BaseUrl + url;
  4892. request.open('GET', loadUrl, true);
  4893. if (useArrayBuffer) {
  4894. request.responseType = "arraybuffer";
  4895. }
  4896. request.onprogress = progressCallBack;
  4897. request.onreadystatechange = function () {
  4898. if (request.readyState === 4) {
  4899. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4900. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4901. callback(!useArrayBuffer ? request.responseText : request.response);
  4902. }
  4903. else {
  4904. if (onError) {
  4905. onError();
  4906. }
  4907. else {
  4908. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4909. }
  4910. }
  4911. }
  4912. };
  4913. request.send(null);
  4914. };
  4915. var loadFromIndexedDB = function () {
  4916. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4917. };
  4918. if (url.indexOf("file:") !== -1) {
  4919. var fileName = url.substring(5).toLowerCase();
  4920. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4921. }
  4922. else {
  4923. // Caching all files
  4924. if (database && database.enableSceneOffline) {
  4925. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4926. }
  4927. else {
  4928. noIndexedDB();
  4929. }
  4930. }
  4931. };
  4932. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  4933. var reader = new FileReader();
  4934. reader.onload = function (e) {
  4935. //target doesn't have result from ts 1.3
  4936. callback(e.target['result']);
  4937. };
  4938. reader.onprogress = progressCallback;
  4939. reader.readAsDataURL(fileToLoad);
  4940. };
  4941. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  4942. var reader = new FileReader();
  4943. reader.onerror = function (e) {
  4944. Tools.Log("Error while reading file: " + fileToLoad.name);
  4945. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  4946. };
  4947. reader.onload = function (e) {
  4948. //target doesn't have result from ts 1.3
  4949. callback(e.target['result']);
  4950. };
  4951. reader.onprogress = progressCallBack;
  4952. if (!useArrayBuffer) {
  4953. // Asynchronous read
  4954. reader.readAsText(fileToLoad);
  4955. }
  4956. else {
  4957. reader.readAsArrayBuffer(fileToLoad);
  4958. }
  4959. };
  4960. //returns a downloadable url to a file content.
  4961. Tools.FileAsURL = function (content) {
  4962. var fileBlob = new Blob([content]);
  4963. var url = window.URL || window.webkitURL;
  4964. var link = url.createObjectURL(fileBlob);
  4965. return link;
  4966. };
  4967. // Misc.
  4968. Tools.Format = function (value, decimals) {
  4969. if (decimals === void 0) { decimals = 2; }
  4970. return value.toFixed(decimals);
  4971. };
  4972. Tools.CheckExtends = function (v, min, max) {
  4973. if (v.x < min.x)
  4974. min.x = v.x;
  4975. if (v.y < min.y)
  4976. min.y = v.y;
  4977. if (v.z < min.z)
  4978. min.z = v.z;
  4979. if (v.x > max.x)
  4980. max.x = v.x;
  4981. if (v.y > max.y)
  4982. max.y = v.y;
  4983. if (v.z > max.z)
  4984. max.z = v.z;
  4985. };
  4986. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  4987. for (var prop in source) {
  4988. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  4989. continue;
  4990. }
  4991. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  4992. continue;
  4993. }
  4994. var sourceValue = source[prop];
  4995. var typeOfSourceValue = typeof sourceValue;
  4996. if (typeOfSourceValue === "function") {
  4997. continue;
  4998. }
  4999. if (typeOfSourceValue === "object") {
  5000. if (sourceValue instanceof Array) {
  5001. destination[prop] = [];
  5002. if (sourceValue.length > 0) {
  5003. if (typeof sourceValue[0] == "object") {
  5004. for (var index = 0; index < sourceValue.length; index++) {
  5005. var clonedValue = cloneValue(sourceValue[index], destination);
  5006. if (destination[prop].indexOf(clonedValue) === -1) {
  5007. destination[prop].push(clonedValue);
  5008. }
  5009. }
  5010. }
  5011. else {
  5012. destination[prop] = sourceValue.slice(0);
  5013. }
  5014. }
  5015. }
  5016. else {
  5017. destination[prop] = cloneValue(sourceValue, destination);
  5018. }
  5019. }
  5020. else {
  5021. destination[prop] = sourceValue;
  5022. }
  5023. }
  5024. };
  5025. Tools.IsEmpty = function (obj) {
  5026. for (var i in obj) {
  5027. return false;
  5028. }
  5029. return true;
  5030. };
  5031. Tools.RegisterTopRootEvents = function (events) {
  5032. for (var index = 0; index < events.length; index++) {
  5033. var event = events[index];
  5034. window.addEventListener(event.name, event.handler, false);
  5035. try {
  5036. if (window.parent) {
  5037. window.parent.addEventListener(event.name, event.handler, false);
  5038. }
  5039. }
  5040. catch (e) {
  5041. }
  5042. }
  5043. };
  5044. Tools.UnregisterTopRootEvents = function (events) {
  5045. for (var index = 0; index < events.length; index++) {
  5046. var event = events[index];
  5047. window.removeEventListener(event.name, event.handler);
  5048. try {
  5049. if (window.parent) {
  5050. window.parent.removeEventListener(event.name, event.handler);
  5051. }
  5052. }
  5053. catch (e) {
  5054. }
  5055. }
  5056. };
  5057. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5058. if (mimeType === void 0) { mimeType = "image/png"; }
  5059. // Read the contents of the framebuffer
  5060. var numberOfChannelsByLine = width * 4;
  5061. var halfHeight = height / 2;
  5062. //Reading datas from WebGL
  5063. var data = engine.readPixels(0, 0, width, height);
  5064. //To flip image on Y axis.
  5065. for (var i = 0; i < halfHeight; i++) {
  5066. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5067. var currentCell = j + i * numberOfChannelsByLine;
  5068. var targetLine = height - i - 1;
  5069. var targetCell = j + targetLine * numberOfChannelsByLine;
  5070. var temp = data[currentCell];
  5071. data[currentCell] = data[targetCell];
  5072. data[targetCell] = temp;
  5073. }
  5074. }
  5075. // Create a 2D canvas to store the result
  5076. if (!screenshotCanvas) {
  5077. screenshotCanvas = document.createElement('canvas');
  5078. }
  5079. screenshotCanvas.width = width;
  5080. screenshotCanvas.height = height;
  5081. var context = screenshotCanvas.getContext('2d');
  5082. // Copy the pixels to a 2D canvas
  5083. var imageData = context.createImageData(width, height);
  5084. var castData = (imageData.data);
  5085. castData.set(data);
  5086. context.putImageData(imageData, 0, 0);
  5087. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5088. };
  5089. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5090. if (mimeType === void 0) { mimeType = "image/png"; }
  5091. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5092. if (successCallback) {
  5093. successCallback(base64Image);
  5094. }
  5095. else {
  5096. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5097. if (("download" in document.createElement("a"))) {
  5098. var a = window.document.createElement("a");
  5099. a.href = base64Image;
  5100. var date = new Date();
  5101. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5102. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5103. window.document.body.appendChild(a);
  5104. a.addEventListener("click", function () {
  5105. a.parentElement.removeChild(a);
  5106. });
  5107. a.click();
  5108. }
  5109. else {
  5110. var newWindow = window.open("");
  5111. var img = newWindow.document.createElement("img");
  5112. img.src = base64Image;
  5113. newWindow.document.body.appendChild(img);
  5114. }
  5115. }
  5116. };
  5117. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5118. if (mimeType === void 0) { mimeType = "image/png"; }
  5119. var width;
  5120. var height;
  5121. // If a precision value is specified
  5122. if (size.precision) {
  5123. width = Math.round(engine.getRenderWidth() * size.precision);
  5124. height = Math.round(width / engine.getAspectRatio(camera));
  5125. }
  5126. else if (size.width && size.height) {
  5127. width = size.width;
  5128. height = size.height;
  5129. }
  5130. else if (size.width && !size.height) {
  5131. width = size.width;
  5132. height = Math.round(width / engine.getAspectRatio(camera));
  5133. }
  5134. else if (size.height && !size.width) {
  5135. height = size.height;
  5136. width = Math.round(height * engine.getAspectRatio(camera));
  5137. }
  5138. else if (!isNaN(size)) {
  5139. height = size;
  5140. width = size;
  5141. }
  5142. else {
  5143. Tools.Error("Invalid 'size' parameter !");
  5144. return;
  5145. }
  5146. if (!screenshotCanvas) {
  5147. screenshotCanvas = document.createElement('canvas');
  5148. }
  5149. screenshotCanvas.width = width;
  5150. screenshotCanvas.height = height;
  5151. var renderContext = screenshotCanvas.getContext("2d");
  5152. renderContext.drawImage(engine.getRenderingCanvas(), 0, 0, width, height);
  5153. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5154. };
  5155. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5156. if (mimeType === void 0) { mimeType = "image/png"; }
  5157. var width;
  5158. var height;
  5159. //If a precision value is specified
  5160. if (size.precision) {
  5161. width = Math.round(engine.getRenderWidth() * size.precision);
  5162. height = Math.round(width / engine.getAspectRatio(camera));
  5163. size = { width: width, height: height };
  5164. }
  5165. else if (size.width && size.height) {
  5166. width = size.width;
  5167. height = size.height;
  5168. }
  5169. else if (size.width && !size.height) {
  5170. width = size.width;
  5171. height = Math.round(width / engine.getAspectRatio(camera));
  5172. size = { width: width, height: height };
  5173. }
  5174. else if (size.height && !size.width) {
  5175. height = size.height;
  5176. width = Math.round(height * engine.getAspectRatio(camera));
  5177. size = { width: width, height: height };
  5178. }
  5179. else if (!isNaN(size)) {
  5180. height = size;
  5181. width = size;
  5182. }
  5183. else {
  5184. Tools.Error("Invalid 'size' parameter !");
  5185. return;
  5186. }
  5187. var scene = camera.getScene();
  5188. var previousCamera = null;
  5189. if (scene.activeCamera !== camera) {
  5190. previousCamera = scene.activeCamera;
  5191. scene.activeCamera = camera;
  5192. }
  5193. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5194. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false);
  5195. texture.renderList = scene.meshes;
  5196. texture.onAfterRenderObservable.add(function () {
  5197. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5198. });
  5199. scene.incrementRenderId();
  5200. scene.resetCachedMaterial();
  5201. texture.render(true);
  5202. texture.dispose();
  5203. if (previousCamera) {
  5204. scene.activeCamera = previousCamera;
  5205. }
  5206. camera.getProjectionMatrix(true); // Force cache refresh;
  5207. };
  5208. // XHR response validator for local file scenario
  5209. Tools.ValidateXHRData = function (xhr, dataType) {
  5210. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5211. if (dataType === void 0) { dataType = 7; }
  5212. try {
  5213. if (dataType & 1) {
  5214. if (xhr.responseText && xhr.responseText.length > 0) {
  5215. return true;
  5216. }
  5217. else if (dataType === 1) {
  5218. return false;
  5219. }
  5220. }
  5221. if (dataType & 2) {
  5222. // Check header width and height since there is no "TGA" magic number
  5223. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5224. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5225. return true;
  5226. }
  5227. else if (dataType === 2) {
  5228. return false;
  5229. }
  5230. }
  5231. if (dataType & 4) {
  5232. // Check for the "DDS" magic number
  5233. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5234. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5235. return true;
  5236. }
  5237. else {
  5238. return false;
  5239. }
  5240. }
  5241. }
  5242. catch (e) {
  5243. }
  5244. return false;
  5245. };
  5246. /**
  5247. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5248. * Be aware Math.random() could cause collisions, but:
  5249. * "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"
  5250. */
  5251. Tools.RandomId = function () {
  5252. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5253. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5254. return v.toString(16);
  5255. });
  5256. };
  5257. Object.defineProperty(Tools, "NoneLogLevel", {
  5258. get: function () {
  5259. return Tools._NoneLogLevel;
  5260. },
  5261. enumerable: true,
  5262. configurable: true
  5263. });
  5264. Object.defineProperty(Tools, "MessageLogLevel", {
  5265. get: function () {
  5266. return Tools._MessageLogLevel;
  5267. },
  5268. enumerable: true,
  5269. configurable: true
  5270. });
  5271. Object.defineProperty(Tools, "WarningLogLevel", {
  5272. get: function () {
  5273. return Tools._WarningLogLevel;
  5274. },
  5275. enumerable: true,
  5276. configurable: true
  5277. });
  5278. Object.defineProperty(Tools, "ErrorLogLevel", {
  5279. get: function () {
  5280. return Tools._ErrorLogLevel;
  5281. },
  5282. enumerable: true,
  5283. configurable: true
  5284. });
  5285. Object.defineProperty(Tools, "AllLogLevel", {
  5286. get: function () {
  5287. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5288. },
  5289. enumerable: true,
  5290. configurable: true
  5291. });
  5292. Tools._AddLogEntry = function (entry) {
  5293. Tools._LogCache = entry + Tools._LogCache;
  5294. if (Tools.OnNewCacheEntry) {
  5295. Tools.OnNewCacheEntry(entry);
  5296. }
  5297. };
  5298. Tools._FormatMessage = function (message) {
  5299. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5300. var date = new Date();
  5301. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5302. };
  5303. Tools._LogDisabled = function (message) {
  5304. // nothing to do
  5305. };
  5306. Tools._LogEnabled = function (message) {
  5307. var formattedMessage = Tools._FormatMessage(message);
  5308. console.log("BJS - " + formattedMessage);
  5309. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5310. Tools._AddLogEntry(entry);
  5311. };
  5312. Tools._WarnDisabled = function (message) {
  5313. // nothing to do
  5314. };
  5315. Tools._WarnEnabled = function (message) {
  5316. var formattedMessage = Tools._FormatMessage(message);
  5317. console.warn("BJS - " + formattedMessage);
  5318. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5319. Tools._AddLogEntry(entry);
  5320. };
  5321. Tools._ErrorDisabled = function (message) {
  5322. // nothing to do
  5323. };
  5324. Tools._ErrorEnabled = function (message) {
  5325. Tools.errorsCount++;
  5326. var formattedMessage = Tools._FormatMessage(message);
  5327. console.error("BJS - " + formattedMessage);
  5328. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5329. Tools._AddLogEntry(entry);
  5330. };
  5331. Object.defineProperty(Tools, "LogCache", {
  5332. get: function () {
  5333. return Tools._LogCache;
  5334. },
  5335. enumerable: true,
  5336. configurable: true
  5337. });
  5338. Tools.ClearLogCache = function () {
  5339. Tools._LogCache = "";
  5340. Tools.errorsCount = 0;
  5341. };
  5342. Object.defineProperty(Tools, "LogLevels", {
  5343. set: function (level) {
  5344. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5345. Tools.Log = Tools._LogEnabled;
  5346. }
  5347. else {
  5348. Tools.Log = Tools._LogDisabled;
  5349. }
  5350. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5351. Tools.Warn = Tools._WarnEnabled;
  5352. }
  5353. else {
  5354. Tools.Warn = Tools._WarnDisabled;
  5355. }
  5356. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5357. Tools.Error = Tools._ErrorEnabled;
  5358. }
  5359. else {
  5360. Tools.Error = Tools._ErrorDisabled;
  5361. }
  5362. },
  5363. enumerable: true,
  5364. configurable: true
  5365. });
  5366. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5367. get: function () {
  5368. return Tools._PerformanceNoneLogLevel;
  5369. },
  5370. enumerable: true,
  5371. configurable: true
  5372. });
  5373. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5374. get: function () {
  5375. return Tools._PerformanceUserMarkLogLevel;
  5376. },
  5377. enumerable: true,
  5378. configurable: true
  5379. });
  5380. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5381. get: function () {
  5382. return Tools._PerformanceConsoleLogLevel;
  5383. },
  5384. enumerable: true,
  5385. configurable: true
  5386. });
  5387. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5388. set: function (level) {
  5389. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5390. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5391. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5392. return;
  5393. }
  5394. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5395. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5396. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5397. return;
  5398. }
  5399. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5400. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5401. },
  5402. enumerable: true,
  5403. configurable: true
  5404. });
  5405. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5406. };
  5407. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5408. };
  5409. Tools._StartUserMark = function (counterName, condition) {
  5410. if (condition === void 0) { condition = true; }
  5411. if (!condition || !Tools._performance.mark) {
  5412. return;
  5413. }
  5414. Tools._performance.mark(counterName + "-Begin");
  5415. };
  5416. Tools._EndUserMark = function (counterName, condition) {
  5417. if (condition === void 0) { condition = true; }
  5418. if (!condition || !Tools._performance.mark) {
  5419. return;
  5420. }
  5421. Tools._performance.mark(counterName + "-End");
  5422. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5423. };
  5424. Tools._StartPerformanceConsole = function (counterName, condition) {
  5425. if (condition === void 0) { condition = true; }
  5426. if (!condition) {
  5427. return;
  5428. }
  5429. Tools._StartUserMark(counterName, condition);
  5430. if (console.time) {
  5431. console.time(counterName);
  5432. }
  5433. };
  5434. Tools._EndPerformanceConsole = function (counterName, condition) {
  5435. if (condition === void 0) { condition = true; }
  5436. if (!condition) {
  5437. return;
  5438. }
  5439. Tools._EndUserMark(counterName, condition);
  5440. if (console.time) {
  5441. console.timeEnd(counterName);
  5442. }
  5443. };
  5444. Object.defineProperty(Tools, "Now", {
  5445. get: function () {
  5446. if (window.performance && window.performance.now) {
  5447. return window.performance.now();
  5448. }
  5449. return new Date().getTime();
  5450. },
  5451. enumerable: true,
  5452. configurable: true
  5453. });
  5454. /**
  5455. * This method will return the name of the class used to create the instance of the given object.
  5456. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5457. * @param object the object to get the class name from
  5458. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5459. */
  5460. Tools.getClassName = function (object, isType) {
  5461. if (isType === void 0) { isType = false; }
  5462. var name = null;
  5463. if (!isType && object.getClassName) {
  5464. name = object.getClassName();
  5465. }
  5466. else {
  5467. if (object instanceof Object) {
  5468. var classObj = isType ? object : Object.getPrototypeOf(object);
  5469. name = classObj.constructor["__bjsclassName__"];
  5470. }
  5471. if (!name) {
  5472. name = typeof object;
  5473. }
  5474. }
  5475. return name;
  5476. };
  5477. Tools.first = function (array, predicate) {
  5478. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5479. var el = array_1[_i];
  5480. if (predicate(el)) {
  5481. return el;
  5482. }
  5483. }
  5484. };
  5485. /**
  5486. * This method will return the name of the full name of the class, including its owning module (if any).
  5487. * 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).
  5488. * @param object the object to get the class name from
  5489. * @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.
  5490. */
  5491. Tools.getFullClassName = function (object, isType) {
  5492. if (isType === void 0) { isType = false; }
  5493. var className = null;
  5494. var moduleName = null;
  5495. if (!isType && object.getClassName) {
  5496. className = object.getClassName();
  5497. }
  5498. else {
  5499. if (object instanceof Object) {
  5500. var classObj = isType ? object : Object.getPrototypeOf(object);
  5501. className = classObj.constructor["__bjsclassName__"];
  5502. moduleName = classObj.constructor["__bjsmoduleName__"];
  5503. }
  5504. if (!className) {
  5505. className = typeof object;
  5506. }
  5507. }
  5508. if (!className) {
  5509. return null;
  5510. }
  5511. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5512. };
  5513. /**
  5514. * 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.
  5515. * @param array
  5516. */
  5517. Tools.arrayOrStringFeeder = function (array) {
  5518. return function (index) {
  5519. if (index >= array.length) {
  5520. return null;
  5521. }
  5522. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5523. if (val && val.getHashCode) {
  5524. val = val.getHashCode();
  5525. }
  5526. if (typeof val === "string") {
  5527. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5528. }
  5529. return val;
  5530. };
  5531. };
  5532. /**
  5533. * Compute the hashCode of a stream of number
  5534. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5535. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5536. * @return the hash code computed
  5537. */
  5538. Tools.hashCodeFromStream = function (feeder) {
  5539. // Based from here: http://stackoverflow.com/a/7616484/802124
  5540. var hash = 0;
  5541. var index = 0;
  5542. var chr = feeder(index++);
  5543. while (chr != null) {
  5544. hash = ((hash << 5) - hash) + chr;
  5545. hash |= 0; // Convert to 32bit integer
  5546. chr = feeder(index++);
  5547. }
  5548. return hash;
  5549. };
  5550. Tools.BaseUrl = "";
  5551. Tools.CorsBehavior = "anonymous";
  5552. Tools.UseFallbackTexture = true;
  5553. // Logs
  5554. Tools._NoneLogLevel = 0;
  5555. Tools._MessageLogLevel = 1;
  5556. Tools._WarningLogLevel = 2;
  5557. Tools._ErrorLogLevel = 4;
  5558. Tools._LogCache = "";
  5559. Tools.errorsCount = 0;
  5560. Tools.Log = Tools._LogEnabled;
  5561. Tools.Warn = Tools._WarnEnabled;
  5562. Tools.Error = Tools._ErrorEnabled;
  5563. // Performances
  5564. Tools._PerformanceNoneLogLevel = 0;
  5565. Tools._PerformanceUserMarkLogLevel = 1;
  5566. Tools._PerformanceConsoleLogLevel = 2;
  5567. Tools._performance = window.performance;
  5568. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5569. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5570. return Tools;
  5571. }());
  5572. BABYLON.Tools = Tools;
  5573. /**
  5574. * This class is used to track a performance counter which is number based.
  5575. * The user has access to many properties which give statistics of different nature
  5576. *
  5577. * The implementer can track two kinds of Performance Counter: time and count
  5578. * 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.
  5579. * 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.
  5580. */
  5581. var PerfCounter = (function () {
  5582. function PerfCounter() {
  5583. this._startMonitoringTime = 0;
  5584. this._min = 0;
  5585. this._max = 0;
  5586. this._average = 0;
  5587. this._lastSecAverage = 0;
  5588. this._current = 0;
  5589. this._totalValueCount = 0;
  5590. this._totalAccumulated = 0;
  5591. this._lastSecAccumulated = 0;
  5592. this._lastSecTime = 0;
  5593. this._lastSecValueCount = 0;
  5594. }
  5595. Object.defineProperty(PerfCounter.prototype, "min", {
  5596. /**
  5597. * Returns the smallest value ever
  5598. */
  5599. get: function () {
  5600. return this._min;
  5601. },
  5602. enumerable: true,
  5603. configurable: true
  5604. });
  5605. Object.defineProperty(PerfCounter.prototype, "max", {
  5606. /**
  5607. * Returns the biggest value ever
  5608. */
  5609. get: function () {
  5610. return this._max;
  5611. },
  5612. enumerable: true,
  5613. configurable: true
  5614. });
  5615. Object.defineProperty(PerfCounter.prototype, "average", {
  5616. /**
  5617. * Returns the average value since the performance counter is running
  5618. */
  5619. get: function () {
  5620. return this._average;
  5621. },
  5622. enumerable: true,
  5623. configurable: true
  5624. });
  5625. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5626. /**
  5627. * Returns the average value of the last second the counter was monitored
  5628. */
  5629. get: function () {
  5630. return this._lastSecAverage;
  5631. },
  5632. enumerable: true,
  5633. configurable: true
  5634. });
  5635. Object.defineProperty(PerfCounter.prototype, "current", {
  5636. /**
  5637. * Returns the current value
  5638. */
  5639. get: function () {
  5640. return this._current;
  5641. },
  5642. enumerable: true,
  5643. configurable: true
  5644. });
  5645. Object.defineProperty(PerfCounter.prototype, "total", {
  5646. get: function () {
  5647. return this._totalAccumulated;
  5648. },
  5649. enumerable: true,
  5650. configurable: true
  5651. });
  5652. /**
  5653. * Call this method to start monitoring a new frame.
  5654. * 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.
  5655. */
  5656. PerfCounter.prototype.fetchNewFrame = function () {
  5657. this._totalValueCount++;
  5658. this._current = 0;
  5659. this._lastSecValueCount++;
  5660. };
  5661. /**
  5662. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5663. * @param newCount the count value to add to the monitored count
  5664. * @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.
  5665. */
  5666. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5667. this._current += newCount;
  5668. if (fetchResult) {
  5669. this._fetchResult();
  5670. }
  5671. };
  5672. /**
  5673. * Start monitoring this performance counter
  5674. */
  5675. PerfCounter.prototype.beginMonitoring = function () {
  5676. this._startMonitoringTime = Tools.Now;
  5677. };
  5678. /**
  5679. * Compute the time lapsed since the previous beginMonitoring() call.
  5680. * @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
  5681. */
  5682. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5683. if (newFrame === void 0) { newFrame = true; }
  5684. if (newFrame) {
  5685. this.fetchNewFrame();
  5686. }
  5687. var currentTime = Tools.Now;
  5688. this._current = currentTime - this._startMonitoringTime;
  5689. if (newFrame) {
  5690. this._fetchResult();
  5691. }
  5692. };
  5693. PerfCounter.prototype._fetchResult = function () {
  5694. this._totalAccumulated += this._current;
  5695. this._lastSecAccumulated += this._current;
  5696. // Min/Max update
  5697. this._min = Math.min(this._min, this._current);
  5698. this._max = Math.max(this._max, this._current);
  5699. this._average = this._totalAccumulated / this._totalValueCount;
  5700. // Reset last sec?
  5701. var now = Tools.Now;
  5702. if ((now - this._lastSecTime) > 1000) {
  5703. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5704. this._lastSecTime = now;
  5705. this._lastSecAccumulated = 0;
  5706. this._lastSecValueCount = 0;
  5707. }
  5708. };
  5709. return PerfCounter;
  5710. }());
  5711. BABYLON.PerfCounter = PerfCounter;
  5712. /**
  5713. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5714. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5715. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5716. * @param name The name of the class, case should be preserved
  5717. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5718. */
  5719. function className(name, module) {
  5720. return function (target) {
  5721. target["__bjsclassName__"] = name;
  5722. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5723. };
  5724. }
  5725. BABYLON.className = className;
  5726. /**
  5727. * An implementation of a loop for asynchronous functions.
  5728. */
  5729. var AsyncLoop = (function () {
  5730. /**
  5731. * Constroctor.
  5732. * @param iterations the number of iterations.
  5733. * @param _fn the function to run each iteration
  5734. * @param _successCallback the callback that will be called upon succesful execution
  5735. * @param offset starting offset.
  5736. */
  5737. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5738. if (offset === void 0) { offset = 0; }
  5739. this.iterations = iterations;
  5740. this._fn = _fn;
  5741. this._successCallback = _successCallback;
  5742. this.index = offset - 1;
  5743. this._done = false;
  5744. }
  5745. /**
  5746. * Execute the next iteration. Must be called after the last iteration was finished.
  5747. */
  5748. AsyncLoop.prototype.executeNext = function () {
  5749. if (!this._done) {
  5750. if (this.index + 1 < this.iterations) {
  5751. ++this.index;
  5752. this._fn(this);
  5753. }
  5754. else {
  5755. this.breakLoop();
  5756. }
  5757. }
  5758. };
  5759. /**
  5760. * Break the loop and run the success callback.
  5761. */
  5762. AsyncLoop.prototype.breakLoop = function () {
  5763. this._done = true;
  5764. this._successCallback();
  5765. };
  5766. /**
  5767. * Helper function
  5768. */
  5769. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5770. if (offset === void 0) { offset = 0; }
  5771. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5772. loop.executeNext();
  5773. return loop;
  5774. };
  5775. /**
  5776. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5777. * @param iterations total number of iterations
  5778. * @param syncedIterations number of synchronous iterations in each async iteration.
  5779. * @param fn the function to call each iteration.
  5780. * @param callback a success call back that will be called when iterating stops.
  5781. * @param breakFunction a break condition (optional)
  5782. * @param timeout timeout settings for the setTimeout function. default - 0.
  5783. * @constructor
  5784. */
  5785. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5786. if (timeout === void 0) { timeout = 0; }
  5787. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5788. if (breakFunction && breakFunction())
  5789. loop.breakLoop();
  5790. else {
  5791. setTimeout(function () {
  5792. for (var i = 0; i < syncedIterations; ++i) {
  5793. var iteration = (loop.index * syncedIterations) + i;
  5794. if (iteration >= iterations)
  5795. break;
  5796. fn(iteration);
  5797. if (breakFunction && breakFunction()) {
  5798. loop.breakLoop();
  5799. break;
  5800. }
  5801. }
  5802. loop.executeNext();
  5803. }, timeout);
  5804. }
  5805. }, callback);
  5806. };
  5807. return AsyncLoop;
  5808. }());
  5809. BABYLON.AsyncLoop = AsyncLoop;
  5810. })(BABYLON || (BABYLON = {}));
  5811. var BABYLON;
  5812. (function (BABYLON) {
  5813. var Internals;
  5814. (function (Internals) {
  5815. var _AlphaState = (function () {
  5816. /**
  5817. * Initializes the state.
  5818. */
  5819. function _AlphaState() {
  5820. this._isAlphaBlendDirty = false;
  5821. this._isBlendFunctionParametersDirty = false;
  5822. this._alphaBlend = false;
  5823. this._blendFunctionParameters = new Array(4);
  5824. this.reset();
  5825. }
  5826. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5827. get: function () {
  5828. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5829. },
  5830. enumerable: true,
  5831. configurable: true
  5832. });
  5833. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5834. get: function () {
  5835. return this._alphaBlend;
  5836. },
  5837. set: function (value) {
  5838. if (this._alphaBlend === value) {
  5839. return;
  5840. }
  5841. this._alphaBlend = value;
  5842. this._isAlphaBlendDirty = true;
  5843. },
  5844. enumerable: true,
  5845. configurable: true
  5846. });
  5847. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5848. if (this._blendFunctionParameters[0] === value0 &&
  5849. this._blendFunctionParameters[1] === value1 &&
  5850. this._blendFunctionParameters[2] === value2 &&
  5851. this._blendFunctionParameters[3] === value3) {
  5852. return;
  5853. }
  5854. this._blendFunctionParameters[0] = value0;
  5855. this._blendFunctionParameters[1] = value1;
  5856. this._blendFunctionParameters[2] = value2;
  5857. this._blendFunctionParameters[3] = value3;
  5858. this._isBlendFunctionParametersDirty = true;
  5859. };
  5860. _AlphaState.prototype.reset = function () {
  5861. this._alphaBlend = false;
  5862. this._blendFunctionParameters[0] = null;
  5863. this._blendFunctionParameters[1] = null;
  5864. this._blendFunctionParameters[2] = null;
  5865. this._blendFunctionParameters[3] = null;
  5866. this._isAlphaBlendDirty = true;
  5867. this._isBlendFunctionParametersDirty = false;
  5868. };
  5869. _AlphaState.prototype.apply = function (gl) {
  5870. if (!this.isDirty) {
  5871. return;
  5872. }
  5873. // Alpha blend
  5874. if (this._isAlphaBlendDirty) {
  5875. if (this._alphaBlend) {
  5876. gl.enable(gl.BLEND);
  5877. }
  5878. else {
  5879. gl.disable(gl.BLEND);
  5880. }
  5881. this._isAlphaBlendDirty = false;
  5882. }
  5883. // Alpha function
  5884. if (this._isBlendFunctionParametersDirty) {
  5885. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5886. this._isBlendFunctionParametersDirty = false;
  5887. }
  5888. };
  5889. return _AlphaState;
  5890. }());
  5891. Internals._AlphaState = _AlphaState;
  5892. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5893. })(BABYLON || (BABYLON = {}));
  5894. var BABYLON;
  5895. (function (BABYLON) {
  5896. var Internals;
  5897. (function (Internals) {
  5898. var _DepthCullingState = (function () {
  5899. /**
  5900. * Initializes the state.
  5901. */
  5902. function _DepthCullingState() {
  5903. this._isDepthTestDirty = false;
  5904. this._isDepthMaskDirty = false;
  5905. this._isDepthFuncDirty = false;
  5906. this._isCullFaceDirty = false;
  5907. this._isCullDirty = false;
  5908. this._isZOffsetDirty = false;
  5909. this.reset();
  5910. }
  5911. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  5912. get: function () {
  5913. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  5914. },
  5915. enumerable: true,
  5916. configurable: true
  5917. });
  5918. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  5919. get: function () {
  5920. return this._zOffset;
  5921. },
  5922. set: function (value) {
  5923. if (this._zOffset === value) {
  5924. return;
  5925. }
  5926. this._zOffset = value;
  5927. this._isZOffsetDirty = true;
  5928. },
  5929. enumerable: true,
  5930. configurable: true
  5931. });
  5932. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  5933. get: function () {
  5934. return this._cullFace;
  5935. },
  5936. set: function (value) {
  5937. if (this._cullFace === value) {
  5938. return;
  5939. }
  5940. this._cullFace = value;
  5941. this._isCullFaceDirty = true;
  5942. },
  5943. enumerable: true,
  5944. configurable: true
  5945. });
  5946. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  5947. get: function () {
  5948. return this._cull;
  5949. },
  5950. set: function (value) {
  5951. if (this._cull === value) {
  5952. return;
  5953. }
  5954. this._cull = value;
  5955. this._isCullDirty = true;
  5956. },
  5957. enumerable: true,
  5958. configurable: true
  5959. });
  5960. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  5961. get: function () {
  5962. return this._depthFunc;
  5963. },
  5964. set: function (value) {
  5965. if (this._depthFunc === value) {
  5966. return;
  5967. }
  5968. this._depthFunc = value;
  5969. this._isDepthFuncDirty = true;
  5970. },
  5971. enumerable: true,
  5972. configurable: true
  5973. });
  5974. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  5975. get: function () {
  5976. return this._depthMask;
  5977. },
  5978. set: function (value) {
  5979. if (this._depthMask === value) {
  5980. return;
  5981. }
  5982. this._depthMask = value;
  5983. this._isDepthMaskDirty = true;
  5984. },
  5985. enumerable: true,
  5986. configurable: true
  5987. });
  5988. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  5989. get: function () {
  5990. return this._depthTest;
  5991. },
  5992. set: function (value) {
  5993. if (this._depthTest === value) {
  5994. return;
  5995. }
  5996. this._depthTest = value;
  5997. this._isDepthTestDirty = true;
  5998. },
  5999. enumerable: true,
  6000. configurable: true
  6001. });
  6002. _DepthCullingState.prototype.reset = function () {
  6003. this._depthMask = true;
  6004. this._depthTest = true;
  6005. this._depthFunc = null;
  6006. this._cullFace = null;
  6007. this._cull = null;
  6008. this._zOffset = 0;
  6009. this._isDepthTestDirty = true;
  6010. this._isDepthMaskDirty = true;
  6011. this._isDepthFuncDirty = false;
  6012. this._isCullFaceDirty = false;
  6013. this._isCullDirty = false;
  6014. this._isZOffsetDirty = false;
  6015. };
  6016. _DepthCullingState.prototype.apply = function (gl) {
  6017. if (!this.isDirty) {
  6018. return;
  6019. }
  6020. // Cull
  6021. if (this._isCullDirty) {
  6022. if (this.cull) {
  6023. gl.enable(gl.CULL_FACE);
  6024. }
  6025. else {
  6026. gl.disable(gl.CULL_FACE);
  6027. }
  6028. this._isCullDirty = false;
  6029. }
  6030. // Cull face
  6031. if (this._isCullFaceDirty) {
  6032. gl.cullFace(this.cullFace);
  6033. this._isCullFaceDirty = false;
  6034. }
  6035. // Depth mask
  6036. if (this._isDepthMaskDirty) {
  6037. gl.depthMask(this.depthMask);
  6038. this._isDepthMaskDirty = false;
  6039. }
  6040. // Depth test
  6041. if (this._isDepthTestDirty) {
  6042. if (this.depthTest) {
  6043. gl.enable(gl.DEPTH_TEST);
  6044. }
  6045. else {
  6046. gl.disable(gl.DEPTH_TEST);
  6047. }
  6048. this._isDepthTestDirty = false;
  6049. }
  6050. // Depth func
  6051. if (this._isDepthFuncDirty) {
  6052. gl.depthFunc(this.depthFunc);
  6053. this._isDepthFuncDirty = false;
  6054. }
  6055. // zOffset
  6056. if (this._isZOffsetDirty) {
  6057. if (this.zOffset) {
  6058. gl.enable(gl.POLYGON_OFFSET_FILL);
  6059. gl.polygonOffset(this.zOffset, 0);
  6060. }
  6061. else {
  6062. gl.disable(gl.POLYGON_OFFSET_FILL);
  6063. }
  6064. this._isZOffsetDirty = false;
  6065. }
  6066. };
  6067. return _DepthCullingState;
  6068. }());
  6069. Internals._DepthCullingState = _DepthCullingState;
  6070. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6071. })(BABYLON || (BABYLON = {}));
  6072. var BABYLON;
  6073. (function (BABYLON) {
  6074. var Internals;
  6075. (function (Internals) {
  6076. var _StencilState = (function () {
  6077. function _StencilState() {
  6078. this._isStencilTestDirty = false;
  6079. this._isStencilMaskDirty = false;
  6080. this._isStencilFuncDirty = false;
  6081. this._isStencilOpDirty = false;
  6082. this.reset();
  6083. }
  6084. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6085. get: function () {
  6086. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6087. },
  6088. enumerable: true,
  6089. configurable: true
  6090. });
  6091. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6092. get: function () {
  6093. return this._stencilFunc;
  6094. },
  6095. set: function (value) {
  6096. if (this._stencilFunc === value) {
  6097. return;
  6098. }
  6099. this._stencilFunc = value;
  6100. this._isStencilFuncDirty = true;
  6101. },
  6102. enumerable: true,
  6103. configurable: true
  6104. });
  6105. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6106. get: function () {
  6107. return this._stencilFuncRef;
  6108. },
  6109. set: function (value) {
  6110. if (this._stencilFuncRef === value) {
  6111. return;
  6112. }
  6113. this._stencilFuncRef = value;
  6114. this._isStencilFuncDirty = true;
  6115. },
  6116. enumerable: true,
  6117. configurable: true
  6118. });
  6119. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6120. get: function () {
  6121. return this._stencilFuncMask;
  6122. },
  6123. set: function (value) {
  6124. if (this._stencilFuncMask === value) {
  6125. return;
  6126. }
  6127. this._stencilFuncMask = value;
  6128. this._isStencilFuncDirty = true;
  6129. },
  6130. enumerable: true,
  6131. configurable: true
  6132. });
  6133. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6134. get: function () {
  6135. return this._stencilOpStencilFail;
  6136. },
  6137. set: function (value) {
  6138. if (this._stencilOpStencilFail === value) {
  6139. return;
  6140. }
  6141. this._stencilOpStencilFail = value;
  6142. this._isStencilOpDirty = true;
  6143. },
  6144. enumerable: true,
  6145. configurable: true
  6146. });
  6147. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6148. get: function () {
  6149. return this._stencilOpDepthFail;
  6150. },
  6151. set: function (value) {
  6152. if (this._stencilOpDepthFail === value) {
  6153. return;
  6154. }
  6155. this._stencilOpDepthFail = value;
  6156. this._isStencilOpDirty = true;
  6157. },
  6158. enumerable: true,
  6159. configurable: true
  6160. });
  6161. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6162. get: function () {
  6163. return this._stencilOpStencilDepthPass;
  6164. },
  6165. set: function (value) {
  6166. if (this._stencilOpStencilDepthPass === value) {
  6167. return;
  6168. }
  6169. this._stencilOpStencilDepthPass = value;
  6170. this._isStencilOpDirty = true;
  6171. },
  6172. enumerable: true,
  6173. configurable: true
  6174. });
  6175. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6176. get: function () {
  6177. return this._stencilMask;
  6178. },
  6179. set: function (value) {
  6180. if (this._stencilMask === value) {
  6181. return;
  6182. }
  6183. this._stencilMask = value;
  6184. this._isStencilMaskDirty = true;
  6185. },
  6186. enumerable: true,
  6187. configurable: true
  6188. });
  6189. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6190. get: function () {
  6191. return this._stencilTest;
  6192. },
  6193. set: function (value) {
  6194. if (this._stencilTest === value) {
  6195. return;
  6196. }
  6197. this._stencilTest = value;
  6198. this._isStencilTestDirty = true;
  6199. },
  6200. enumerable: true,
  6201. configurable: true
  6202. });
  6203. _StencilState.prototype.reset = function () {
  6204. this._stencilTest = false;
  6205. this._stencilMask = 0xFF;
  6206. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6207. this._stencilFuncRef = 1;
  6208. this._stencilFuncMask = 0xFF;
  6209. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6210. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6211. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6212. this._isStencilTestDirty = true;
  6213. this._isStencilMaskDirty = true;
  6214. this._isStencilFuncDirty = true;
  6215. this._isStencilOpDirty = true;
  6216. };
  6217. _StencilState.prototype.apply = function (gl) {
  6218. if (!this.isDirty) {
  6219. return;
  6220. }
  6221. // Stencil test
  6222. if (this._isStencilTestDirty) {
  6223. if (this.stencilTest) {
  6224. gl.enable(gl.STENCIL_TEST);
  6225. }
  6226. else {
  6227. gl.disable(gl.STENCIL_TEST);
  6228. }
  6229. this._isStencilTestDirty = false;
  6230. }
  6231. // Stencil mask
  6232. if (this._isStencilMaskDirty) {
  6233. gl.stencilMask(this.stencilMask);
  6234. this._isStencilMaskDirty = false;
  6235. }
  6236. // Stencil func
  6237. if (this._isStencilFuncDirty) {
  6238. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6239. this._isStencilFuncDirty = false;
  6240. }
  6241. // Stencil op
  6242. if (this._isStencilOpDirty) {
  6243. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6244. this._isStencilOpDirty = false;
  6245. }
  6246. };
  6247. return _StencilState;
  6248. }());
  6249. Internals._StencilState = _StencilState;
  6250. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6251. })(BABYLON || (BABYLON = {}));
  6252. var BABYLON;
  6253. (function (BABYLON) {
  6254. var compileShader = function (gl, source, type, defines) {
  6255. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6256. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6257. gl.compileShader(shader);
  6258. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6259. throw new Error(gl.getShaderInfoLog(shader));
  6260. }
  6261. return shader;
  6262. };
  6263. var HALF_FLOAT_OES = 0x8D61;
  6264. var getWebGLTextureType = function (gl, type) {
  6265. if (type === Engine.TEXTURETYPE_FLOAT) {
  6266. return gl.FLOAT;
  6267. }
  6268. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6269. // Add Half Float Constant.
  6270. return HALF_FLOAT_OES;
  6271. }
  6272. return gl.UNSIGNED_BYTE;
  6273. };
  6274. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6275. var magFilter = gl.NEAREST;
  6276. var minFilter = gl.NEAREST;
  6277. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6278. magFilter = gl.LINEAR;
  6279. if (generateMipMaps) {
  6280. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6281. }
  6282. else {
  6283. minFilter = gl.LINEAR;
  6284. }
  6285. }
  6286. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6287. magFilter = gl.LINEAR;
  6288. if (generateMipMaps) {
  6289. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6290. }
  6291. else {
  6292. minFilter = gl.LINEAR;
  6293. }
  6294. }
  6295. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6296. magFilter = gl.NEAREST;
  6297. if (generateMipMaps) {
  6298. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6299. }
  6300. else {
  6301. minFilter = gl.NEAREST;
  6302. }
  6303. }
  6304. return {
  6305. min: minFilter,
  6306. mag: magFilter
  6307. };
  6308. };
  6309. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6311. var engine = scene.getEngine();
  6312. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6313. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6314. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6315. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6316. texture._baseWidth = width;
  6317. texture._baseHeight = height;
  6318. texture._width = potWidth;
  6319. texture._height = potHeight;
  6320. texture.isReady = true;
  6321. processFunction(potWidth, potHeight);
  6322. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6323. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6324. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6325. if (!noMipmap && !isCompressed) {
  6326. gl.generateMipmap(gl.TEXTURE_2D);
  6327. }
  6328. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6329. engine.resetTextureCache();
  6330. scene._removePendingData(texture);
  6331. texture.onLoadedCallbacks.forEach(function (callback) {
  6332. callback();
  6333. });
  6334. texture.onLoadedCallbacks = [];
  6335. };
  6336. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6337. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6338. var img;
  6339. var onload = function () {
  6340. loadedImages[index] = img;
  6341. loadedImages._internalCount++;
  6342. scene._removePendingData(img);
  6343. if (loadedImages._internalCount === 6) {
  6344. onfinish(loadedImages);
  6345. }
  6346. };
  6347. var onerror = function () {
  6348. scene._removePendingData(img);
  6349. if (onErrorCallBack) {
  6350. onErrorCallBack();
  6351. }
  6352. };
  6353. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6354. scene._addPendingData(img);
  6355. };
  6356. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6357. if (onError === void 0) { onError = null; }
  6358. var loadedImages = [];
  6359. loadedImages._internalCount = 0;
  6360. for (var index = 0; index < 6; index++) {
  6361. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6362. }
  6363. };
  6364. var InstancingAttributeInfo = (function () {
  6365. function InstancingAttributeInfo() {
  6366. }
  6367. return InstancingAttributeInfo;
  6368. }());
  6369. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6370. var EngineCapabilities = (function () {
  6371. function EngineCapabilities() {
  6372. }
  6373. return EngineCapabilities;
  6374. }());
  6375. BABYLON.EngineCapabilities = EngineCapabilities;
  6376. /**
  6377. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6378. */
  6379. var Engine = (function () {
  6380. /**
  6381. * @constructor
  6382. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6383. * @param {boolean} [antialias] - enable antialias
  6384. * @param options - further options to be sent to the getContext function
  6385. */
  6386. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6387. var _this = this;
  6388. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = true; }
  6389. // Public members
  6390. this.isFullscreen = false;
  6391. this.isPointerLock = false;
  6392. this.cullBackFaces = true;
  6393. this.renderEvenInBackground = true;
  6394. // To enable/disable IDB support and avoid XHR on .manifest
  6395. this.enableOfflineSupport = true;
  6396. this.scenes = new Array();
  6397. this._windowIsBackground = false;
  6398. this._webGLVersion = "1.0";
  6399. this._badOS = false;
  6400. this._drawCalls = new BABYLON.PerfCounter();
  6401. this._renderingQueueLaunched = false;
  6402. this._activeRenderLoops = [];
  6403. // FPS
  6404. this.fpsRange = 60;
  6405. this.previousFramesDuration = [];
  6406. this.fps = 60;
  6407. this.deltaTime = 0;
  6408. // States
  6409. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6410. this._stencilState = new BABYLON.Internals._StencilState();
  6411. this._alphaState = new BABYLON.Internals._AlphaState();
  6412. this._alphaMode = Engine.ALPHA_DISABLE;
  6413. // Cache
  6414. this._loadedTexturesCache = new Array();
  6415. this._maxTextureChannels = 16;
  6416. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6417. this._compiledEffects = {};
  6418. this._vertexAttribArraysEnabled = [];
  6419. this._uintIndicesCurrentlySet = false;
  6420. this._currentBoundBuffer = new Array();
  6421. this._currentBufferPointers = [];
  6422. this._currentInstanceLocations = new Array();
  6423. this._currentInstanceBuffers = new Array();
  6424. this._onVRFullScreenTriggered = function () {
  6425. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6426. //get the old size before we change
  6427. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6428. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6429. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6430. //But actually, no browser follow the specs...
  6431. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6432. //get the width and height, change the render size
  6433. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6434. var width, height;
  6435. _this.setHardwareScalingLevel(1);
  6436. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6437. }
  6438. else {
  6439. //When the specs are implemented, need to uncomment this.
  6440. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6441. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6442. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6443. _this._vrDisplayEnabled = undefined;
  6444. }
  6445. };
  6446. this._renderingCanvas = canvas;
  6447. this._externalData = new BABYLON.StringDictionary();
  6448. options = options || {};
  6449. if (antialias != null) {
  6450. options.antialias = antialias;
  6451. }
  6452. if (options.preserveDrawingBuffer === undefined) {
  6453. options.preserveDrawingBuffer = false;
  6454. }
  6455. // Checks if some of the format renders first to allow the use of webgl inspector.
  6456. var renderToFullFloat = this._canRenderToFloatTexture();
  6457. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6458. // GL
  6459. //try {
  6460. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6461. // if (this._gl) {
  6462. // this._webGLVersion = "2.0";
  6463. // }
  6464. //} catch (e) {
  6465. // // Do nothing
  6466. //}
  6467. if (!this._gl) {
  6468. try {
  6469. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6470. }
  6471. catch (e) {
  6472. throw new Error("WebGL not supported");
  6473. }
  6474. }
  6475. if (!this._gl) {
  6476. throw new Error("WebGL not supported");
  6477. }
  6478. this._onBlur = function () {
  6479. _this._windowIsBackground = true;
  6480. };
  6481. this._onFocus = function () {
  6482. _this._windowIsBackground = false;
  6483. };
  6484. window.addEventListener("blur", this._onBlur);
  6485. window.addEventListener("focus", this._onFocus);
  6486. // Viewport
  6487. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6488. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6489. this.resize();
  6490. // Caps
  6491. this._isStencilEnable = options.stencil;
  6492. this._caps = new EngineCapabilities();
  6493. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6494. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6495. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6496. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6497. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6498. // Infos
  6499. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6500. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6501. if (rendererInfo != null) {
  6502. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6503. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6504. }
  6505. if (!this._glVendor) {
  6506. this._glVendor = "Unknown vendor";
  6507. }
  6508. if (!this._glRenderer) {
  6509. this._glRenderer = "Unknown renderer";
  6510. }
  6511. // Extensions
  6512. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6513. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6514. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6515. 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');
  6516. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6517. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6518. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6519. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6520. this._caps.highPrecisionShaderSupported = true;
  6521. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6522. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6523. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6524. this._caps.textureFloatRender = renderToFullFloat;
  6525. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6526. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6527. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6528. if (this._gl.getShaderPrecisionFormat) {
  6529. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6530. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6531. }
  6532. // Depth buffer
  6533. this.setDepthBuffer(true);
  6534. this.setDepthFunctionToLessOrEqual();
  6535. this.setDepthWrite(true);
  6536. // Fullscreen
  6537. this._onFullscreenChange = function () {
  6538. if (document.fullscreen !== undefined) {
  6539. _this.isFullscreen = document.fullscreen;
  6540. }
  6541. else if (document.mozFullScreen !== undefined) {
  6542. _this.isFullscreen = document.mozFullScreen;
  6543. }
  6544. else if (document.webkitIsFullScreen !== undefined) {
  6545. _this.isFullscreen = document.webkitIsFullScreen;
  6546. }
  6547. else if (document.msIsFullScreen !== undefined) {
  6548. _this.isFullscreen = document.msIsFullScreen;
  6549. }
  6550. // Pointer lock
  6551. if (_this.isFullscreen && _this._pointerLockRequested) {
  6552. canvas.requestPointerLock = canvas.requestPointerLock ||
  6553. canvas.msRequestPointerLock ||
  6554. canvas.mozRequestPointerLock ||
  6555. canvas.webkitRequestPointerLock;
  6556. if (canvas.requestPointerLock) {
  6557. canvas.requestPointerLock();
  6558. }
  6559. }
  6560. };
  6561. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6562. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6563. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6564. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6565. // Pointer lock
  6566. this._onPointerLockChange = function () {
  6567. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6568. document.webkitPointerLockElement === canvas ||
  6569. document.msPointerLockElement === canvas ||
  6570. document.pointerLockElement === canvas);
  6571. };
  6572. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6573. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6574. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6575. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6576. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6577. Engine.audioEngine = new BABYLON.AudioEngine();
  6578. }
  6579. //default loading screen
  6580. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6581. //Load WebVR Devices
  6582. if (options.autoEnableWebVR) {
  6583. this.initWebVR();
  6584. }
  6585. //Detect if we are running on a faulty buggy OS.
  6586. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6587. //ua sniffing is the tool of the devil.
  6588. this._badOS = regexp.test(navigator.userAgent);
  6589. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6590. }
  6591. Object.defineProperty(Engine, "NEVER", {
  6592. get: function () {
  6593. return Engine._NEVER;
  6594. },
  6595. enumerable: true,
  6596. configurable: true
  6597. });
  6598. Object.defineProperty(Engine, "ALWAYS", {
  6599. get: function () {
  6600. return Engine._ALWAYS;
  6601. },
  6602. enumerable: true,
  6603. configurable: true
  6604. });
  6605. Object.defineProperty(Engine, "LESS", {
  6606. get: function () {
  6607. return Engine._LESS;
  6608. },
  6609. enumerable: true,
  6610. configurable: true
  6611. });
  6612. Object.defineProperty(Engine, "EQUAL", {
  6613. get: function () {
  6614. return Engine._EQUAL;
  6615. },
  6616. enumerable: true,
  6617. configurable: true
  6618. });
  6619. Object.defineProperty(Engine, "LEQUAL", {
  6620. get: function () {
  6621. return Engine._LEQUAL;
  6622. },
  6623. enumerable: true,
  6624. configurable: true
  6625. });
  6626. Object.defineProperty(Engine, "GREATER", {
  6627. get: function () {
  6628. return Engine._GREATER;
  6629. },
  6630. enumerable: true,
  6631. configurable: true
  6632. });
  6633. Object.defineProperty(Engine, "GEQUAL", {
  6634. get: function () {
  6635. return Engine._GEQUAL;
  6636. },
  6637. enumerable: true,
  6638. configurable: true
  6639. });
  6640. Object.defineProperty(Engine, "NOTEQUAL", {
  6641. get: function () {
  6642. return Engine._NOTEQUAL;
  6643. },
  6644. enumerable: true,
  6645. configurable: true
  6646. });
  6647. Object.defineProperty(Engine, "KEEP", {
  6648. get: function () {
  6649. return Engine._KEEP;
  6650. },
  6651. enumerable: true,
  6652. configurable: true
  6653. });
  6654. Object.defineProperty(Engine, "REPLACE", {
  6655. get: function () {
  6656. return Engine._REPLACE;
  6657. },
  6658. enumerable: true,
  6659. configurable: true
  6660. });
  6661. Object.defineProperty(Engine, "INCR", {
  6662. get: function () {
  6663. return Engine._INCR;
  6664. },
  6665. enumerable: true,
  6666. configurable: true
  6667. });
  6668. Object.defineProperty(Engine, "DECR", {
  6669. get: function () {
  6670. return Engine._DECR;
  6671. },
  6672. enumerable: true,
  6673. configurable: true
  6674. });
  6675. Object.defineProperty(Engine, "INVERT", {
  6676. get: function () {
  6677. return Engine._INVERT;
  6678. },
  6679. enumerable: true,
  6680. configurable: true
  6681. });
  6682. Object.defineProperty(Engine, "INCR_WRAP", {
  6683. get: function () {
  6684. return Engine._INCR_WRAP;
  6685. },
  6686. enumerable: true,
  6687. configurable: true
  6688. });
  6689. Object.defineProperty(Engine, "DECR_WRAP", {
  6690. get: function () {
  6691. return Engine._DECR_WRAP;
  6692. },
  6693. enumerable: true,
  6694. configurable: true
  6695. });
  6696. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6697. get: function () {
  6698. return Engine._ALPHA_DISABLE;
  6699. },
  6700. enumerable: true,
  6701. configurable: true
  6702. });
  6703. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6704. get: function () {
  6705. return Engine._ALPHA_ONEONE;
  6706. },
  6707. enumerable: true,
  6708. configurable: true
  6709. });
  6710. Object.defineProperty(Engine, "ALPHA_ADD", {
  6711. get: function () {
  6712. return Engine._ALPHA_ADD;
  6713. },
  6714. enumerable: true,
  6715. configurable: true
  6716. });
  6717. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6718. get: function () {
  6719. return Engine._ALPHA_COMBINE;
  6720. },
  6721. enumerable: true,
  6722. configurable: true
  6723. });
  6724. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6725. get: function () {
  6726. return Engine._ALPHA_SUBTRACT;
  6727. },
  6728. enumerable: true,
  6729. configurable: true
  6730. });
  6731. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6732. get: function () {
  6733. return Engine._ALPHA_MULTIPLY;
  6734. },
  6735. enumerable: true,
  6736. configurable: true
  6737. });
  6738. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6739. get: function () {
  6740. return Engine._ALPHA_MAXIMIZED;
  6741. },
  6742. enumerable: true,
  6743. configurable: true
  6744. });
  6745. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6746. get: function () {
  6747. return Engine._DELAYLOADSTATE_NONE;
  6748. },
  6749. enumerable: true,
  6750. configurable: true
  6751. });
  6752. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6753. get: function () {
  6754. return Engine._DELAYLOADSTATE_LOADED;
  6755. },
  6756. enumerable: true,
  6757. configurable: true
  6758. });
  6759. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6760. get: function () {
  6761. return Engine._DELAYLOADSTATE_LOADING;
  6762. },
  6763. enumerable: true,
  6764. configurable: true
  6765. });
  6766. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6767. get: function () {
  6768. return Engine._DELAYLOADSTATE_NOTLOADED;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6774. get: function () {
  6775. return Engine._TEXTUREFORMAT_ALPHA;
  6776. },
  6777. enumerable: true,
  6778. configurable: true
  6779. });
  6780. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6781. get: function () {
  6782. return Engine._TEXTUREFORMAT_LUMINANCE;
  6783. },
  6784. enumerable: true,
  6785. configurable: true
  6786. });
  6787. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6788. get: function () {
  6789. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6790. },
  6791. enumerable: true,
  6792. configurable: true
  6793. });
  6794. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6795. get: function () {
  6796. return Engine._TEXTUREFORMAT_RGB;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6802. get: function () {
  6803. return Engine._TEXTUREFORMAT_RGBA;
  6804. },
  6805. enumerable: true,
  6806. configurable: true
  6807. });
  6808. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6809. get: function () {
  6810. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6811. },
  6812. enumerable: true,
  6813. configurable: true
  6814. });
  6815. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6816. get: function () {
  6817. return Engine._TEXTURETYPE_FLOAT;
  6818. },
  6819. enumerable: true,
  6820. configurable: true
  6821. });
  6822. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6823. get: function () {
  6824. return Engine._TEXTURETYPE_HALF_FLOAT;
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. Object.defineProperty(Engine, "Version", {
  6830. get: function () {
  6831. return "2.5.-beta";
  6832. },
  6833. enumerable: true,
  6834. configurable: true
  6835. });
  6836. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6837. get: function () {
  6838. return this._webGLVersion;
  6839. },
  6840. enumerable: true,
  6841. configurable: true
  6842. });
  6843. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6844. /**
  6845. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  6846. */
  6847. get: function () {
  6848. return this._isStencilEnable;
  6849. },
  6850. enumerable: true,
  6851. configurable: true
  6852. });
  6853. Engine.prototype._prepareWorkingCanvas = function () {
  6854. if (this._workingCanvas) {
  6855. return;
  6856. }
  6857. this._workingCanvas = document.createElement("canvas");
  6858. this._workingContext = this._workingCanvas.getContext("2d");
  6859. };
  6860. Engine.prototype.resetTextureCache = function () {
  6861. for (var index = 0; index < this._maxTextureChannels; index++) {
  6862. this._activeTexturesCache[index] = null;
  6863. }
  6864. };
  6865. Engine.prototype.getGlInfo = function () {
  6866. return {
  6867. vendor: this._glVendor,
  6868. renderer: this._glRenderer,
  6869. version: this._glVersion
  6870. };
  6871. };
  6872. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  6873. if (useScreen === void 0) { useScreen = false; }
  6874. var viewport = camera.viewport;
  6875. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  6876. };
  6877. Engine.prototype.getRenderWidth = function (useScreen) {
  6878. if (useScreen === void 0) { useScreen = false; }
  6879. if (!useScreen && this._currentRenderTarget) {
  6880. return this._currentRenderTarget._width;
  6881. }
  6882. return this._renderingCanvas.width;
  6883. };
  6884. Engine.prototype.getRenderHeight = function (useScreen) {
  6885. if (useScreen === void 0) { useScreen = false; }
  6886. if (!useScreen && this._currentRenderTarget) {
  6887. return this._currentRenderTarget._height;
  6888. }
  6889. return this._renderingCanvas.height;
  6890. };
  6891. Engine.prototype.getRenderingCanvas = function () {
  6892. return this._renderingCanvas;
  6893. };
  6894. Engine.prototype.getRenderingCanvasClientRect = function () {
  6895. return this._renderingCanvas.getBoundingClientRect();
  6896. };
  6897. Engine.prototype.setHardwareScalingLevel = function (level) {
  6898. this._hardwareScalingLevel = level;
  6899. this.resize();
  6900. };
  6901. Engine.prototype.getHardwareScalingLevel = function () {
  6902. return this._hardwareScalingLevel;
  6903. };
  6904. Engine.prototype.getLoadedTexturesCache = function () {
  6905. return this._loadedTexturesCache;
  6906. };
  6907. Engine.prototype.getCaps = function () {
  6908. return this._caps;
  6909. };
  6910. Object.defineProperty(Engine.prototype, "drawCalls", {
  6911. get: function () {
  6912. return this._drawCalls.current;
  6913. },
  6914. enumerable: true,
  6915. configurable: true
  6916. });
  6917. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  6918. get: function () {
  6919. return this._drawCalls;
  6920. },
  6921. enumerable: true,
  6922. configurable: true
  6923. });
  6924. Engine.prototype.getDepthFunction = function () {
  6925. return this._depthCullingState.depthFunc;
  6926. };
  6927. Engine.prototype.setDepthFunction = function (depthFunc) {
  6928. this._depthCullingState.depthFunc = depthFunc;
  6929. };
  6930. Engine.prototype.setDepthFunctionToGreater = function () {
  6931. this._depthCullingState.depthFunc = this._gl.GREATER;
  6932. };
  6933. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  6934. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  6935. };
  6936. Engine.prototype.setDepthFunctionToLess = function () {
  6937. this._depthCullingState.depthFunc = this._gl.LESS;
  6938. };
  6939. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  6940. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  6941. };
  6942. Engine.prototype.getStencilBuffer = function () {
  6943. return this._stencilState.stencilTest;
  6944. };
  6945. Engine.prototype.setStencilBuffer = function (enable) {
  6946. this._stencilState.stencilTest = enable;
  6947. };
  6948. Engine.prototype.getStencilMask = function () {
  6949. return this._stencilState.stencilMask;
  6950. };
  6951. Engine.prototype.setStencilMask = function (mask) {
  6952. this._stencilState.stencilMask = mask;
  6953. };
  6954. Engine.prototype.getStencilFunction = function () {
  6955. return this._stencilState.stencilFunc;
  6956. };
  6957. Engine.prototype.getStencilFunctionReference = function () {
  6958. return this._stencilState.stencilFuncRef;
  6959. };
  6960. Engine.prototype.getStencilFunctionMask = function () {
  6961. return this._stencilState.stencilFuncMask;
  6962. };
  6963. Engine.prototype.setStencilFunction = function (stencilFunc) {
  6964. this._stencilState.stencilFunc = stencilFunc;
  6965. };
  6966. Engine.prototype.setStencilFunctionReference = function (reference) {
  6967. this._stencilState.stencilFuncRef = reference;
  6968. };
  6969. Engine.prototype.setStencilFunctionMask = function (mask) {
  6970. this._stencilState.stencilFuncMask = mask;
  6971. };
  6972. Engine.prototype.getStencilOperationFail = function () {
  6973. return this._stencilState.stencilOpStencilFail;
  6974. };
  6975. Engine.prototype.getStencilOperationDepthFail = function () {
  6976. return this._stencilState.stencilOpDepthFail;
  6977. };
  6978. Engine.prototype.getStencilOperationPass = function () {
  6979. return this._stencilState.stencilOpStencilDepthPass;
  6980. };
  6981. Engine.prototype.setStencilOperationFail = function (operation) {
  6982. this._stencilState.stencilOpStencilFail = operation;
  6983. };
  6984. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  6985. this._stencilState.stencilOpDepthFail = operation;
  6986. };
  6987. Engine.prototype.setStencilOperationPass = function (operation) {
  6988. this._stencilState.stencilOpStencilDepthPass = operation;
  6989. };
  6990. /**
  6991. * stop executing a render loop function and remove it from the execution array
  6992. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  6993. */
  6994. Engine.prototype.stopRenderLoop = function (renderFunction) {
  6995. if (!renderFunction) {
  6996. this._activeRenderLoops = [];
  6997. return;
  6998. }
  6999. var index = this._activeRenderLoops.indexOf(renderFunction);
  7000. if (index >= 0) {
  7001. this._activeRenderLoops.splice(index, 1);
  7002. }
  7003. };
  7004. Engine.prototype._renderLoop = function () {
  7005. var shouldRender = true;
  7006. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7007. shouldRender = false;
  7008. }
  7009. if (shouldRender) {
  7010. // Start new frame
  7011. this.beginFrame();
  7012. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7013. var renderFunction = this._activeRenderLoops[index];
  7014. renderFunction();
  7015. }
  7016. // Present
  7017. this.endFrame();
  7018. }
  7019. if (this._activeRenderLoops.length > 0) {
  7020. // Register new frame
  7021. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7022. }
  7023. else {
  7024. this._renderingQueueLaunched = false;
  7025. }
  7026. };
  7027. /**
  7028. * Register and execute a render loop. The engine can have more than one render function.
  7029. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7030. * @example
  7031. * engine.runRenderLoop(function () {
  7032. * scene.render()
  7033. * })
  7034. */
  7035. Engine.prototype.runRenderLoop = function (renderFunction) {
  7036. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7037. return;
  7038. }
  7039. this._activeRenderLoops.push(renderFunction);
  7040. if (!this._renderingQueueLaunched) {
  7041. this._renderingQueueLaunched = true;
  7042. this._bindedRenderFunction = this._renderLoop.bind(this);
  7043. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7044. }
  7045. };
  7046. /**
  7047. * Toggle full screen mode.
  7048. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7049. * @param {any} options - an options object to be sent to the requestFullscreen function
  7050. */
  7051. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7052. if (this.isFullscreen) {
  7053. BABYLON.Tools.ExitFullscreen();
  7054. }
  7055. else {
  7056. this._pointerLockRequested = requestPointerLock;
  7057. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7058. }
  7059. };
  7060. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7061. if (stencil === void 0) { stencil = false; }
  7062. this.applyStates();
  7063. var mode = 0;
  7064. if (backBuffer) {
  7065. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7066. mode |= this._gl.COLOR_BUFFER_BIT;
  7067. }
  7068. if (depth) {
  7069. this._gl.clearDepth(1.0);
  7070. mode |= this._gl.DEPTH_BUFFER_BIT;
  7071. }
  7072. if (stencil) {
  7073. this._gl.clearStencil(0);
  7074. mode |= this._gl.STENCIL_BUFFER_BIT;
  7075. }
  7076. this._gl.clear(mode);
  7077. };
  7078. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7079. var gl = this._gl;
  7080. // Save state
  7081. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7082. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7083. // Change state
  7084. gl.enable(gl.SCISSOR_TEST);
  7085. gl.scissor(x, y, width, height);
  7086. // Clear
  7087. this.clear(clearColor, true, true, true);
  7088. // Restore state
  7089. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7090. if (curScissor === true) {
  7091. gl.enable(gl.SCISSOR_TEST);
  7092. }
  7093. else {
  7094. gl.disable(gl.SCISSOR_TEST);
  7095. }
  7096. };
  7097. /**
  7098. * Set the WebGL's viewport
  7099. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7100. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7101. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7102. */
  7103. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7104. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.width);
  7105. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.height);
  7106. var x = viewport.x || 0;
  7107. var y = viewport.y || 0;
  7108. this._cachedViewport = viewport;
  7109. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7110. };
  7111. /**
  7112. * Directly set the WebGL Viewport
  7113. * The x, y, width & height are directly passed to the WebGL call
  7114. * @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.
  7115. */
  7116. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7117. var currentViewport = this._cachedViewport;
  7118. this._cachedViewport = null;
  7119. this._gl.viewport(x, y, width, height);
  7120. return currentViewport;
  7121. };
  7122. Engine.prototype.beginFrame = function () {
  7123. this._measureFps();
  7124. };
  7125. Engine.prototype.endFrame = function () {
  7126. //force a flush in case we are using a bad OS.
  7127. if (this._badOS) {
  7128. this.flushFramebuffer();
  7129. }
  7130. //submit frame to the vr device, if enabled
  7131. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7132. this._vrDisplayEnabled.submitFrame();
  7133. }
  7134. };
  7135. /**
  7136. * resize the view according to the canvas' size.
  7137. * @example
  7138. * window.addEventListener("resize", function () {
  7139. * engine.resize();
  7140. * });
  7141. */
  7142. Engine.prototype.resize = function () {
  7143. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7144. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7145. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7146. for (var index = 0; index < this.scenes.length; index++) {
  7147. var scene = this.scenes[index];
  7148. if (BABYLON.DebugLayer && scene.debugLayer.isVisible()) {
  7149. scene.debugLayer._syncPositions();
  7150. }
  7151. }
  7152. };
  7153. /**
  7154. * force a specific size of the canvas
  7155. * @param {number} width - the new canvas' width
  7156. * @param {number} height - the new canvas' height
  7157. */
  7158. Engine.prototype.setSize = function (width, height) {
  7159. this._renderingCanvas.width = width;
  7160. this._renderingCanvas.height = height;
  7161. for (var index = 0; index < this.scenes.length; index++) {
  7162. var scene = this.scenes[index];
  7163. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7164. var cam = scene.cameras[camIndex];
  7165. cam._currentRenderId = 0;
  7166. }
  7167. }
  7168. };
  7169. //WebVR functions
  7170. Engine.prototype.initWebVR = function () {
  7171. if (!this.vrDisplaysPromise) {
  7172. this._getVRDisplays();
  7173. }
  7174. };
  7175. Engine.prototype.enableVR = function (vrDevice) {
  7176. this._vrDisplayEnabled = vrDevice;
  7177. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7178. };
  7179. Engine.prototype.disableVR = function () {
  7180. if (this._vrDisplayEnabled) {
  7181. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7182. }
  7183. };
  7184. Engine.prototype._getVRDisplays = function () {
  7185. var _this = this;
  7186. var getWebVRDevices = function (devices) {
  7187. var size = devices.length;
  7188. var i = 0;
  7189. _this._vrDisplays = devices.filter(function (device) {
  7190. return devices[i] instanceof VRDisplay;
  7191. });
  7192. return _this._vrDisplays;
  7193. };
  7194. //using a key due to typescript
  7195. if (navigator.getVRDisplays) {
  7196. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7197. }
  7198. };
  7199. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7200. this._currentRenderTarget = texture;
  7201. this.bindUnboundFramebuffer(texture._framebuffer);
  7202. var gl = this._gl;
  7203. if (texture.isCube) {
  7204. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7205. }
  7206. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7207. this.wipeCaches();
  7208. };
  7209. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7210. if (this._currentFramebuffer !== framebuffer) {
  7211. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7212. this._currentFramebuffer = framebuffer;
  7213. }
  7214. };
  7215. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7216. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7217. this._currentRenderTarget = null;
  7218. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7219. var gl = this._gl;
  7220. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7221. gl.generateMipmap(gl.TEXTURE_2D);
  7222. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7223. }
  7224. this.bindUnboundFramebuffer(null);
  7225. };
  7226. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7227. if (texture.generateMipMaps) {
  7228. var gl = this._gl;
  7229. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7230. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7231. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7232. }
  7233. };
  7234. Engine.prototype.flushFramebuffer = function () {
  7235. this._gl.flush();
  7236. };
  7237. Engine.prototype.restoreDefaultFramebuffer = function () {
  7238. this._currentRenderTarget = null;
  7239. this.bindUnboundFramebuffer(null);
  7240. this.setViewport(this._cachedViewport);
  7241. this.wipeCaches();
  7242. };
  7243. // VBOs
  7244. Engine.prototype._resetVertexBufferBinding = function () {
  7245. this.bindArrayBuffer(null);
  7246. this._cachedVertexBuffers = null;
  7247. };
  7248. Engine.prototype.createVertexBuffer = function (vertices) {
  7249. var vbo = this._gl.createBuffer();
  7250. this.bindArrayBuffer(vbo);
  7251. if (vertices instanceof Float32Array) {
  7252. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7253. }
  7254. else {
  7255. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7256. }
  7257. this._resetVertexBufferBinding();
  7258. vbo.references = 1;
  7259. return vbo;
  7260. };
  7261. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7262. var vbo = this._gl.createBuffer();
  7263. this.bindArrayBuffer(vbo);
  7264. if (vertices instanceof Float32Array) {
  7265. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7266. }
  7267. else {
  7268. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7269. }
  7270. this._resetVertexBufferBinding();
  7271. vbo.references = 1;
  7272. return vbo;
  7273. };
  7274. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7275. this.bindArrayBuffer(vertexBuffer);
  7276. if (offset === undefined) {
  7277. offset = 0;
  7278. }
  7279. if (count === undefined) {
  7280. if (vertices instanceof Float32Array) {
  7281. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7282. }
  7283. else {
  7284. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7285. }
  7286. }
  7287. else {
  7288. if (vertices instanceof Float32Array) {
  7289. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7290. }
  7291. else {
  7292. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7293. }
  7294. }
  7295. this._resetVertexBufferBinding();
  7296. };
  7297. Engine.prototype._resetIndexBufferBinding = function () {
  7298. this.bindIndexBuffer(null);
  7299. this._cachedIndexBuffer = null;
  7300. };
  7301. Engine.prototype.createIndexBuffer = function (indices) {
  7302. var vbo = this._gl.createBuffer();
  7303. this.bindIndexBuffer(vbo);
  7304. // Check for 32 bits indices
  7305. var arrayBuffer;
  7306. var need32Bits = false;
  7307. if (this._caps.uintIndices) {
  7308. for (var index = 0; index < indices.length; index++) {
  7309. if (indices[index] > 65535) {
  7310. need32Bits = true;
  7311. break;
  7312. }
  7313. }
  7314. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7315. }
  7316. else {
  7317. arrayBuffer = new Uint16Array(indices);
  7318. }
  7319. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7320. this._resetIndexBufferBinding();
  7321. vbo.references = 1;
  7322. vbo.is32Bits = need32Bits;
  7323. return vbo;
  7324. };
  7325. Engine.prototype.bindArrayBuffer = function (buffer) {
  7326. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7327. };
  7328. Engine.prototype.bindIndexBuffer = function (buffer) {
  7329. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7330. };
  7331. Engine.prototype.bindBuffer = function (buffer, target) {
  7332. if (this._currentBoundBuffer[target] !== buffer) {
  7333. this._gl.bindBuffer(target, buffer);
  7334. this._currentBoundBuffer[target] = buffer;
  7335. }
  7336. };
  7337. Engine.prototype.updateArrayBuffer = function (data) {
  7338. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7339. };
  7340. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7341. var pointer = this._currentBufferPointers[indx];
  7342. var changed = false;
  7343. if (!pointer) {
  7344. changed = true;
  7345. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7346. }
  7347. else {
  7348. if (pointer.buffer !== buffer) {
  7349. pointer.buffer = buffer;
  7350. changed = true;
  7351. }
  7352. if (pointer.size !== size) {
  7353. pointer.size = size;
  7354. changed = true;
  7355. }
  7356. if (pointer.type !== type) {
  7357. pointer.type = type;
  7358. changed = true;
  7359. }
  7360. if (pointer.normalized !== normalized) {
  7361. pointer.normalized = normalized;
  7362. changed = true;
  7363. }
  7364. if (pointer.stride !== stride) {
  7365. pointer.stride = stride;
  7366. changed = true;
  7367. }
  7368. if (pointer.offset !== offset) {
  7369. pointer.offset = offset;
  7370. changed = true;
  7371. }
  7372. }
  7373. if (changed) {
  7374. this.bindArrayBuffer(buffer);
  7375. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7376. }
  7377. };
  7378. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7379. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7380. this._cachedVertexBuffers = vertexBuffer;
  7381. this._cachedEffectForVertexBuffers = effect;
  7382. var attributesCount = effect.getAttributesCount();
  7383. var offset = 0;
  7384. for (var index = 0; index < attributesCount; index++) {
  7385. if (index < vertexDeclaration.length) {
  7386. var order = effect.getAttributeLocation(index);
  7387. if (order >= 0) {
  7388. if (!this._vertexAttribArraysEnabled[order]) {
  7389. this._gl.enableVertexAttribArray(order);
  7390. this._vertexAttribArraysEnabled[order] = true;
  7391. }
  7392. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7393. }
  7394. offset += vertexDeclaration[index] * 4;
  7395. }
  7396. else {
  7397. //disable effect attributes that have no data
  7398. var order = effect.getAttributeLocation(index);
  7399. if (this._vertexAttribArraysEnabled[order]) {
  7400. this._gl.disableVertexAttribArray(order);
  7401. this._vertexAttribArraysEnabled[order] = false;
  7402. }
  7403. }
  7404. }
  7405. }
  7406. if (this._cachedIndexBuffer !== indexBuffer) {
  7407. this._cachedIndexBuffer = indexBuffer;
  7408. this.bindIndexBuffer(indexBuffer);
  7409. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7410. }
  7411. };
  7412. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7413. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7414. this._cachedVertexBuffers = vertexBuffers;
  7415. this._cachedEffectForVertexBuffers = effect;
  7416. var attributes = effect.getAttributesNames();
  7417. for (var index = 0; index < attributes.length; index++) {
  7418. var order = effect.getAttributeLocation(index);
  7419. if (order >= 0) {
  7420. var vertexBuffer = vertexBuffers[attributes[index]];
  7421. if (!vertexBuffer) {
  7422. if (this._vertexAttribArraysEnabled[order]) {
  7423. this._gl.disableVertexAttribArray(order);
  7424. this._vertexAttribArraysEnabled[order] = false;
  7425. }
  7426. continue;
  7427. }
  7428. if (!this._vertexAttribArraysEnabled[order]) {
  7429. this._gl.enableVertexAttribArray(order);
  7430. this._vertexAttribArraysEnabled[order] = true;
  7431. }
  7432. var buffer = vertexBuffer.getBuffer();
  7433. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7434. if (vertexBuffer.getIsInstanced()) {
  7435. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7436. this._currentInstanceLocations.push(order);
  7437. this._currentInstanceBuffers.push(buffer);
  7438. }
  7439. }
  7440. }
  7441. }
  7442. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7443. this._cachedIndexBuffer = indexBuffer;
  7444. this.bindIndexBuffer(indexBuffer);
  7445. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7446. }
  7447. };
  7448. Engine.prototype.unbindInstanceAttributes = function () {
  7449. var boundBuffer;
  7450. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7451. var instancesBuffer = this._currentInstanceBuffers[i];
  7452. if (boundBuffer != instancesBuffer) {
  7453. boundBuffer = instancesBuffer;
  7454. this.bindArrayBuffer(instancesBuffer);
  7455. }
  7456. var offsetLocation = this._currentInstanceLocations[i];
  7457. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7458. }
  7459. this._currentInstanceBuffers.length = 0;
  7460. this._currentInstanceLocations.length = 0;
  7461. };
  7462. Engine.prototype._releaseBuffer = function (buffer) {
  7463. buffer.references--;
  7464. if (buffer.references === 0) {
  7465. this._gl.deleteBuffer(buffer);
  7466. return true;
  7467. }
  7468. return false;
  7469. };
  7470. Engine.prototype.createInstancesBuffer = function (capacity) {
  7471. var buffer = this._gl.createBuffer();
  7472. buffer.capacity = capacity;
  7473. this.bindArrayBuffer(buffer);
  7474. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7475. return buffer;
  7476. };
  7477. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7478. this._gl.deleteBuffer(buffer);
  7479. };
  7480. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7481. this.bindArrayBuffer(instancesBuffer);
  7482. if (data) {
  7483. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7484. }
  7485. if (offsetLocations[0].index !== undefined) {
  7486. var stride = 0;
  7487. for (var i = 0; i < offsetLocations.length; i++) {
  7488. var ai = offsetLocations[i];
  7489. stride += ai.attributeSize * 4;
  7490. }
  7491. for (var i = 0; i < offsetLocations.length; i++) {
  7492. var ai = offsetLocations[i];
  7493. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7494. this._gl.enableVertexAttribArray(ai.index);
  7495. this._vertexAttribArraysEnabled[ai.index] = true;
  7496. }
  7497. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7498. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7499. this._currentInstanceLocations.push(ai.index);
  7500. this._currentInstanceBuffers.push(instancesBuffer);
  7501. }
  7502. }
  7503. else {
  7504. for (var index = 0; index < 4; index++) {
  7505. var offsetLocation = offsetLocations[index];
  7506. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7507. this._gl.enableVertexAttribArray(offsetLocation);
  7508. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7509. }
  7510. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7511. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7512. this._currentInstanceLocations.push(offsetLocation);
  7513. this._currentInstanceBuffers.push(instancesBuffer);
  7514. }
  7515. }
  7516. };
  7517. Engine.prototype.applyStates = function () {
  7518. this._depthCullingState.apply(this._gl);
  7519. this._stencilState.apply(this._gl);
  7520. this._alphaState.apply(this._gl);
  7521. };
  7522. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7523. // Apply states
  7524. this.applyStates();
  7525. this._drawCalls.addCount(1, false);
  7526. // Render
  7527. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7528. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7529. if (instancesCount) {
  7530. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7531. return;
  7532. }
  7533. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7534. };
  7535. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7536. // Apply states
  7537. this.applyStates();
  7538. this._drawCalls.addCount(1, false);
  7539. if (instancesCount) {
  7540. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7541. return;
  7542. }
  7543. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7544. };
  7545. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7546. // Apply states
  7547. this.applyStates();
  7548. this._drawCalls.addCount(1, false);
  7549. if (instancesCount) {
  7550. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7551. return;
  7552. }
  7553. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7554. };
  7555. // Shaders
  7556. Engine.prototype._releaseEffect = function (effect) {
  7557. if (this._compiledEffects[effect._key]) {
  7558. delete this._compiledEffects[effect._key];
  7559. if (effect.getProgram()) {
  7560. this._gl.deleteProgram(effect.getProgram());
  7561. }
  7562. }
  7563. };
  7564. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7565. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7566. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7567. var name = vertex + "+" + fragment + "@" + defines;
  7568. if (this._compiledEffects[name]) {
  7569. return this._compiledEffects[name];
  7570. }
  7571. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7572. effect._key = name;
  7573. this._compiledEffects[name] = effect;
  7574. return effect;
  7575. };
  7576. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7577. if (uniformsNames === void 0) { uniformsNames = []; }
  7578. if (samplers === void 0) { samplers = []; }
  7579. if (defines === void 0) { defines = ""; }
  7580. return this.createEffect({
  7581. vertex: "particles",
  7582. fragmentElement: fragmentName
  7583. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7584. };
  7585. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7586. context = context || this._gl;
  7587. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7588. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7589. var shaderProgram = context.createProgram();
  7590. context.attachShader(shaderProgram, vertexShader);
  7591. context.attachShader(shaderProgram, fragmentShader);
  7592. context.linkProgram(shaderProgram);
  7593. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7594. if (!linked) {
  7595. var error = context.getProgramInfoLog(shaderProgram);
  7596. if (error) {
  7597. throw new Error(error);
  7598. }
  7599. }
  7600. context.deleteShader(vertexShader);
  7601. context.deleteShader(fragmentShader);
  7602. return shaderProgram;
  7603. };
  7604. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7605. var results = [];
  7606. for (var index = 0; index < uniformsNames.length; index++) {
  7607. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7608. }
  7609. return results;
  7610. };
  7611. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7612. var results = [];
  7613. for (var index = 0; index < attributesNames.length; index++) {
  7614. try {
  7615. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7616. }
  7617. catch (e) {
  7618. results.push(-1);
  7619. }
  7620. }
  7621. return results;
  7622. };
  7623. Engine.prototype.enableEffect = function (effect) {
  7624. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7625. // if (effect && effect.onBind) {
  7626. // effect.onBind(effect);
  7627. // }
  7628. // return;
  7629. //}
  7630. // Use program
  7631. this.setProgram(effect.getProgram());
  7632. this._currentEffect = effect;
  7633. if (effect.onBind) {
  7634. effect.onBind(effect);
  7635. }
  7636. };
  7637. Engine.prototype.setIntArray = function (uniform, array) {
  7638. if (!uniform)
  7639. return;
  7640. this._gl.uniform1iv(uniform, array);
  7641. };
  7642. Engine.prototype.setIntArray2 = function (uniform, array) {
  7643. if (!uniform || array.length % 2 !== 0)
  7644. return;
  7645. this._gl.uniform2iv(uniform, array);
  7646. };
  7647. Engine.prototype.setIntArray3 = function (uniform, array) {
  7648. if (!uniform || array.length % 3 !== 0)
  7649. return;
  7650. this._gl.uniform3iv(uniform, array);
  7651. };
  7652. Engine.prototype.setIntArray4 = function (uniform, array) {
  7653. if (!uniform || array.length % 4 !== 0)
  7654. return;
  7655. this._gl.uniform4iv(uniform, array);
  7656. };
  7657. Engine.prototype.setFloatArray = function (uniform, array) {
  7658. if (!uniform)
  7659. return;
  7660. this._gl.uniform1fv(uniform, array);
  7661. };
  7662. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7663. if (!uniform || array.length % 2 !== 0)
  7664. return;
  7665. this._gl.uniform2fv(uniform, array);
  7666. };
  7667. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7668. if (!uniform || array.length % 3 !== 0)
  7669. return;
  7670. this._gl.uniform3fv(uniform, array);
  7671. };
  7672. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7673. if (!uniform || array.length % 4 !== 0)
  7674. return;
  7675. this._gl.uniform4fv(uniform, array);
  7676. };
  7677. Engine.prototype.setArray = function (uniform, array) {
  7678. if (!uniform)
  7679. return;
  7680. this._gl.uniform1fv(uniform, array);
  7681. };
  7682. Engine.prototype.setArray2 = function (uniform, array) {
  7683. if (!uniform || array.length % 2 !== 0)
  7684. return;
  7685. this._gl.uniform2fv(uniform, array);
  7686. };
  7687. Engine.prototype.setArray3 = function (uniform, array) {
  7688. if (!uniform || array.length % 3 !== 0)
  7689. return;
  7690. this._gl.uniform3fv(uniform, array);
  7691. };
  7692. Engine.prototype.setArray4 = function (uniform, array) {
  7693. if (!uniform || array.length % 4 !== 0)
  7694. return;
  7695. this._gl.uniform4fv(uniform, array);
  7696. };
  7697. Engine.prototype.setMatrices = function (uniform, matrices) {
  7698. if (!uniform)
  7699. return;
  7700. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7701. };
  7702. Engine.prototype.setMatrix = function (uniform, matrix) {
  7703. if (!uniform)
  7704. return;
  7705. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7706. };
  7707. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7708. if (!uniform)
  7709. return;
  7710. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7711. };
  7712. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7713. if (!uniform)
  7714. return;
  7715. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7716. };
  7717. Engine.prototype.setFloat = function (uniform, value) {
  7718. if (!uniform)
  7719. return;
  7720. this._gl.uniform1f(uniform, value);
  7721. };
  7722. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7723. if (!uniform)
  7724. return;
  7725. this._gl.uniform2f(uniform, x, y);
  7726. };
  7727. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7728. if (!uniform)
  7729. return;
  7730. this._gl.uniform3f(uniform, x, y, z);
  7731. };
  7732. Engine.prototype.setBool = function (uniform, bool) {
  7733. if (!uniform)
  7734. return;
  7735. this._gl.uniform1i(uniform, bool);
  7736. };
  7737. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7738. if (!uniform)
  7739. return;
  7740. this._gl.uniform4f(uniform, x, y, z, w);
  7741. };
  7742. Engine.prototype.setColor3 = function (uniform, color3) {
  7743. if (!uniform)
  7744. return;
  7745. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7746. };
  7747. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7748. if (!uniform)
  7749. return;
  7750. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7751. };
  7752. // States
  7753. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7754. if (zOffset === void 0) { zOffset = 0; }
  7755. if (reverseSide === void 0) { reverseSide = false; }
  7756. // Culling
  7757. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7758. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7759. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7760. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7761. if (culling) {
  7762. this._depthCullingState.cullFace = cullFace;
  7763. this._depthCullingState.cull = true;
  7764. }
  7765. else {
  7766. this._depthCullingState.cull = false;
  7767. }
  7768. }
  7769. // Z offset
  7770. this._depthCullingState.zOffset = zOffset;
  7771. };
  7772. Engine.prototype.setDepthBuffer = function (enable) {
  7773. this._depthCullingState.depthTest = enable;
  7774. };
  7775. Engine.prototype.getDepthWrite = function () {
  7776. return this._depthCullingState.depthMask;
  7777. };
  7778. Engine.prototype.setDepthWrite = function (enable) {
  7779. this._depthCullingState.depthMask = enable;
  7780. };
  7781. Engine.prototype.setColorWrite = function (enable) {
  7782. this._gl.colorMask(enable, enable, enable, enable);
  7783. };
  7784. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7785. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7786. if (this._alphaMode === mode) {
  7787. return;
  7788. }
  7789. switch (mode) {
  7790. case Engine.ALPHA_DISABLE:
  7791. this._alphaState.alphaBlend = false;
  7792. break;
  7793. case Engine.ALPHA_COMBINE:
  7794. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7795. this._alphaState.alphaBlend = true;
  7796. break;
  7797. case Engine.ALPHA_ONEONE:
  7798. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7799. this._alphaState.alphaBlend = true;
  7800. break;
  7801. case Engine.ALPHA_ADD:
  7802. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7803. this._alphaState.alphaBlend = true;
  7804. break;
  7805. case Engine.ALPHA_SUBTRACT:
  7806. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7807. this._alphaState.alphaBlend = true;
  7808. break;
  7809. case Engine.ALPHA_MULTIPLY:
  7810. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7811. this._alphaState.alphaBlend = true;
  7812. break;
  7813. case Engine.ALPHA_MAXIMIZED:
  7814. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7815. this._alphaState.alphaBlend = true;
  7816. break;
  7817. }
  7818. if (!noDepthWriteChange) {
  7819. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7820. }
  7821. this._alphaMode = mode;
  7822. };
  7823. Engine.prototype.getAlphaMode = function () {
  7824. return this._alphaMode;
  7825. };
  7826. Engine.prototype.setAlphaTesting = function (enable) {
  7827. this._alphaTest = enable;
  7828. };
  7829. Engine.prototype.getAlphaTesting = function () {
  7830. return this._alphaTest;
  7831. };
  7832. // Textures
  7833. Engine.prototype.wipeCaches = function () {
  7834. this.resetTextureCache();
  7835. this._currentEffect = null;
  7836. this._stencilState.reset();
  7837. this._depthCullingState.reset();
  7838. this.setDepthFunctionToLessOrEqual();
  7839. this._alphaState.reset();
  7840. this._cachedVertexBuffers = null;
  7841. this._cachedIndexBuffer = null;
  7842. this._cachedEffectForVertexBuffers = null;
  7843. };
  7844. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7845. var gl = this._gl;
  7846. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7847. var magFilter = gl.NEAREST;
  7848. var minFilter = gl.NEAREST;
  7849. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7850. magFilter = gl.LINEAR;
  7851. minFilter = gl.LINEAR;
  7852. }
  7853. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7854. magFilter = gl.LINEAR;
  7855. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7856. }
  7857. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7858. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7859. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7860. texture.samplingMode = samplingMode;
  7861. };
  7862. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  7863. var _this = this;
  7864. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  7865. if (onLoad === void 0) { onLoad = null; }
  7866. if (onError === void 0) { onError = null; }
  7867. if (buffer === void 0) { buffer = null; }
  7868. var texture = this._gl.createTexture();
  7869. var extension;
  7870. var fromData = false;
  7871. if (url.substr(0, 5) === "data:") {
  7872. fromData = true;
  7873. }
  7874. if (!fromData)
  7875. extension = url.substr(url.length - 4, 4).toLowerCase();
  7876. else {
  7877. var oldUrl = url;
  7878. fromData = oldUrl.split(':');
  7879. url = oldUrl;
  7880. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  7881. }
  7882. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  7883. var isTGA = (extension === ".tga");
  7884. scene._addPendingData(texture);
  7885. texture.url = url;
  7886. texture.noMipmap = noMipmap;
  7887. texture.references = 1;
  7888. texture.samplingMode = samplingMode;
  7889. texture.onLoadedCallbacks = [onLoad];
  7890. this._loadedTexturesCache.push(texture);
  7891. var onerror = function () {
  7892. scene._removePendingData(texture);
  7893. if (onError) {
  7894. onError();
  7895. }
  7896. };
  7897. var callback;
  7898. if (isTGA) {
  7899. callback = function (arrayBuffer) {
  7900. var data = new Uint8Array(arrayBuffer);
  7901. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  7902. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  7903. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  7904. }, samplingMode);
  7905. };
  7906. if (!(fromData instanceof Array))
  7907. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  7908. callback(arrayBuffer);
  7909. }, null, scene.database, true, onerror);
  7910. else
  7911. callback(buffer);
  7912. }
  7913. else if (isDDS) {
  7914. callback = function (data) {
  7915. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  7916. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  7917. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  7918. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  7919. }, samplingMode);
  7920. };
  7921. if (!(fromData instanceof Array))
  7922. BABYLON.Tools.LoadFile(url, function (data) {
  7923. callback(data);
  7924. }, null, scene.database, true, onerror);
  7925. else
  7926. callback(buffer);
  7927. }
  7928. else {
  7929. var onload = function (img) {
  7930. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  7931. var isPot = (img.width === potWidth && img.height === potHeight);
  7932. if (!isPot) {
  7933. _this._prepareWorkingCanvas();
  7934. _this._workingCanvas.width = potWidth;
  7935. _this._workingCanvas.height = potHeight;
  7936. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7937. _this._workingContext.imageSmoothingEnabled = false;
  7938. _this._workingContext.mozImageSmoothingEnabled = false;
  7939. _this._workingContext.oImageSmoothingEnabled = false;
  7940. _this._workingContext.webkitImageSmoothingEnabled = false;
  7941. _this._workingContext.msImageSmoothingEnabled = false;
  7942. }
  7943. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  7944. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  7945. _this._workingContext.imageSmoothingEnabled = true;
  7946. _this._workingContext.mozImageSmoothingEnabled = true;
  7947. _this._workingContext.oImageSmoothingEnabled = true;
  7948. _this._workingContext.webkitImageSmoothingEnabled = true;
  7949. _this._workingContext.msImageSmoothingEnabled = true;
  7950. }
  7951. }
  7952. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  7953. }, samplingMode);
  7954. };
  7955. if (!(fromData instanceof Array))
  7956. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  7957. else
  7958. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  7959. }
  7960. return texture;
  7961. };
  7962. Engine.prototype._getInternalFormat = function (format) {
  7963. var internalFormat = this._gl.RGBA;
  7964. switch (format) {
  7965. case Engine.TEXTUREFORMAT_ALPHA:
  7966. internalFormat = this._gl.ALPHA;
  7967. break;
  7968. case Engine.TEXTUREFORMAT_LUMINANCE:
  7969. internalFormat = this._gl.LUMINANCE;
  7970. break;
  7971. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  7972. internalFormat = this._gl.LUMINANCE_ALPHA;
  7973. break;
  7974. case Engine.TEXTUREFORMAT_RGB:
  7975. internalFormat = this._gl.RGB;
  7976. break;
  7977. case Engine.TEXTUREFORMAT_RGBA:
  7978. internalFormat = this._gl.RGBA;
  7979. break;
  7980. }
  7981. return internalFormat;
  7982. };
  7983. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  7984. if (compression === void 0) { compression = null; }
  7985. var internalFormat = this._getInternalFormat(format);
  7986. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  7987. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  7988. if (texture._width % 4 !== 0) {
  7989. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  7990. }
  7991. if (compression) {
  7992. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  7993. }
  7994. else {
  7995. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  7996. }
  7997. if (texture.generateMipMaps) {
  7998. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  7999. }
  8000. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8001. this.resetTextureCache();
  8002. texture.isReady = true;
  8003. };
  8004. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8005. if (compression === void 0) { compression = null; }
  8006. var texture = this._gl.createTexture();
  8007. texture._baseWidth = width;
  8008. texture._baseHeight = height;
  8009. texture._width = width;
  8010. texture._height = height;
  8011. texture.references = 1;
  8012. this.updateRawTexture(texture, data, format, invertY, compression);
  8013. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8014. // Filters
  8015. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8016. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8017. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8018. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8019. texture.samplingMode = samplingMode;
  8020. this._loadedTexturesCache.push(texture);
  8021. return texture;
  8022. };
  8023. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8024. var texture = this._gl.createTexture();
  8025. texture._baseWidth = width;
  8026. texture._baseHeight = height;
  8027. if (generateMipMaps) {
  8028. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8029. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8030. }
  8031. this.resetTextureCache();
  8032. texture._width = width;
  8033. texture._height = height;
  8034. texture.isReady = false;
  8035. texture.generateMipMaps = generateMipMaps;
  8036. texture.references = 1;
  8037. texture.samplingMode = samplingMode;
  8038. this.updateTextureSamplingMode(samplingMode, texture);
  8039. this._loadedTexturesCache.push(texture);
  8040. return texture;
  8041. };
  8042. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8043. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8044. if (texture.isCube) {
  8045. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8046. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8047. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8048. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8049. }
  8050. else {
  8051. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8052. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8053. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8054. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8055. }
  8056. };
  8057. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8058. if (premulAlpha === void 0) { premulAlpha = false; }
  8059. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8060. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8061. if (premulAlpha) {
  8062. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8063. }
  8064. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8065. if (texture.generateMipMaps) {
  8066. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8067. }
  8068. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8069. if (premulAlpha) {
  8070. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8071. }
  8072. this.resetTextureCache();
  8073. texture.isReady = true;
  8074. };
  8075. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8076. if (texture._isDisabled) {
  8077. return;
  8078. }
  8079. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8080. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8081. try {
  8082. // Testing video texture support
  8083. if (this._videoTextureSupported === undefined) {
  8084. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8085. if (this._gl.getError() !== 0) {
  8086. this._videoTextureSupported = false;
  8087. }
  8088. else {
  8089. this._videoTextureSupported = true;
  8090. }
  8091. }
  8092. // Copy video through the current working canvas if video texture is not supported
  8093. if (!this._videoTextureSupported) {
  8094. if (!texture._workingCanvas) {
  8095. texture._workingCanvas = document.createElement("canvas");
  8096. texture._workingContext = texture._workingCanvas.getContext("2d");
  8097. texture._workingCanvas.width = texture._width;
  8098. texture._workingCanvas.height = texture._height;
  8099. }
  8100. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8101. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8102. }
  8103. else {
  8104. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8105. }
  8106. if (texture.generateMipMaps) {
  8107. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8108. }
  8109. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8110. this.resetTextureCache();
  8111. texture.isReady = true;
  8112. }
  8113. catch (ex) {
  8114. // Something unexpected
  8115. // Let's disable the texture
  8116. texture._isDisabled = true;
  8117. }
  8118. };
  8119. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8120. // old version had a "generateMipMaps" arg instead of options.
  8121. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8122. // in the same way, generateDepthBuffer is defaulted to true
  8123. var generateMipMaps = false;
  8124. var generateDepthBuffer = true;
  8125. var generateStencilBuffer = false;
  8126. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8127. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8128. if (options !== undefined) {
  8129. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8130. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8131. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8132. type = options.type === undefined ? type : options.type;
  8133. if (options.samplingMode !== undefined) {
  8134. samplingMode = options.samplingMode;
  8135. }
  8136. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8137. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8138. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8139. }
  8140. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8141. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8142. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8143. }
  8144. }
  8145. var gl = this._gl;
  8146. var texture = gl.createTexture();
  8147. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8148. var width = size.width || size;
  8149. var height = size.height || size;
  8150. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8151. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8152. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8153. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8154. }
  8155. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8156. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8157. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8158. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8159. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8160. var depthStencilBuffer;
  8161. // Create the depth/stencil buffer
  8162. if (generateStencilBuffer) {
  8163. depthStencilBuffer = gl.createRenderbuffer();
  8164. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8165. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8166. }
  8167. else if (generateDepthBuffer) {
  8168. depthStencilBuffer = gl.createRenderbuffer();
  8169. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8170. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8171. }
  8172. // Create the framebuffer
  8173. var framebuffer = gl.createFramebuffer();
  8174. this.bindUnboundFramebuffer(framebuffer);
  8175. // Manage attachments
  8176. if (generateStencilBuffer) {
  8177. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8178. }
  8179. else if (generateDepthBuffer) {
  8180. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8181. }
  8182. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8183. if (generateMipMaps) {
  8184. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8185. }
  8186. // Unbind
  8187. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8188. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8189. this.bindUnboundFramebuffer(null);
  8190. texture._framebuffer = framebuffer;
  8191. if (generateDepthBuffer) {
  8192. texture._depthBuffer = depthStencilBuffer;
  8193. }
  8194. texture._baseWidth = width;
  8195. texture._baseHeight = height;
  8196. texture._width = width;
  8197. texture._height = height;
  8198. texture.isReady = true;
  8199. texture.generateMipMaps = generateMipMaps;
  8200. texture.references = 1;
  8201. texture.samplingMode = samplingMode;
  8202. texture.type = type;
  8203. this.resetTextureCache();
  8204. this._loadedTexturesCache.push(texture);
  8205. return texture;
  8206. };
  8207. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8208. var gl = this._gl;
  8209. var texture = gl.createTexture();
  8210. var generateMipMaps = true;
  8211. var generateDepthBuffer = true;
  8212. var generateStencilBuffer = false;
  8213. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8214. if (options !== undefined) {
  8215. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8216. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8217. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8218. if (options.samplingMode !== undefined) {
  8219. samplingMode = options.samplingMode;
  8220. }
  8221. }
  8222. texture.isCube = true;
  8223. texture.references = 1;
  8224. texture.generateMipMaps = generateMipMaps;
  8225. texture.references = 1;
  8226. texture.samplingMode = samplingMode;
  8227. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8228. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8229. for (var face = 0; face < 6; face++) {
  8230. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8231. }
  8232. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8233. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8234. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8235. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8236. // Create the depth buffer
  8237. var depthStencilBuffer;
  8238. // Create the depth/stencil buffer
  8239. if (generateStencilBuffer) {
  8240. depthStencilBuffer = gl.createRenderbuffer();
  8241. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8242. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8243. }
  8244. else if (generateDepthBuffer) {
  8245. depthStencilBuffer = gl.createRenderbuffer();
  8246. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8247. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8248. }
  8249. // Create the framebuffer
  8250. var framebuffer = gl.createFramebuffer();
  8251. this.bindUnboundFramebuffer(framebuffer);
  8252. // Manage attachments
  8253. if (generateStencilBuffer) {
  8254. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8255. }
  8256. else if (generateDepthBuffer) {
  8257. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8258. }
  8259. // Mipmaps
  8260. if (texture.generateMipMaps) {
  8261. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8262. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8263. }
  8264. // Unbind
  8265. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8266. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8267. this.bindUnboundFramebuffer(null);
  8268. texture._framebuffer = framebuffer;
  8269. if (generateDepthBuffer) {
  8270. texture._depthBuffer = depthStencilBuffer;
  8271. }
  8272. texture._width = size;
  8273. texture._height = size;
  8274. texture.isReady = true;
  8275. this.resetTextureCache();
  8276. this._loadedTexturesCache.push(texture);
  8277. return texture;
  8278. };
  8279. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8280. var _this = this;
  8281. if (onLoad === void 0) { onLoad = null; }
  8282. if (onError === void 0) { onError = null; }
  8283. var gl = this._gl;
  8284. var texture = gl.createTexture();
  8285. texture.isCube = true;
  8286. texture.url = rootUrl;
  8287. texture.references = 1;
  8288. texture.onLoadedCallbacks = [];
  8289. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8290. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8291. if (isDDS) {
  8292. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8293. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8294. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8295. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8296. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8297. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8298. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8299. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8300. }
  8301. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8302. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8303. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8304. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8305. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8306. _this.resetTextureCache();
  8307. texture._width = info.width;
  8308. texture._height = info.height;
  8309. texture.isReady = true;
  8310. }, null, null, true, onError);
  8311. }
  8312. else {
  8313. cascadeLoad(rootUrl, scene, function (imgs) {
  8314. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8315. var height = width;
  8316. _this._prepareWorkingCanvas();
  8317. _this._workingCanvas.width = width;
  8318. _this._workingCanvas.height = height;
  8319. var faces = [
  8320. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8321. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8322. ];
  8323. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8324. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8325. for (var index = 0; index < faces.length; index++) {
  8326. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8327. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8328. }
  8329. if (!noMipmap) {
  8330. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8331. }
  8332. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8333. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8334. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8335. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8336. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8337. _this.resetTextureCache();
  8338. texture._width = width;
  8339. texture._height = height;
  8340. texture.isReady = true;
  8341. texture.onLoadedCallbacks.forEach(function (callback) {
  8342. callback();
  8343. });
  8344. if (onLoad) {
  8345. onLoad();
  8346. }
  8347. }, files, onError);
  8348. }
  8349. this._loadedTexturesCache.push(texture);
  8350. return texture;
  8351. };
  8352. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8353. texture._width = width;
  8354. texture._height = height;
  8355. texture._size = width * height;
  8356. texture._baseWidth = width;
  8357. texture._baseHeight = height;
  8358. };
  8359. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8360. var _this = this;
  8361. var gl = this._gl;
  8362. var texture = gl.createTexture();
  8363. scene._addPendingData(texture);
  8364. texture.isCube = true;
  8365. texture.references = 1;
  8366. texture.url = url;
  8367. var internalFormat = this._getInternalFormat(format);
  8368. var textureType = gl.UNSIGNED_BYTE;
  8369. if (type === Engine.TEXTURETYPE_FLOAT) {
  8370. textureType = gl.FLOAT;
  8371. }
  8372. var width = size;
  8373. var height = width;
  8374. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8375. texture._width = width;
  8376. texture._height = height;
  8377. var onerror = function () {
  8378. scene._removePendingData(texture);
  8379. };
  8380. var internalCallback = function (data) {
  8381. var rgbeDataArrays = callback(data);
  8382. var facesIndex = [
  8383. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8384. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8385. ];
  8386. width = texture._width;
  8387. height = texture._height;
  8388. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8389. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8390. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8391. if (!noMipmap && isPot) {
  8392. if (mipmmapGenerator) {
  8393. var arrayTemp = [];
  8394. // Data are known to be in +X +Y +Z -X -Y -Z
  8395. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8396. arrayTemp.push(rgbeDataArrays[0]); // +X
  8397. arrayTemp.push(rgbeDataArrays[3]); // -X
  8398. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8399. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8400. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8401. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8402. var mipData = mipmmapGenerator(arrayTemp);
  8403. for (var level = 0; level < mipData.length; level++) {
  8404. var mipSize = width >> level;
  8405. // mipData is order in +X -X +Y -Y +Z -Z
  8406. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8407. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8408. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8409. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8410. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8411. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8412. }
  8413. }
  8414. else {
  8415. // Data are known to be in +X +Y +Z -X -Y -Z
  8416. for (var index = 0; index < facesIndex.length; index++) {
  8417. var faceData = rgbeDataArrays[index];
  8418. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8419. }
  8420. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8421. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8422. // By following the webgl standard changes from Revision 7, 2014/11/24
  8423. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8424. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8425. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8426. // Data are known to be in +X +Y +Z -X -Y -Z
  8427. for (var index = 0; index < facesIndex.length; index++) {
  8428. var faceData = rgbeDataArrays[index];
  8429. // Create a new RGBA Face.
  8430. var newFaceData = new Float32Array(width * height * 4);
  8431. for (var x = 0; x < width; x++) {
  8432. for (var y = 0; y < height; y++) {
  8433. var index_1 = (y * width + x) * 3;
  8434. var newIndex = (y * width + x) * 4;
  8435. // Map Old Value to new value.
  8436. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8437. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8438. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8439. // Add fully opaque alpha channel.
  8440. newFaceData[newIndex + 3] = 1;
  8441. }
  8442. }
  8443. // Reupload the face.
  8444. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8445. }
  8446. // Try to generate mipmap again.
  8447. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8448. }
  8449. }
  8450. }
  8451. else {
  8452. noMipmap = true;
  8453. }
  8454. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8455. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8456. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8457. }
  8458. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8459. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8460. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8461. }
  8462. else {
  8463. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8464. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8465. }
  8466. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8467. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8468. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8469. texture.isReady = true;
  8470. _this.resetTextureCache();
  8471. scene._removePendingData(texture);
  8472. };
  8473. BABYLON.Tools.LoadFile(url, function (data) {
  8474. internalCallback(data);
  8475. }, onerror, scene.database, true);
  8476. return texture;
  8477. };
  8478. ;
  8479. Engine.prototype._releaseTexture = function (texture) {
  8480. var gl = this._gl;
  8481. if (texture._framebuffer) {
  8482. gl.deleteFramebuffer(texture._framebuffer);
  8483. }
  8484. if (texture._depthBuffer) {
  8485. gl.deleteRenderbuffer(texture._depthBuffer);
  8486. }
  8487. gl.deleteTexture(texture);
  8488. // Unbind channels
  8489. this.unbindAllTextures();
  8490. var index = this._loadedTexturesCache.indexOf(texture);
  8491. if (index !== -1) {
  8492. this._loadedTexturesCache.splice(index, 1);
  8493. }
  8494. };
  8495. Engine.prototype.setProgram = function (program) {
  8496. if (this._currentProgram !== program) {
  8497. this._gl.useProgram(program);
  8498. this._currentProgram = program;
  8499. }
  8500. };
  8501. Engine.prototype.bindSamplers = function (effect) {
  8502. this.setProgram(effect.getProgram());
  8503. var samplers = effect.getSamplers();
  8504. for (var index = 0; index < samplers.length; index++) {
  8505. var uniform = effect.getUniform(samplers[index]);
  8506. this._gl.uniform1i(uniform, index);
  8507. }
  8508. this._currentEffect = null;
  8509. };
  8510. Engine.prototype.activateTexture = function (texture) {
  8511. if (this._activeTexture !== texture) {
  8512. this._gl.activeTexture(texture);
  8513. this._activeTexture = texture;
  8514. }
  8515. };
  8516. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8517. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8518. this._gl.bindTexture(target, texture);
  8519. this._activeTexturesCache[this._activeTexture] = texture;
  8520. }
  8521. };
  8522. Engine.prototype._bindTexture = function (channel, texture) {
  8523. if (channel < 0) {
  8524. return;
  8525. }
  8526. this.activateTexture(this._gl["TEXTURE" + channel]);
  8527. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8528. };
  8529. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8530. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8531. };
  8532. Engine.prototype.unbindAllTextures = function () {
  8533. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8534. this.activateTexture(this._gl["TEXTURE" + channel]);
  8535. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8536. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8537. }
  8538. };
  8539. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8540. if (channel < 0) {
  8541. return;
  8542. }
  8543. this._gl.uniform1i(uniform, channel);
  8544. this._setTexture(channel, texture);
  8545. };
  8546. Engine.prototype._setTexture = function (channel, texture) {
  8547. // Not ready?
  8548. if (!texture || !texture.isReady()) {
  8549. if (this._activeTexturesCache[channel] != null) {
  8550. this.activateTexture(this._gl["TEXTURE" + channel]);
  8551. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8552. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8553. }
  8554. return;
  8555. }
  8556. // Video
  8557. var alreadyActivated = false;
  8558. if (texture instanceof BABYLON.VideoTexture) {
  8559. this.activateTexture(this._gl["TEXTURE" + channel]);
  8560. alreadyActivated = true;
  8561. texture.update();
  8562. }
  8563. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8564. texture.delayLoad();
  8565. return;
  8566. }
  8567. var internalTexture = texture.getInternalTexture();
  8568. if (this._activeTexturesCache[channel] === internalTexture) {
  8569. return;
  8570. }
  8571. if (!alreadyActivated) {
  8572. this.activateTexture(this._gl["TEXTURE" + channel]);
  8573. }
  8574. if (internalTexture.isCube) {
  8575. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8576. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8577. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8578. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8579. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8580. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8581. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8582. }
  8583. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8584. }
  8585. else {
  8586. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8587. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8588. internalTexture._cachedWrapU = texture.wrapU;
  8589. switch (texture.wrapU) {
  8590. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8591. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8592. break;
  8593. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8594. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8595. break;
  8596. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8597. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8598. break;
  8599. }
  8600. }
  8601. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8602. internalTexture._cachedWrapV = texture.wrapV;
  8603. switch (texture.wrapV) {
  8604. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8605. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8606. break;
  8607. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8608. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8609. break;
  8610. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8611. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8612. break;
  8613. }
  8614. }
  8615. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8616. }
  8617. };
  8618. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8619. if (channel < 0) {
  8620. return;
  8621. }
  8622. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8623. this._textureUnits = new Int32Array(textures.length);
  8624. }
  8625. for (var i = 0; i < textures.length; i++) {
  8626. this._textureUnits[i] = channel + i;
  8627. }
  8628. this._gl.uniform1iv(uniform, this._textureUnits);
  8629. for (var index = 0; index < textures.length; index++) {
  8630. this._setTexture(channel + index, textures[index]);
  8631. }
  8632. };
  8633. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8634. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8635. var value = texture.anisotropicFilteringLevel;
  8636. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8637. value = 1;
  8638. }
  8639. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8640. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8641. texture._cachedAnisotropicFilteringLevel = value;
  8642. }
  8643. };
  8644. Engine.prototype.readPixels = function (x, y, width, height) {
  8645. var data = new Uint8Array(height * width * 4);
  8646. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8647. return data;
  8648. };
  8649. /**
  8650. * Add an externaly attached data from its key.
  8651. * This method call will fail and return false, if such key already exists.
  8652. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8653. * @param key the unique key that identifies the data
  8654. * @param data the data object to associate to the key for this Engine instance
  8655. * @return true if no such key were already present and the data was added successfully, false otherwise
  8656. */
  8657. Engine.prototype.addExternalData = function (key, data) {
  8658. return this._externalData.add(key, data);
  8659. };
  8660. /**
  8661. * Get an externaly attached data from its key
  8662. * @param key the unique key that identifies the data
  8663. * @return the associated data, if present (can be null), or undefined if not present
  8664. */
  8665. Engine.prototype.getExternalData = function (key) {
  8666. return this._externalData.get(key);
  8667. };
  8668. /**
  8669. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8670. * @param key the unique key that identifies the data
  8671. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8672. * @return the associated data, can be null if the factory returned null.
  8673. */
  8674. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8675. return this._externalData.getOrAddWithFactory(key, factory);
  8676. };
  8677. /**
  8678. * Remove an externaly attached data from the Engine instance
  8679. * @param key the unique key that identifies the data
  8680. * @return true if the data was successfully removed, false if it doesn't exist
  8681. */
  8682. Engine.prototype.removeExternalData = function (key) {
  8683. return this._externalData.remove(key);
  8684. };
  8685. Engine.prototype.releaseInternalTexture = function (texture) {
  8686. if (!texture) {
  8687. return;
  8688. }
  8689. texture.references--;
  8690. // Final reference ?
  8691. if (texture.references === 0) {
  8692. var texturesCache = this.getLoadedTexturesCache();
  8693. var index = texturesCache.indexOf(texture);
  8694. if (index > -1) {
  8695. texturesCache.splice(index, 1);
  8696. }
  8697. this._releaseTexture(texture);
  8698. }
  8699. };
  8700. Engine.prototype.unbindAllAttributes = function () {
  8701. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8702. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8703. continue;
  8704. }
  8705. this._gl.disableVertexAttribArray(i);
  8706. this._vertexAttribArraysEnabled[i] = false;
  8707. }
  8708. };
  8709. // Dispose
  8710. Engine.prototype.dispose = function () {
  8711. this.hideLoadingUI();
  8712. this.stopRenderLoop();
  8713. // Release scenes
  8714. while (this.scenes.length) {
  8715. this.scenes[0].dispose();
  8716. }
  8717. // Release audio engine
  8718. Engine.audioEngine.dispose();
  8719. // Release effects
  8720. for (var name in this._compiledEffects) {
  8721. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8722. }
  8723. // Unbind
  8724. this.unbindAllAttributes();
  8725. this._gl = null;
  8726. //WebVR
  8727. this.disableVR();
  8728. // Events
  8729. window.removeEventListener("blur", this._onBlur);
  8730. window.removeEventListener("focus", this._onFocus);
  8731. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8732. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8733. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8734. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8735. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8736. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8737. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8738. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8739. };
  8740. // Loading screen
  8741. Engine.prototype.displayLoadingUI = function () {
  8742. this._loadingScreen.displayLoadingUI();
  8743. };
  8744. Engine.prototype.hideLoadingUI = function () {
  8745. this._loadingScreen.hideLoadingUI();
  8746. };
  8747. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8748. get: function () {
  8749. return this._loadingScreen;
  8750. },
  8751. set: function (loadingScreen) {
  8752. this._loadingScreen = loadingScreen;
  8753. },
  8754. enumerable: true,
  8755. configurable: true
  8756. });
  8757. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8758. set: function (text) {
  8759. this._loadingScreen.loadingUIText = text;
  8760. },
  8761. enumerable: true,
  8762. configurable: true
  8763. });
  8764. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8765. set: function (color) {
  8766. this._loadingScreen.loadingUIBackgroundColor = color;
  8767. },
  8768. enumerable: true,
  8769. configurable: true
  8770. });
  8771. Engine.prototype.attachContextLostEvent = function (callback) {
  8772. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8773. };
  8774. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8775. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8776. };
  8777. // FPS
  8778. Engine.prototype.getFps = function () {
  8779. return this.fps;
  8780. };
  8781. Engine.prototype.getDeltaTime = function () {
  8782. return this.deltaTime;
  8783. };
  8784. Engine.prototype._measureFps = function () {
  8785. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8786. var length = this.previousFramesDuration.length;
  8787. if (length >= 2) {
  8788. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8789. }
  8790. if (length >= this.fpsRange) {
  8791. if (length > this.fpsRange) {
  8792. this.previousFramesDuration.splice(0, 1);
  8793. length = this.previousFramesDuration.length;
  8794. }
  8795. var sum = 0;
  8796. for (var id = 0; id < length - 1; id++) {
  8797. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8798. }
  8799. this.fps = 1000.0 / (sum / (length - 1));
  8800. }
  8801. };
  8802. Engine.prototype._canRenderToFloatTexture = function () {
  8803. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8804. };
  8805. Engine.prototype._canRenderToHalfFloatTexture = function () {
  8806. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  8807. };
  8808. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  8809. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  8810. var tempcanvas = document.createElement("canvas");
  8811. tempcanvas.height = 16;
  8812. tempcanvas.width = 16;
  8813. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  8814. // extension.
  8815. var ext = gl.getExtension(extension);
  8816. if (!ext) {
  8817. return false;
  8818. }
  8819. // setup GLSL program
  8820. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  8821. 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 }";
  8822. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  8823. gl.useProgram(program);
  8824. // look up where the vertex data needs to go.
  8825. var positionLocation = gl.getAttribLocation(program, "a_position");
  8826. var colorLoc = gl.getUniformLocation(program, "u_color");
  8827. // provide texture coordinates for the rectangle.
  8828. var positionBuffer = gl.createBuffer();
  8829. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  8830. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  8831. -1.0, -1.0,
  8832. 1.0, -1.0,
  8833. -1.0, 1.0,
  8834. -1.0, 1.0,
  8835. 1.0, -1.0,
  8836. 1.0, 1.0]), gl.STATIC_DRAW);
  8837. gl.enableVertexAttribArray(positionLocation);
  8838. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  8839. var whiteTex = gl.createTexture();
  8840. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8841. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  8842. var tex = gl.createTexture();
  8843. gl.bindTexture(gl.TEXTURE_2D, tex);
  8844. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  8845. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8846. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8847. var fb = gl.createFramebuffer();
  8848. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  8849. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  8850. var cleanup = function () {
  8851. gl.deleteProgram(program);
  8852. gl.disableVertexAttribArray(positionLocation);
  8853. gl.deleteBuffer(positionBuffer);
  8854. gl.deleteFramebuffer(fb);
  8855. gl.deleteTexture(whiteTex);
  8856. gl.deleteTexture(tex);
  8857. };
  8858. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  8859. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  8860. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  8861. cleanup();
  8862. return false;
  8863. }
  8864. // Draw the rectangle.
  8865. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  8866. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  8867. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8868. gl.bindTexture(gl.TEXTURE_2D, tex);
  8869. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  8870. gl.clearColor(1, 0, 0, 1);
  8871. gl.clear(gl.COLOR_BUFFER_BIT);
  8872. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  8873. gl.drawArrays(gl.TRIANGLES, 0, 6);
  8874. var pixel = new Uint8Array(4);
  8875. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  8876. if (pixel[0] !== 0 ||
  8877. pixel[1] < 248 ||
  8878. pixel[2] < 248 ||
  8879. pixel[3] < 254) {
  8880. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  8881. cleanup();
  8882. return false;
  8883. }
  8884. // Succesfully rendered to "format" texture.
  8885. cleanup();
  8886. return true;
  8887. };
  8888. // Statics
  8889. Engine.isSupported = function () {
  8890. try {
  8891. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  8892. if (navigator.isCocoonJS) {
  8893. return true;
  8894. }
  8895. var tempcanvas = document.createElement("canvas");
  8896. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  8897. return gl != null && !!window.WebGLRenderingContext;
  8898. }
  8899. catch (e) {
  8900. return false;
  8901. }
  8902. };
  8903. // Const statics
  8904. Engine._ALPHA_DISABLE = 0;
  8905. Engine._ALPHA_ADD = 1;
  8906. Engine._ALPHA_COMBINE = 2;
  8907. Engine._ALPHA_SUBTRACT = 3;
  8908. Engine._ALPHA_MULTIPLY = 4;
  8909. Engine._ALPHA_MAXIMIZED = 5;
  8910. Engine._ALPHA_ONEONE = 6;
  8911. Engine._DELAYLOADSTATE_NONE = 0;
  8912. Engine._DELAYLOADSTATE_LOADED = 1;
  8913. Engine._DELAYLOADSTATE_LOADING = 2;
  8914. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  8915. Engine._TEXTUREFORMAT_ALPHA = 0;
  8916. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  8917. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  8918. Engine._TEXTUREFORMAT_RGB = 4;
  8919. Engine._TEXTUREFORMAT_RGBA = 5;
  8920. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  8921. Engine._TEXTURETYPE_FLOAT = 1;
  8922. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  8923. // Depht or Stencil test Constants.
  8924. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  8925. 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.
  8926. 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.
  8927. 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.
  8928. 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.
  8929. 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.
  8930. 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.
  8931. 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.
  8932. // Stencil Actions Constants.
  8933. Engine._KEEP = 0x1E00;
  8934. Engine._REPLACE = 0x1E01;
  8935. Engine._INCR = 0x1E02;
  8936. Engine._DECR = 0x1E03;
  8937. Engine._INVERT = 0x150A;
  8938. Engine._INCR_WRAP = 0x8507;
  8939. Engine._DECR_WRAP = 0x8508;
  8940. // Updatable statics so stick with vars here
  8941. Engine.CollisionsEpsilon = 0.001;
  8942. Engine.CodeRepository = "src/";
  8943. Engine.ShadersRepository = "src/Shaders/";
  8944. return Engine;
  8945. }());
  8946. BABYLON.Engine = Engine;
  8947. })(BABYLON || (BABYLON = {}));
  8948. var BABYLON;
  8949. (function (BABYLON) {
  8950. /**
  8951. * Node is the basic class for all scene objects (Mesh, Light Camera).
  8952. */
  8953. var Node = (function () {
  8954. /**
  8955. * @constructor
  8956. * @param {string} name - the name and id to be given to this node
  8957. * @param {BABYLON.Scene} the scene this node will be added to
  8958. */
  8959. function Node(name, scene) {
  8960. this.state = "";
  8961. this.metadata = null;
  8962. this.animations = new Array();
  8963. this._ranges = {};
  8964. this._childrenFlag = -1;
  8965. this._isEnabled = true;
  8966. this._isReady = true;
  8967. this._currentRenderId = -1;
  8968. this._parentRenderId = -1;
  8969. this.name = name;
  8970. this.id = name;
  8971. this._scene = scene;
  8972. this._initCache();
  8973. }
  8974. Object.defineProperty(Node.prototype, "parent", {
  8975. get: function () {
  8976. return this._parentNode;
  8977. },
  8978. set: function (parent) {
  8979. if (this._parentNode === parent) {
  8980. return;
  8981. }
  8982. if (this._parentNode) {
  8983. var index = this._parentNode._children.indexOf(this);
  8984. if (index !== -1) {
  8985. this._parentNode._children.splice(index, 1);
  8986. }
  8987. }
  8988. this._parentNode = parent;
  8989. if (this._parentNode) {
  8990. if (!this._parentNode._children) {
  8991. this._parentNode._children = new Array();
  8992. }
  8993. this._parentNode._children.push(this);
  8994. }
  8995. },
  8996. enumerable: true,
  8997. configurable: true
  8998. });
  8999. Node.prototype.getScene = function () {
  9000. return this._scene;
  9001. };
  9002. Node.prototype.getEngine = function () {
  9003. return this._scene.getEngine();
  9004. };
  9005. // override it in derived class
  9006. Node.prototype.getWorldMatrix = function () {
  9007. return BABYLON.Matrix.Identity();
  9008. };
  9009. // override it in derived class if you add new variables to the cache
  9010. // and call the parent class method
  9011. Node.prototype._initCache = function () {
  9012. this._cache = {};
  9013. this._cache.parent = undefined;
  9014. };
  9015. Node.prototype.updateCache = function (force) {
  9016. if (!force && this.isSynchronized())
  9017. return;
  9018. this._cache.parent = this.parent;
  9019. this._updateCache();
  9020. };
  9021. // override it in derived class if you add new variables to the cache
  9022. // and call the parent class method if !ignoreParentClass
  9023. Node.prototype._updateCache = function (ignoreParentClass) {
  9024. };
  9025. // override it in derived class if you add new variables to the cache
  9026. Node.prototype._isSynchronized = function () {
  9027. return true;
  9028. };
  9029. Node.prototype._markSyncedWithParent = function () {
  9030. this._parentRenderId = this.parent._currentRenderId;
  9031. };
  9032. Node.prototype.isSynchronizedWithParent = function () {
  9033. if (!this.parent) {
  9034. return true;
  9035. }
  9036. if (this._parentRenderId !== this.parent._currentRenderId) {
  9037. return false;
  9038. }
  9039. return this.parent.isSynchronized();
  9040. };
  9041. Node.prototype.isSynchronized = function (updateCache) {
  9042. var check = this.hasNewParent();
  9043. check = check || !this.isSynchronizedWithParent();
  9044. check = check || !this._isSynchronized();
  9045. if (updateCache)
  9046. this.updateCache(true);
  9047. return !check;
  9048. };
  9049. Node.prototype.hasNewParent = function (update) {
  9050. if (this._cache.parent === this.parent)
  9051. return false;
  9052. if (update)
  9053. this._cache.parent = this.parent;
  9054. return true;
  9055. };
  9056. /**
  9057. * Is this node ready to be used/rendered
  9058. * @return {boolean} is it ready
  9059. */
  9060. Node.prototype.isReady = function () {
  9061. return this._isReady;
  9062. };
  9063. /**
  9064. * Is this node enabled.
  9065. * If the node has a parent and is enabled, the parent will be inspected as well.
  9066. * @return {boolean} whether this node (and its parent) is enabled.
  9067. * @see setEnabled
  9068. */
  9069. Node.prototype.isEnabled = function () {
  9070. if (!this._isEnabled) {
  9071. return false;
  9072. }
  9073. if (this.parent) {
  9074. return this.parent.isEnabled();
  9075. }
  9076. return true;
  9077. };
  9078. /**
  9079. * Set the enabled state of this node.
  9080. * @param {boolean} value - the new enabled state
  9081. * @see isEnabled
  9082. */
  9083. Node.prototype.setEnabled = function (value) {
  9084. this._isEnabled = value;
  9085. };
  9086. /**
  9087. * Is this node a descendant of the given node.
  9088. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9089. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9090. * @see parent
  9091. */
  9092. Node.prototype.isDescendantOf = function (ancestor) {
  9093. if (this.parent) {
  9094. if (this.parent === ancestor) {
  9095. return true;
  9096. }
  9097. return this.parent.isDescendantOf(ancestor);
  9098. }
  9099. return false;
  9100. };
  9101. /**
  9102. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9103. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9104. * @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.
  9105. * @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.
  9106. */
  9107. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9108. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9109. if (!this._children) {
  9110. return;
  9111. }
  9112. for (var index = 0; index < this._children.length; index++) {
  9113. var item = this._children[index];
  9114. if (!predicate || predicate(item)) {
  9115. results.push(item);
  9116. }
  9117. if (!directDescendantsOnly) {
  9118. item._getDescendants(results, false, predicate);
  9119. }
  9120. }
  9121. };
  9122. /**
  9123. * Will return all nodes that have this node as ascendant.
  9124. * @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.
  9125. * @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.
  9126. * @return {BABYLON.Node[]} all children nodes of all types.
  9127. */
  9128. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9129. var results = [];
  9130. this._getDescendants(results, directDescendantsOnly, predicate);
  9131. return results;
  9132. };
  9133. /**
  9134. * @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.
  9135. * @Deprecated, legacy support.
  9136. * use getDecendants instead.
  9137. */
  9138. Node.prototype.getChildren = function (predicate) {
  9139. return this.getDescendants(true, predicate);
  9140. };
  9141. /**
  9142. * Get all child-meshes of this node.
  9143. */
  9144. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9145. var results = [];
  9146. this._getDescendants(results, directDecendantsOnly, function (node) {
  9147. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9148. });
  9149. return results;
  9150. };
  9151. Node.prototype._setReady = function (state) {
  9152. if (state === this._isReady) {
  9153. return;
  9154. }
  9155. if (!state) {
  9156. this._isReady = false;
  9157. return;
  9158. }
  9159. this._isReady = true;
  9160. if (this.onReady) {
  9161. this.onReady(this);
  9162. }
  9163. };
  9164. Node.prototype.getAnimationByName = function (name) {
  9165. for (var i = 0; i < this.animations.length; i++) {
  9166. var animation = this.animations[i];
  9167. if (animation.name === name) {
  9168. return animation;
  9169. }
  9170. }
  9171. return null;
  9172. };
  9173. Node.prototype.createAnimationRange = function (name, from, to) {
  9174. // check name not already in use
  9175. if (!this._ranges[name]) {
  9176. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9177. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9178. if (this.animations[i]) {
  9179. this.animations[i].createRange(name, from, to);
  9180. }
  9181. }
  9182. }
  9183. };
  9184. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9185. if (deleteFrames === void 0) { deleteFrames = true; }
  9186. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9187. if (this.animations[i]) {
  9188. this.animations[i].deleteRange(name, deleteFrames);
  9189. }
  9190. }
  9191. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9192. };
  9193. Node.prototype.getAnimationRange = function (name) {
  9194. return this._ranges[name];
  9195. };
  9196. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9197. var range = this.getAnimationRange(name);
  9198. if (!range) {
  9199. return null;
  9200. }
  9201. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9202. };
  9203. Node.prototype.serializeAnimationRanges = function () {
  9204. var serializationRanges = [];
  9205. for (var name in this._ranges) {
  9206. var range = {};
  9207. range.name = name;
  9208. range.from = this._ranges[name].from;
  9209. range.to = this._ranges[name].to;
  9210. serializationRanges.push(range);
  9211. }
  9212. return serializationRanges;
  9213. };
  9214. Node.prototype.dispose = function () {
  9215. this.parent = null;
  9216. };
  9217. Node.prototype.getDirection = function (localAxis) {
  9218. var result = BABYLON.Vector3.Zero();
  9219. this.getDirectionToRef(localAxis, result);
  9220. return result;
  9221. };
  9222. Node.prototype.getDirectionToRef = function (localAxis, result) {
  9223. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  9224. };
  9225. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9226. if (parsedNode.ranges) {
  9227. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9228. var data = parsedNode.ranges[index];
  9229. node.createAnimationRange(data.name, data.from, data.to);
  9230. }
  9231. }
  9232. };
  9233. __decorate([
  9234. BABYLON.serialize()
  9235. ], Node.prototype, "name", void 0);
  9236. __decorate([
  9237. BABYLON.serialize()
  9238. ], Node.prototype, "id", void 0);
  9239. __decorate([
  9240. BABYLON.serialize()
  9241. ], Node.prototype, "uniqueId", void 0);
  9242. __decorate([
  9243. BABYLON.serialize()
  9244. ], Node.prototype, "state", void 0);
  9245. __decorate([
  9246. BABYLON.serialize()
  9247. ], Node.prototype, "metadata", void 0);
  9248. return Node;
  9249. }());
  9250. BABYLON.Node = Node;
  9251. })(BABYLON || (BABYLON = {}));
  9252. var BABYLON;
  9253. (function (BABYLON) {
  9254. var FilesInput = (function () {
  9255. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9256. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9257. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9258. this._engine = p_engine;
  9259. this._canvas = p_canvas;
  9260. this._currentScene = p_scene;
  9261. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9262. this._progressCallback = p_progressCallback;
  9263. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9264. this._textureLoadingCallback = p_textureLoadingCallback;
  9265. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9266. }
  9267. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9268. var _this = this;
  9269. if (p_elementToMonitor) {
  9270. this._elementToMonitor = p_elementToMonitor;
  9271. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9272. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9273. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9274. }
  9275. };
  9276. FilesInput.prototype.renderFunction = function () {
  9277. if (this._additionnalRenderLoopLogicCallback) {
  9278. this._additionnalRenderLoopLogicCallback();
  9279. }
  9280. if (this._currentScene) {
  9281. if (this._textureLoadingCallback) {
  9282. var remaining = this._currentScene.getWaitingItemsCount();
  9283. if (remaining > 0) {
  9284. this._textureLoadingCallback(remaining);
  9285. }
  9286. }
  9287. this._currentScene.render();
  9288. }
  9289. };
  9290. FilesInput.prototype.drag = function (e) {
  9291. e.stopPropagation();
  9292. e.preventDefault();
  9293. };
  9294. FilesInput.prototype.drop = function (eventDrop) {
  9295. eventDrop.stopPropagation();
  9296. eventDrop.preventDefault();
  9297. this.loadFiles(eventDrop);
  9298. };
  9299. FilesInput.prototype.loadFiles = function (event) {
  9300. if (this._startingProcessingFilesCallback)
  9301. this._startingProcessingFilesCallback();
  9302. // Handling data transfer via drag'n'drop
  9303. if (event && event.dataTransfer && event.dataTransfer.files) {
  9304. this._filesToLoad = event.dataTransfer.files;
  9305. }
  9306. // Handling files from input files
  9307. if (event && event.target && event.target.files) {
  9308. this._filesToLoad = event.target.files;
  9309. }
  9310. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9311. for (var i = 0; i < this._filesToLoad.length; i++) {
  9312. switch (this._filesToLoad[i].type) {
  9313. case "image/jpeg":
  9314. case "image/png":
  9315. case "image/bmp":
  9316. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9317. break;
  9318. case "image/targa":
  9319. case "image/vnd.ms-dds":
  9320. case "audio/wav":
  9321. case "audio/x-wav":
  9322. case "audio/mp3":
  9323. case "audio/mpeg":
  9324. case "audio/mpeg3":
  9325. case "audio/x-mpeg-3":
  9326. case "audio/ogg":
  9327. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9328. break;
  9329. default:
  9330. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9331. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9332. }
  9333. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9334. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9335. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9336. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9337. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9338. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9339. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9340. this._sceneFileToLoad = this._filesToLoad[i];
  9341. }
  9342. break;
  9343. }
  9344. }
  9345. this.reload();
  9346. }
  9347. };
  9348. FilesInput.prototype.reload = function () {
  9349. var _this = this;
  9350. var that = this;
  9351. // If a ".babylon" file has been provided
  9352. if (this._sceneFileToLoad) {
  9353. if (this._currentScene) {
  9354. if (BABYLON.Tools.errorsCount > 0) {
  9355. BABYLON.Tools.ClearLogCache();
  9356. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9357. }
  9358. this._engine.stopRenderLoop();
  9359. this._currentScene.dispose();
  9360. }
  9361. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9362. that._currentScene = newScene;
  9363. // Wait for textures and shaders to be ready
  9364. that._currentScene.executeWhenReady(function () {
  9365. // Attach camera to canvas inputs
  9366. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9367. that._currentScene.createDefaultCameraOrLight();
  9368. }
  9369. that._currentScene.activeCamera.attachControl(that._canvas);
  9370. if (that._sceneLoadedCallback) {
  9371. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9372. }
  9373. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9374. });
  9375. }, function (progress) {
  9376. if (_this._progressCallback) {
  9377. _this._progressCallback(progress);
  9378. }
  9379. });
  9380. }
  9381. else {
  9382. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9383. }
  9384. };
  9385. FilesInput.FilesTextures = new Array();
  9386. FilesInput.FilesToLoad = new Array();
  9387. return FilesInput;
  9388. }());
  9389. BABYLON.FilesInput = FilesInput;
  9390. })(BABYLON || (BABYLON = {}));
  9391. var BABYLON;
  9392. (function (BABYLON) {
  9393. var IntersectionInfo = (function () {
  9394. function IntersectionInfo(bu, bv, distance) {
  9395. this.bu = bu;
  9396. this.bv = bv;
  9397. this.distance = distance;
  9398. this.faceId = 0;
  9399. this.subMeshId = 0;
  9400. }
  9401. return IntersectionInfo;
  9402. }());
  9403. BABYLON.IntersectionInfo = IntersectionInfo;
  9404. var PickingInfo = (function () {
  9405. function PickingInfo() {
  9406. this.hit = false;
  9407. this.distance = 0;
  9408. this.pickedPoint = null;
  9409. this.pickedMesh = null;
  9410. this.bu = 0;
  9411. this.bv = 0;
  9412. this.faceId = -1;
  9413. this.subMeshId = 0;
  9414. this.pickedSprite = null;
  9415. }
  9416. // Methods
  9417. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9418. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9419. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9420. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9421. return null;
  9422. }
  9423. var indices = this.pickedMesh.getIndices();
  9424. var result;
  9425. if (useVerticesNormals) {
  9426. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9427. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9428. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9429. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9430. normal0 = normal0.scale(this.bu);
  9431. normal1 = normal1.scale(this.bv);
  9432. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9433. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9434. }
  9435. else {
  9436. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9437. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9438. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9439. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9440. var p1p2 = vertex1.subtract(vertex2);
  9441. var p3p2 = vertex3.subtract(vertex2);
  9442. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9443. }
  9444. if (useWorldCoordinates) {
  9445. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9446. }
  9447. return BABYLON.Vector3.Normalize(result);
  9448. };
  9449. PickingInfo.prototype.getTextureCoordinates = function () {
  9450. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9451. return null;
  9452. }
  9453. var indices = this.pickedMesh.getIndices();
  9454. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9455. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9456. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9457. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9458. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9459. uv1 = uv1.scale(this.bu);
  9460. uv2 = uv2.scale(this.bv);
  9461. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9462. };
  9463. return PickingInfo;
  9464. }());
  9465. BABYLON.PickingInfo = PickingInfo;
  9466. })(BABYLON || (BABYLON = {}));
  9467. var BABYLON;
  9468. (function (BABYLON) {
  9469. var BoundingSphere = (function () {
  9470. function BoundingSphere(minimum, maximum) {
  9471. this.minimum = minimum;
  9472. this.maximum = maximum;
  9473. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9474. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9475. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9476. this.radius = distance * 0.5;
  9477. this.centerWorld = BABYLON.Vector3.Zero();
  9478. this._update(BABYLON.Matrix.Identity());
  9479. }
  9480. // Methods
  9481. BoundingSphere.prototype._update = function (world) {
  9482. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9483. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9484. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9485. };
  9486. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9487. for (var i = 0; i < 6; i++) {
  9488. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9489. return false;
  9490. }
  9491. return true;
  9492. };
  9493. BoundingSphere.prototype.intersectsPoint = function (point) {
  9494. var x = this.centerWorld.x - point.x;
  9495. var y = this.centerWorld.y - point.y;
  9496. var z = this.centerWorld.z - point.z;
  9497. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9498. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9499. return false;
  9500. return true;
  9501. };
  9502. // Statics
  9503. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9504. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9505. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9506. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9507. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9508. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9509. return false;
  9510. return true;
  9511. };
  9512. return BoundingSphere;
  9513. }());
  9514. BABYLON.BoundingSphere = BoundingSphere;
  9515. })(BABYLON || (BABYLON = {}));
  9516. var BABYLON;
  9517. (function (BABYLON) {
  9518. var BoundingBox = (function () {
  9519. function BoundingBox(minimum, maximum) {
  9520. this.minimum = minimum;
  9521. this.maximum = maximum;
  9522. this.vectors = new Array();
  9523. this.vectorsWorld = new Array();
  9524. // Bounding vectors
  9525. this.vectors.push(this.minimum.clone());
  9526. this.vectors.push(this.maximum.clone());
  9527. this.vectors.push(this.minimum.clone());
  9528. this.vectors[2].x = this.maximum.x;
  9529. this.vectors.push(this.minimum.clone());
  9530. this.vectors[3].y = this.maximum.y;
  9531. this.vectors.push(this.minimum.clone());
  9532. this.vectors[4].z = this.maximum.z;
  9533. this.vectors.push(this.maximum.clone());
  9534. this.vectors[5].z = this.minimum.z;
  9535. this.vectors.push(this.maximum.clone());
  9536. this.vectors[6].x = this.minimum.x;
  9537. this.vectors.push(this.maximum.clone());
  9538. this.vectors[7].y = this.minimum.y;
  9539. // OBB
  9540. this.center = this.maximum.add(this.minimum).scale(0.5);
  9541. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9542. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9543. // World
  9544. for (var index = 0; index < this.vectors.length; index++) {
  9545. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9546. }
  9547. this.minimumWorld = BABYLON.Vector3.Zero();
  9548. this.maximumWorld = BABYLON.Vector3.Zero();
  9549. this._update(BABYLON.Matrix.Identity());
  9550. }
  9551. // Methods
  9552. BoundingBox.prototype.getWorldMatrix = function () {
  9553. return this._worldMatrix;
  9554. };
  9555. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9556. this._worldMatrix.copyFrom(matrix);
  9557. return this;
  9558. };
  9559. BoundingBox.prototype._update = function (world) {
  9560. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9561. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9562. for (var index = 0; index < this.vectors.length; index++) {
  9563. var v = this.vectorsWorld[index];
  9564. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9565. if (v.x < this.minimumWorld.x)
  9566. this.minimumWorld.x = v.x;
  9567. if (v.y < this.minimumWorld.y)
  9568. this.minimumWorld.y = v.y;
  9569. if (v.z < this.minimumWorld.z)
  9570. this.minimumWorld.z = v.z;
  9571. if (v.x > this.maximumWorld.x)
  9572. this.maximumWorld.x = v.x;
  9573. if (v.y > this.maximumWorld.y)
  9574. this.maximumWorld.y = v.y;
  9575. if (v.z > this.maximumWorld.z)
  9576. this.maximumWorld.z = v.z;
  9577. }
  9578. // OBB
  9579. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9580. this.center.scaleInPlace(0.5);
  9581. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9582. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9583. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9584. this._worldMatrix = world;
  9585. };
  9586. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9587. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9588. };
  9589. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9590. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9591. };
  9592. BoundingBox.prototype.intersectsPoint = function (point) {
  9593. var delta = -BABYLON.Epsilon;
  9594. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9595. return false;
  9596. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9597. return false;
  9598. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9599. return false;
  9600. return true;
  9601. };
  9602. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9603. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9604. };
  9605. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9606. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9607. return false;
  9608. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9609. return false;
  9610. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9611. return false;
  9612. return true;
  9613. };
  9614. // Statics
  9615. BoundingBox.Intersects = function (box0, box1) {
  9616. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9617. return false;
  9618. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9619. return false;
  9620. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9621. return false;
  9622. return true;
  9623. };
  9624. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9625. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9626. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9627. return (num <= (sphereRadius * sphereRadius));
  9628. };
  9629. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9630. for (var p = 0; p < 6; p++) {
  9631. for (var i = 0; i < 8; i++) {
  9632. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9633. return false;
  9634. }
  9635. }
  9636. }
  9637. return true;
  9638. };
  9639. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9640. for (var p = 0; p < 6; p++) {
  9641. var inCount = 8;
  9642. for (var i = 0; i < 8; i++) {
  9643. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9644. --inCount;
  9645. }
  9646. else {
  9647. break;
  9648. }
  9649. }
  9650. if (inCount === 0)
  9651. return false;
  9652. }
  9653. return true;
  9654. };
  9655. return BoundingBox;
  9656. }());
  9657. BABYLON.BoundingBox = BoundingBox;
  9658. })(BABYLON || (BABYLON = {}));
  9659. var BABYLON;
  9660. (function (BABYLON) {
  9661. var computeBoxExtents = function (axis, box) {
  9662. var p = BABYLON.Vector3.Dot(box.center, axis);
  9663. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9664. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9665. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9666. var r = r0 + r1 + r2;
  9667. return {
  9668. min: p - r,
  9669. max: p + r
  9670. };
  9671. };
  9672. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9673. var axisOverlap = function (axis, box0, box1) {
  9674. var result0 = computeBoxExtents(axis, box0);
  9675. var result1 = computeBoxExtents(axis, box1);
  9676. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9677. };
  9678. var BoundingInfo = (function () {
  9679. function BoundingInfo(minimum, maximum) {
  9680. this.minimum = minimum;
  9681. this.maximum = maximum;
  9682. this._isLocked = false;
  9683. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9684. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9685. }
  9686. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9687. get: function () {
  9688. return this._isLocked;
  9689. },
  9690. set: function (value) {
  9691. this._isLocked = value;
  9692. },
  9693. enumerable: true,
  9694. configurable: true
  9695. });
  9696. // Methods
  9697. BoundingInfo.prototype.update = function (world) {
  9698. if (this._isLocked) {
  9699. return;
  9700. }
  9701. this.boundingBox._update(world);
  9702. this.boundingSphere._update(world);
  9703. };
  9704. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9705. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9706. return false;
  9707. return this.boundingBox.isInFrustum(frustumPlanes);
  9708. };
  9709. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9710. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9711. };
  9712. BoundingInfo.prototype._checkCollision = function (collider) {
  9713. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9714. };
  9715. BoundingInfo.prototype.intersectsPoint = function (point) {
  9716. if (!this.boundingSphere.centerWorld) {
  9717. return false;
  9718. }
  9719. if (!this.boundingSphere.intersectsPoint(point)) {
  9720. return false;
  9721. }
  9722. if (!this.boundingBox.intersectsPoint(point)) {
  9723. return false;
  9724. }
  9725. return true;
  9726. };
  9727. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9728. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9729. return false;
  9730. }
  9731. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9732. return false;
  9733. }
  9734. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9735. return false;
  9736. }
  9737. if (!precise) {
  9738. return true;
  9739. }
  9740. var box0 = this.boundingBox;
  9741. var box1 = boundingInfo.boundingBox;
  9742. if (!axisOverlap(box0.directions[0], box0, box1))
  9743. return false;
  9744. if (!axisOverlap(box0.directions[1], box0, box1))
  9745. return false;
  9746. if (!axisOverlap(box0.directions[2], box0, box1))
  9747. return false;
  9748. if (!axisOverlap(box1.directions[0], box0, box1))
  9749. return false;
  9750. if (!axisOverlap(box1.directions[1], box0, box1))
  9751. return false;
  9752. if (!axisOverlap(box1.directions[2], box0, box1))
  9753. return false;
  9754. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9755. return false;
  9756. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9757. return false;
  9758. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9759. return false;
  9760. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9761. return false;
  9762. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9763. return false;
  9764. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9765. return false;
  9766. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9767. return false;
  9768. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9769. return false;
  9770. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9771. return false;
  9772. return true;
  9773. };
  9774. return BoundingInfo;
  9775. }());
  9776. BABYLON.BoundingInfo = BoundingInfo;
  9777. })(BABYLON || (BABYLON = {}));
  9778. var BABYLON;
  9779. (function (BABYLON) {
  9780. var Ray = (function () {
  9781. function Ray(origin, direction, length) {
  9782. if (length === void 0) { length = Number.MAX_VALUE; }
  9783. this.origin = origin;
  9784. this.direction = direction;
  9785. this.length = length;
  9786. }
  9787. // Methods
  9788. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  9789. var d = 0.0;
  9790. var maxValue = Number.MAX_VALUE;
  9791. var inv;
  9792. var min;
  9793. var max;
  9794. var temp;
  9795. if (Math.abs(this.direction.x) < 0.0000001) {
  9796. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  9797. return false;
  9798. }
  9799. }
  9800. else {
  9801. inv = 1.0 / this.direction.x;
  9802. min = (minimum.x - this.origin.x) * inv;
  9803. max = (maximum.x - this.origin.x) * inv;
  9804. if (max === -Infinity) {
  9805. max = Infinity;
  9806. }
  9807. if (min > max) {
  9808. temp = min;
  9809. min = max;
  9810. max = temp;
  9811. }
  9812. d = Math.max(min, d);
  9813. maxValue = Math.min(max, maxValue);
  9814. if (d > maxValue) {
  9815. return false;
  9816. }
  9817. }
  9818. if (Math.abs(this.direction.y) < 0.0000001) {
  9819. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  9820. return false;
  9821. }
  9822. }
  9823. else {
  9824. inv = 1.0 / this.direction.y;
  9825. min = (minimum.y - this.origin.y) * inv;
  9826. max = (maximum.y - this.origin.y) * inv;
  9827. if (max === -Infinity) {
  9828. max = Infinity;
  9829. }
  9830. if (min > max) {
  9831. temp = min;
  9832. min = max;
  9833. max = temp;
  9834. }
  9835. d = Math.max(min, d);
  9836. maxValue = Math.min(max, maxValue);
  9837. if (d > maxValue) {
  9838. return false;
  9839. }
  9840. }
  9841. if (Math.abs(this.direction.z) < 0.0000001) {
  9842. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  9843. return false;
  9844. }
  9845. }
  9846. else {
  9847. inv = 1.0 / this.direction.z;
  9848. min = (minimum.z - this.origin.z) * inv;
  9849. max = (maximum.z - this.origin.z) * inv;
  9850. if (max === -Infinity) {
  9851. max = Infinity;
  9852. }
  9853. if (min > max) {
  9854. temp = min;
  9855. min = max;
  9856. max = temp;
  9857. }
  9858. d = Math.max(min, d);
  9859. maxValue = Math.min(max, maxValue);
  9860. if (d > maxValue) {
  9861. return false;
  9862. }
  9863. }
  9864. return true;
  9865. };
  9866. Ray.prototype.intersectsBox = function (box) {
  9867. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  9868. };
  9869. Ray.prototype.intersectsSphere = function (sphere) {
  9870. var x = sphere.center.x - this.origin.x;
  9871. var y = sphere.center.y - this.origin.y;
  9872. var z = sphere.center.z - this.origin.z;
  9873. var pyth = (x * x) + (y * y) + (z * z);
  9874. var rr = sphere.radius * sphere.radius;
  9875. if (pyth <= rr) {
  9876. return true;
  9877. }
  9878. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  9879. if (dot < 0.0) {
  9880. return false;
  9881. }
  9882. var temp = pyth - (dot * dot);
  9883. return temp <= rr;
  9884. };
  9885. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  9886. if (!this._edge1) {
  9887. this._edge1 = BABYLON.Vector3.Zero();
  9888. this._edge2 = BABYLON.Vector3.Zero();
  9889. this._pvec = BABYLON.Vector3.Zero();
  9890. this._tvec = BABYLON.Vector3.Zero();
  9891. this._qvec = BABYLON.Vector3.Zero();
  9892. }
  9893. vertex1.subtractToRef(vertex0, this._edge1);
  9894. vertex2.subtractToRef(vertex0, this._edge2);
  9895. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  9896. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  9897. if (det === 0) {
  9898. return null;
  9899. }
  9900. var invdet = 1 / det;
  9901. this.origin.subtractToRef(vertex0, this._tvec);
  9902. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  9903. if (bu < 0 || bu > 1.0) {
  9904. return null;
  9905. }
  9906. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  9907. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  9908. if (bv < 0 || bu + bv > 1.0) {
  9909. return null;
  9910. }
  9911. //check if the distance is longer than the predefined length.
  9912. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  9913. if (distance > this.length) {
  9914. return null;
  9915. }
  9916. return new BABYLON.IntersectionInfo(bu, bv, distance);
  9917. };
  9918. Ray.prototype.intersectsPlane = function (plane) {
  9919. var distance;
  9920. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  9921. if (Math.abs(result1) < 9.99999997475243E-07) {
  9922. return null;
  9923. }
  9924. else {
  9925. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  9926. distance = (-plane.d - result2) / result1;
  9927. if (distance < 0.0) {
  9928. if (distance < -9.99999997475243E-07) {
  9929. return null;
  9930. }
  9931. else {
  9932. return 0;
  9933. }
  9934. }
  9935. return distance;
  9936. }
  9937. };
  9938. /**
  9939. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  9940. * @param sega the first point of the segment to test the intersection against
  9941. * @param segb the second point of the segment to test the intersection against
  9942. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  9943. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  9944. */
  9945. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  9946. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  9947. var u = segb.subtract(sega);
  9948. var v = rsegb.subtract(this.origin);
  9949. var w = sega.subtract(this.origin);
  9950. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  9951. var b = BABYLON.Vector3.Dot(u, v);
  9952. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  9953. var d = BABYLON.Vector3.Dot(u, w);
  9954. var e = BABYLON.Vector3.Dot(v, w);
  9955. var D = a * c - b * b; // always >= 0
  9956. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  9957. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  9958. // compute the line parameters of the two closest points
  9959. if (D < Ray.smallnum) {
  9960. sN = 0.0; // force using point P0 on segment S1
  9961. sD = 1.0; // to prevent possible division by 0.0 later
  9962. tN = e;
  9963. tD = c;
  9964. }
  9965. else {
  9966. sN = (b * e - c * d);
  9967. tN = (a * e - b * d);
  9968. if (sN < 0.0) {
  9969. sN = 0.0;
  9970. tN = e;
  9971. tD = c;
  9972. }
  9973. else if (sN > sD) {
  9974. sN = sD;
  9975. tN = e + b;
  9976. tD = c;
  9977. }
  9978. }
  9979. if (tN < 0.0) {
  9980. tN = 0.0;
  9981. // recompute sc for this edge
  9982. if (-d < 0.0) {
  9983. sN = 0.0;
  9984. }
  9985. else if (-d > a)
  9986. sN = sD;
  9987. else {
  9988. sN = -d;
  9989. sD = a;
  9990. }
  9991. }
  9992. else if (tN > tD) {
  9993. tN = tD;
  9994. // recompute sc for this edge
  9995. if ((-d + b) < 0.0) {
  9996. sN = 0;
  9997. }
  9998. else if ((-d + b) > a) {
  9999. sN = sD;
  10000. }
  10001. else {
  10002. sN = (-d + b);
  10003. sD = a;
  10004. }
  10005. }
  10006. // finally do the division to get sc and tc
  10007. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10008. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10009. // get the difference of the two closest points
  10010. var qtc = v.multiplyByFloats(tc, tc, tc);
  10011. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10012. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10013. if (isIntersected) {
  10014. return qtc.length();
  10015. }
  10016. return -1;
  10017. };
  10018. // Statics
  10019. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10020. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10021. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10022. var direction = end.subtract(start);
  10023. direction.normalize();
  10024. return new Ray(start, direction);
  10025. };
  10026. /**
  10027. * 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
  10028. * transformed to the given world matrix.
  10029. * @param origin The origin point
  10030. * @param end The end point
  10031. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10032. */
  10033. Ray.CreateNewFromTo = function (origin, end, world) {
  10034. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10035. var direction = end.subtract(origin);
  10036. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10037. direction.normalize();
  10038. return Ray.Transform(new Ray(origin, direction, length), world);
  10039. };
  10040. Ray.Transform = function (ray, matrix) {
  10041. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10042. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10043. newDirection.normalize();
  10044. return new Ray(newOrigin, newDirection, ray.length);
  10045. };
  10046. Ray.smallnum = 0.00000001;
  10047. Ray.rayl = 10e8;
  10048. return Ray;
  10049. }());
  10050. BABYLON.Ray = Ray;
  10051. })(BABYLON || (BABYLON = {}));
  10052. var BABYLON;
  10053. (function (BABYLON) {
  10054. var AbstractMesh = (function (_super) {
  10055. __extends(AbstractMesh, _super);
  10056. // Constructor
  10057. function AbstractMesh(name, scene) {
  10058. var _this = this;
  10059. _super.call(this, name, scene);
  10060. // Events
  10061. /**
  10062. * An event triggered when the mesh is disposed.
  10063. * @type {BABYLON.Observable}
  10064. */
  10065. this.onDisposeObservable = new BABYLON.Observable();
  10066. /**
  10067. * An event triggered when this mesh collides with another one
  10068. * @type {BABYLON.Observable}
  10069. */
  10070. this.onCollideObservable = new BABYLON.Observable();
  10071. /**
  10072. * An event triggered when the collision's position changes
  10073. * @type {BABYLON.Observable}
  10074. */
  10075. this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10076. /**
  10077. * An event triggered after the world matrix is updated
  10078. * @type {BABYLON.Observable}
  10079. */
  10080. this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10081. // Properties
  10082. this.definedFacingForward = true; // orientation for POV movement & rotation
  10083. this.position = new BABYLON.Vector3(0, 0, 0);
  10084. this._rotation = new BABYLON.Vector3(0, 0, 0);
  10085. this._scaling = new BABYLON.Vector3(1, 1, 1);
  10086. this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10087. this.visibility = 1.0;
  10088. this.alphaIndex = Number.MAX_VALUE;
  10089. this.infiniteDistance = false;
  10090. this.isVisible = true;
  10091. this.isPickable = true;
  10092. this.showBoundingBox = false;
  10093. this.showSubMeshesBoundingBox = false;
  10094. this.isBlocker = false;
  10095. this.renderingGroupId = 0;
  10096. this.receiveShadows = false;
  10097. this.renderOutline = false;
  10098. this.outlineColor = BABYLON.Color3.Red();
  10099. this.outlineWidth = 0.02;
  10100. this.renderOverlay = false;
  10101. this.overlayColor = BABYLON.Color3.Red();
  10102. this.overlayAlpha = 0.5;
  10103. this.hasVertexAlpha = false;
  10104. this.useVertexColors = true;
  10105. this.applyFog = true;
  10106. this.computeBonesUsingShaders = true;
  10107. this.scalingDeterminant = 1;
  10108. this.numBoneInfluencers = 4;
  10109. this.useOctreeForRenderingSelection = true;
  10110. this.useOctreeForPicking = true;
  10111. this.useOctreeForCollisions = true;
  10112. this.layerMask = 0x0FFFFFFF;
  10113. this.alwaysSelectAsActiveMesh = false;
  10114. // Collisions
  10115. this._checkCollisions = false;
  10116. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10117. this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10118. this._collider = new BABYLON.Collider();
  10119. this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10120. this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10121. this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10122. // Edges
  10123. this.edgesWidth = 1;
  10124. this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10125. // Cache
  10126. this._localWorld = BABYLON.Matrix.Zero();
  10127. this._worldMatrix = BABYLON.Matrix.Zero();
  10128. this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10129. this._absolutePosition = BABYLON.Vector3.Zero();
  10130. this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10131. this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10132. this._isDirty = false;
  10133. this._pivotMatrix = BABYLON.Matrix.Identity();
  10134. this._isDisposed = false;
  10135. this._renderId = 0;
  10136. this._intersectionsInProgress = new Array();
  10137. this._isWorldMatrixFrozen = false;
  10138. this._unIndexed = false;
  10139. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10140. if (collidedMesh === void 0) { collidedMesh = null; }
  10141. //TODO move this to the collision coordinator!
  10142. if (_this.getScene().workerCollisions)
  10143. newPosition.multiplyInPlace(_this._collider.radius);
  10144. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10145. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10146. _this.position.addInPlace(_this._diffPositionForCollisions);
  10147. }
  10148. if (collidedMesh) {
  10149. _this.onCollideObservable.notifyObservers(collidedMesh);
  10150. }
  10151. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10152. };
  10153. scene.addMesh(this);
  10154. }
  10155. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10156. get: function () {
  10157. return AbstractMesh._BILLBOARDMODE_NONE;
  10158. },
  10159. enumerable: true,
  10160. configurable: true
  10161. });
  10162. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10163. get: function () {
  10164. return AbstractMesh._BILLBOARDMODE_X;
  10165. },
  10166. enumerable: true,
  10167. configurable: true
  10168. });
  10169. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10170. get: function () {
  10171. return AbstractMesh._BILLBOARDMODE_Y;
  10172. },
  10173. enumerable: true,
  10174. configurable: true
  10175. });
  10176. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10177. get: function () {
  10178. return AbstractMesh._BILLBOARDMODE_Z;
  10179. },
  10180. enumerable: true,
  10181. configurable: true
  10182. });
  10183. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10184. get: function () {
  10185. return AbstractMesh._BILLBOARDMODE_ALL;
  10186. },
  10187. enumerable: true,
  10188. configurable: true
  10189. });
  10190. Object.defineProperty(AbstractMesh.prototype, "onDispose", {
  10191. set: function (callback) {
  10192. if (this._onDisposeObserver) {
  10193. this.onDisposeObservable.remove(this._onDisposeObserver);
  10194. }
  10195. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  10196. },
  10197. enumerable: true,
  10198. configurable: true
  10199. });
  10200. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10201. set: function (callback) {
  10202. if (this._onCollideObserver) {
  10203. this.onCollideObservable.remove(this._onCollideObserver);
  10204. }
  10205. this._onCollideObserver = this.onCollideObservable.add(callback);
  10206. },
  10207. enumerable: true,
  10208. configurable: true
  10209. });
  10210. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10211. set: function (callback) {
  10212. if (this._onCollisionPositionChangeObserver) {
  10213. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10214. }
  10215. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10216. },
  10217. enumerable: true,
  10218. configurable: true
  10219. });
  10220. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10221. get: function () {
  10222. return this._skeleton;
  10223. },
  10224. set: function (value) {
  10225. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10226. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10227. }
  10228. if (value && value.needInitialSkinMatrix) {
  10229. value._registerMeshWithPoseMatrix(this);
  10230. }
  10231. this._skeleton = value;
  10232. if (!this._skeleton) {
  10233. this._bonesTransformMatrices = null;
  10234. }
  10235. },
  10236. enumerable: true,
  10237. configurable: true
  10238. });
  10239. /**
  10240. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10241. */
  10242. AbstractMesh.prototype.toString = function (fullDetails) {
  10243. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10244. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10245. if (this._skeleton) {
  10246. ret += ", skeleton: " + this._skeleton.name;
  10247. }
  10248. if (fullDetails) {
  10249. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10250. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10251. }
  10252. return ret;
  10253. };
  10254. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10255. /**
  10256. * Getting the rotation object.
  10257. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10258. */
  10259. get: function () {
  10260. return this._rotation;
  10261. },
  10262. set: function (newRotation) {
  10263. this._rotation = newRotation;
  10264. },
  10265. enumerable: true,
  10266. configurable: true
  10267. });
  10268. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10269. get: function () {
  10270. return this._scaling;
  10271. },
  10272. set: function (newScaling) {
  10273. this._scaling = newScaling;
  10274. if (this.physicsImpostor) {
  10275. this.physicsImpostor.forceUpdate();
  10276. }
  10277. },
  10278. enumerable: true,
  10279. configurable: true
  10280. });
  10281. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10282. get: function () {
  10283. return this._rotationQuaternion;
  10284. },
  10285. set: function (quaternion) {
  10286. this._rotationQuaternion = quaternion;
  10287. //reset the rotation vector.
  10288. if (quaternion && this.rotation.length()) {
  10289. this.rotation.copyFromFloats(0, 0, 0);
  10290. }
  10291. },
  10292. enumerable: true,
  10293. configurable: true
  10294. });
  10295. // Methods
  10296. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10297. this._poseMatrix.copyFrom(matrix);
  10298. };
  10299. AbstractMesh.prototype.getPoseMatrix = function () {
  10300. return this._poseMatrix;
  10301. };
  10302. AbstractMesh.prototype.disableEdgesRendering = function () {
  10303. if (this._edgesRenderer !== undefined) {
  10304. this._edgesRenderer.dispose();
  10305. this._edgesRenderer = undefined;
  10306. }
  10307. };
  10308. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10309. if (epsilon === void 0) { epsilon = 0.95; }
  10310. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10311. this.disableEdgesRendering();
  10312. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10313. };
  10314. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10315. get: function () {
  10316. return false;
  10317. },
  10318. enumerable: true,
  10319. configurable: true
  10320. });
  10321. AbstractMesh.prototype.getLOD = function (camera) {
  10322. return this;
  10323. };
  10324. AbstractMesh.prototype.getTotalVertices = function () {
  10325. return 0;
  10326. };
  10327. AbstractMesh.prototype.getIndices = function () {
  10328. return null;
  10329. };
  10330. AbstractMesh.prototype.getVerticesData = function (kind) {
  10331. return null;
  10332. };
  10333. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10334. return false;
  10335. };
  10336. AbstractMesh.prototype.getBoundingInfo = function () {
  10337. if (this._masterMesh) {
  10338. return this._masterMesh.getBoundingInfo();
  10339. }
  10340. if (!this._boundingInfo) {
  10341. this._updateBoundingInfo();
  10342. }
  10343. return this._boundingInfo;
  10344. };
  10345. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10346. this._boundingInfo = boundingInfo;
  10347. };
  10348. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10349. get: function () {
  10350. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10351. },
  10352. enumerable: true,
  10353. configurable: true
  10354. });
  10355. AbstractMesh.prototype._preActivate = function () {
  10356. };
  10357. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10358. };
  10359. AbstractMesh.prototype._activate = function (renderId) {
  10360. this._renderId = renderId;
  10361. };
  10362. AbstractMesh.prototype.getWorldMatrix = function () {
  10363. if (this._masterMesh) {
  10364. return this._masterMesh.getWorldMatrix();
  10365. }
  10366. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10367. this.computeWorldMatrix();
  10368. }
  10369. return this._worldMatrix;
  10370. };
  10371. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10372. get: function () {
  10373. return this._worldMatrix;
  10374. },
  10375. enumerable: true,
  10376. configurable: true
  10377. });
  10378. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10379. get: function () {
  10380. return this._absolutePosition;
  10381. },
  10382. enumerable: true,
  10383. configurable: true
  10384. });
  10385. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10386. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10387. this.computeWorldMatrix(true);
  10388. this._isWorldMatrixFrozen = true;
  10389. };
  10390. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10391. this._isWorldMatrixFrozen = false;
  10392. this.computeWorldMatrix(true);
  10393. };
  10394. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10395. get: function () {
  10396. return this._isWorldMatrixFrozen;
  10397. },
  10398. enumerable: true,
  10399. configurable: true
  10400. });
  10401. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10402. axis.normalize();
  10403. if (!this.rotationQuaternion) {
  10404. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10405. this.rotation = BABYLON.Vector3.Zero();
  10406. }
  10407. var rotationQuaternion;
  10408. if (!space || space === BABYLON.Space.LOCAL) {
  10409. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10410. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10411. }
  10412. else {
  10413. if (this.parent) {
  10414. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10415. invertParentWorldMatrix.invert();
  10416. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10417. }
  10418. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10419. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10420. }
  10421. };
  10422. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10423. var displacementVector = axis.scale(distance);
  10424. if (!space || space === BABYLON.Space.LOCAL) {
  10425. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10426. this.setPositionWithLocalVector(tempV3);
  10427. }
  10428. else {
  10429. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10430. }
  10431. };
  10432. AbstractMesh.prototype.getAbsolutePosition = function () {
  10433. this.computeWorldMatrix();
  10434. return this._absolutePosition;
  10435. };
  10436. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10437. if (!absolutePosition) {
  10438. return;
  10439. }
  10440. var absolutePositionX;
  10441. var absolutePositionY;
  10442. var absolutePositionZ;
  10443. if (absolutePosition.x === undefined) {
  10444. if (arguments.length < 3) {
  10445. return;
  10446. }
  10447. absolutePositionX = arguments[0];
  10448. absolutePositionY = arguments[1];
  10449. absolutePositionZ = arguments[2];
  10450. }
  10451. else {
  10452. absolutePositionX = absolutePosition.x;
  10453. absolutePositionY = absolutePosition.y;
  10454. absolutePositionZ = absolutePosition.z;
  10455. }
  10456. if (this.parent) {
  10457. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10458. invertParentWorldMatrix.invert();
  10459. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10460. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10461. }
  10462. else {
  10463. this.position.x = absolutePositionX;
  10464. this.position.y = absolutePositionY;
  10465. this.position.z = absolutePositionZ;
  10466. }
  10467. };
  10468. // ================================== Point of View Movement =================================
  10469. /**
  10470. * Perform relative position change from the point of view of behind the front of the mesh.
  10471. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10472. * Supports definition of mesh facing forward or backward.
  10473. * @param {number} amountRight
  10474. * @param {number} amountUp
  10475. * @param {number} amountForward
  10476. */
  10477. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10478. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10479. };
  10480. /**
  10481. * Calculate relative position change from the point of view of behind the front of the mesh.
  10482. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10483. * Supports definition of mesh facing forward or backward.
  10484. * @param {number} amountRight
  10485. * @param {number} amountUp
  10486. * @param {number} amountForward
  10487. */
  10488. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10489. var rotMatrix = new BABYLON.Matrix();
  10490. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10491. rotQuaternion.toRotationMatrix(rotMatrix);
  10492. var translationDelta = BABYLON.Vector3.Zero();
  10493. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10494. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10495. return translationDelta;
  10496. };
  10497. // ================================== Point of View Rotation =================================
  10498. /**
  10499. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10500. * Supports definition of mesh facing forward or backward.
  10501. * @param {number} flipBack
  10502. * @param {number} twirlClockwise
  10503. * @param {number} tiltRight
  10504. */
  10505. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10506. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10507. };
  10508. /**
  10509. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10510. * Supports definition of mesh facing forward or backward.
  10511. * @param {number} flipBack
  10512. * @param {number} twirlClockwise
  10513. * @param {number} tiltRight
  10514. */
  10515. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10516. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10517. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10518. };
  10519. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10520. this._pivotMatrix = matrix;
  10521. this._cache.pivotMatrixUpdated = true;
  10522. };
  10523. AbstractMesh.prototype.getPivotMatrix = function () {
  10524. return this._pivotMatrix;
  10525. };
  10526. AbstractMesh.prototype._isSynchronized = function () {
  10527. if (this._isDirty) {
  10528. return false;
  10529. }
  10530. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10531. return false;
  10532. if (this._cache.pivotMatrixUpdated) {
  10533. return false;
  10534. }
  10535. if (this.infiniteDistance) {
  10536. return false;
  10537. }
  10538. if (!this._cache.position.equals(this.position))
  10539. return false;
  10540. if (this.rotationQuaternion) {
  10541. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10542. return false;
  10543. }
  10544. if (!this._cache.rotation.equals(this.rotation))
  10545. return false;
  10546. if (!this._cache.scaling.equals(this.scaling))
  10547. return false;
  10548. return true;
  10549. };
  10550. AbstractMesh.prototype._initCache = function () {
  10551. _super.prototype._initCache.call(this);
  10552. this._cache.localMatrixUpdated = false;
  10553. this._cache.position = BABYLON.Vector3.Zero();
  10554. this._cache.scaling = BABYLON.Vector3.Zero();
  10555. this._cache.rotation = BABYLON.Vector3.Zero();
  10556. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10557. this._cache.billboardMode = -1;
  10558. };
  10559. AbstractMesh.prototype.markAsDirty = function (property) {
  10560. if (property === "rotation") {
  10561. this.rotationQuaternion = null;
  10562. }
  10563. this._currentRenderId = Number.MAX_VALUE;
  10564. this._isDirty = true;
  10565. };
  10566. AbstractMesh.prototype._updateBoundingInfo = function () {
  10567. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10568. this._boundingInfo.update(this.worldMatrixFromCache);
  10569. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10570. };
  10571. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10572. if (!this.subMeshes) {
  10573. return;
  10574. }
  10575. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10576. var subMesh = this.subMeshes[subIndex];
  10577. if (!subMesh.IsGlobal) {
  10578. subMesh.updateBoundingInfo(matrix);
  10579. }
  10580. }
  10581. };
  10582. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10583. if (this._isWorldMatrixFrozen) {
  10584. return this._worldMatrix;
  10585. }
  10586. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10587. this._currentRenderId = this.getScene().getRenderId();
  10588. return this._worldMatrix;
  10589. }
  10590. this._cache.position.copyFrom(this.position);
  10591. this._cache.scaling.copyFrom(this.scaling);
  10592. this._cache.pivotMatrixUpdated = false;
  10593. this._cache.billboardMode = this.billboardMode;
  10594. this._currentRenderId = this.getScene().getRenderId();
  10595. this._isDirty = false;
  10596. // Scaling
  10597. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10598. // Rotation
  10599. //rotate, if quaternion is set and rotation was used
  10600. if (this.rotationQuaternion) {
  10601. var len = this.rotation.length();
  10602. if (len) {
  10603. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10604. this.rotation.copyFromFloats(0, 0, 0);
  10605. }
  10606. }
  10607. if (this.rotationQuaternion) {
  10608. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10609. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10610. }
  10611. else {
  10612. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10613. this._cache.rotation.copyFrom(this.rotation);
  10614. }
  10615. // Translation
  10616. if (this.infiniteDistance && !this.parent) {
  10617. var camera = this.getScene().activeCamera;
  10618. if (camera) {
  10619. var cameraWorldMatrix = camera.getWorldMatrix();
  10620. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10621. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10622. }
  10623. }
  10624. else {
  10625. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10626. }
  10627. // Composing transformations
  10628. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10629. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10630. // Billboarding
  10631. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10632. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10633. var localPosition = BABYLON.Tmp.Vector3[0];
  10634. if (this.parent && this.parent.getWorldMatrix) {
  10635. this._markSyncedWithParent();
  10636. var parentMatrix;
  10637. if (this._meshToBoneReferal) {
  10638. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10639. parentMatrix = BABYLON.Tmp.Matrix[6];
  10640. }
  10641. else {
  10642. parentMatrix = this.parent.getWorldMatrix();
  10643. }
  10644. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10645. localPosition = BABYLON.Tmp.Vector3[1];
  10646. }
  10647. var zero = this.getScene().activeCamera.globalPosition.clone();
  10648. if (this.parent && this.parent.position) {
  10649. localPosition.addInPlace(this.parent.position);
  10650. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10651. }
  10652. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10653. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10654. zero.x = localPosition.x + BABYLON.Epsilon;
  10655. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10656. zero.y = localPosition.y + BABYLON.Epsilon;
  10657. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10658. zero.z = localPosition.z + BABYLON.Epsilon;
  10659. }
  10660. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10661. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10662. BABYLON.Tmp.Matrix[3].invert();
  10663. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10664. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10665. }
  10666. // Local world
  10667. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10668. // Parent
  10669. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10670. this._markSyncedWithParent();
  10671. if (this._meshToBoneReferal) {
  10672. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10673. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10674. }
  10675. else {
  10676. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10677. }
  10678. }
  10679. else {
  10680. this._worldMatrix.copyFrom(this._localWorld);
  10681. }
  10682. // Bounding info
  10683. this._updateBoundingInfo();
  10684. // Absolute position
  10685. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10686. // Callbacks
  10687. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10688. if (!this._poseMatrix) {
  10689. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10690. }
  10691. return this._worldMatrix;
  10692. };
  10693. /**
  10694. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10695. * @param func: callback function to add
  10696. */
  10697. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10698. this.onAfterWorldMatrixUpdateObservable.add(func);
  10699. };
  10700. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10701. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10702. };
  10703. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10704. this.computeWorldMatrix();
  10705. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10706. };
  10707. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10708. this.computeWorldMatrix();
  10709. var invLocalWorldMatrix = this._localWorld.clone();
  10710. invLocalWorldMatrix.invert();
  10711. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10712. };
  10713. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10714. this.computeWorldMatrix(true);
  10715. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10716. };
  10717. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10718. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10719. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10720. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10721. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10722. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10723. /// <returns>Mesh oriented towards targetMesh</returns>
  10724. if (yawCor === void 0) { yawCor = 0; }
  10725. if (pitchCor === void 0) { pitchCor = 0; }
  10726. if (rollCor === void 0) { rollCor = 0; }
  10727. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10728. var dv = AbstractMesh._lookAtVectorCache;
  10729. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10730. targetPoint.subtractToRef(pos, dv);
  10731. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10732. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10733. var pitch = Math.atan2(dv.y, len);
  10734. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10735. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10736. };
  10737. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10738. this._meshToBoneReferal = affectedMesh;
  10739. this.parent = bone;
  10740. if (bone.getWorldMatrix().determinant() < 0) {
  10741. this.scalingDeterminant *= -1;
  10742. }
  10743. };
  10744. AbstractMesh.prototype.detachFromBone = function () {
  10745. if (this.parent.getWorldMatrix().determinant() < 0) {
  10746. this.scalingDeterminant *= -1;
  10747. }
  10748. this._meshToBoneReferal = null;
  10749. this.parent = null;
  10750. };
  10751. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  10752. return this._boundingInfo.isInFrustum(frustumPlanes);
  10753. };
  10754. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10755. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  10756. ;
  10757. };
  10758. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  10759. if (!this._boundingInfo || !mesh._boundingInfo) {
  10760. return false;
  10761. }
  10762. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  10763. };
  10764. AbstractMesh.prototype.intersectsPoint = function (point) {
  10765. if (!this._boundingInfo) {
  10766. return false;
  10767. }
  10768. return this._boundingInfo.intersectsPoint(point);
  10769. };
  10770. // Physics
  10771. /**
  10772. * @Deprecated. Use new PhysicsImpostor instead.
  10773. * */
  10774. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  10775. //legacy support
  10776. if (impostor.impostor) {
  10777. options = impostor;
  10778. impostor = impostor.impostor;
  10779. }
  10780. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  10781. return this.physicsImpostor.physicsBody;
  10782. };
  10783. AbstractMesh.prototype.getPhysicsImpostor = function () {
  10784. return this.physicsImpostor;
  10785. };
  10786. /**
  10787. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  10788. */
  10789. AbstractMesh.prototype.getPhysicsMass = function () {
  10790. return this.physicsImpostor.getParam("mass");
  10791. };
  10792. /**
  10793. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  10794. */
  10795. AbstractMesh.prototype.getPhysicsFriction = function () {
  10796. return this.physicsImpostor.getParam("friction");
  10797. };
  10798. /**
  10799. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  10800. */
  10801. AbstractMesh.prototype.getPhysicsRestitution = function () {
  10802. return this.physicsImpostor.getParam("restitution");
  10803. };
  10804. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  10805. if (!camera) {
  10806. camera = this.getScene().activeCamera;
  10807. }
  10808. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  10809. };
  10810. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  10811. if (!camera) {
  10812. camera = this.getScene().activeCamera;
  10813. }
  10814. return this.absolutePosition.subtract(camera.position).length();
  10815. };
  10816. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  10817. if (!this.physicsImpostor) {
  10818. return;
  10819. }
  10820. this.physicsImpostor.applyImpulse(force, contactPoint);
  10821. };
  10822. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  10823. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  10824. return;
  10825. }
  10826. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  10827. mainPivot: pivot1,
  10828. connectedPivot: pivot2,
  10829. nativeParams: options
  10830. });
  10831. };
  10832. /**
  10833. * @Deprecated
  10834. */
  10835. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  10836. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  10837. this.updatePhysicsBody();
  10838. };
  10839. /**
  10840. * @Deprecated
  10841. * Calling this function is not needed anymore.
  10842. * The physics engine takes care of transofmration automatically.
  10843. */
  10844. AbstractMesh.prototype.updatePhysicsBody = function () {
  10845. //Unneeded
  10846. };
  10847. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  10848. // Collisions
  10849. get: function () {
  10850. return this._checkCollisions;
  10851. },
  10852. set: function (collisionEnabled) {
  10853. this._checkCollisions = collisionEnabled;
  10854. if (this.getScene().workerCollisions) {
  10855. this.getScene().collisionCoordinator.onMeshUpdated(this);
  10856. }
  10857. },
  10858. enumerable: true,
  10859. configurable: true
  10860. });
  10861. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  10862. var globalPosition = this.getAbsolutePosition();
  10863. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  10864. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  10865. this._collider.radius = this.ellipsoid;
  10866. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  10867. };
  10868. // Submeshes octree
  10869. /**
  10870. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  10871. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  10872. */
  10873. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  10874. if (maxCapacity === void 0) { maxCapacity = 64; }
  10875. if (maxDepth === void 0) { maxDepth = 2; }
  10876. if (!this._submeshesOctree) {
  10877. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  10878. }
  10879. this.computeWorldMatrix(true);
  10880. // Update octree
  10881. var bbox = this.getBoundingInfo().boundingBox;
  10882. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  10883. return this._submeshesOctree;
  10884. };
  10885. // Collisions
  10886. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  10887. this._generatePointsArray();
  10888. // Transformation
  10889. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  10890. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  10891. subMesh._lastColliderWorldVertices = [];
  10892. subMesh._trianglePlanes = [];
  10893. var start = subMesh.verticesStart;
  10894. var end = (subMesh.verticesStart + subMesh.verticesCount);
  10895. for (var i = start; i < end; i++) {
  10896. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  10897. }
  10898. }
  10899. // Collide
  10900. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  10901. if (collider.collisionFound) {
  10902. collider.collidedMesh = this;
  10903. }
  10904. };
  10905. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  10906. var subMeshes;
  10907. var len;
  10908. // Octrees
  10909. if (this._submeshesOctree && this.useOctreeForCollisions) {
  10910. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  10911. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  10912. len = intersections.length;
  10913. subMeshes = intersections.data;
  10914. }
  10915. else {
  10916. subMeshes = this.subMeshes;
  10917. len = subMeshes.length;
  10918. }
  10919. for (var index = 0; index < len; index++) {
  10920. var subMesh = subMeshes[index];
  10921. // Bounding test
  10922. if (len > 1 && !subMesh._checkCollision(collider))
  10923. continue;
  10924. this._collideForSubMesh(subMesh, transformMatrix, collider);
  10925. }
  10926. };
  10927. AbstractMesh.prototype._checkCollision = function (collider) {
  10928. // Bounding box test
  10929. if (!this._boundingInfo._checkCollision(collider))
  10930. return;
  10931. // Transformation matrix
  10932. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  10933. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  10934. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  10935. };
  10936. // Picking
  10937. AbstractMesh.prototype._generatePointsArray = function () {
  10938. return false;
  10939. };
  10940. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  10941. var pickingInfo = new BABYLON.PickingInfo();
  10942. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  10943. return pickingInfo;
  10944. }
  10945. if (!this._generatePointsArray()) {
  10946. return pickingInfo;
  10947. }
  10948. var intersectInfo = null;
  10949. // Octrees
  10950. var subMeshes;
  10951. var len;
  10952. if (this._submeshesOctree && this.useOctreeForPicking) {
  10953. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  10954. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  10955. len = intersections.length;
  10956. subMeshes = intersections.data;
  10957. }
  10958. else {
  10959. subMeshes = this.subMeshes;
  10960. len = subMeshes.length;
  10961. }
  10962. for (var index = 0; index < len; index++) {
  10963. var subMesh = subMeshes[index];
  10964. // Bounding test
  10965. if (len > 1 && !subMesh.canIntersects(ray))
  10966. continue;
  10967. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  10968. if (currentIntersectInfo) {
  10969. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  10970. intersectInfo = currentIntersectInfo;
  10971. intersectInfo.subMeshId = index;
  10972. if (fastCheck) {
  10973. break;
  10974. }
  10975. }
  10976. }
  10977. }
  10978. if (intersectInfo) {
  10979. // Get picked point
  10980. var world = this.getWorldMatrix();
  10981. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  10982. var direction = ray.direction.clone();
  10983. direction = direction.scale(intersectInfo.distance);
  10984. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  10985. var pickedPoint = worldOrigin.add(worldDirection);
  10986. // Return result
  10987. pickingInfo.hit = true;
  10988. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  10989. pickingInfo.pickedPoint = pickedPoint;
  10990. pickingInfo.pickedMesh = this;
  10991. pickingInfo.bu = intersectInfo.bu;
  10992. pickingInfo.bv = intersectInfo.bv;
  10993. pickingInfo.faceId = intersectInfo.faceId;
  10994. pickingInfo.subMeshId = intersectInfo.subMeshId;
  10995. return pickingInfo;
  10996. }
  10997. return pickingInfo;
  10998. };
  10999. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11000. return null;
  11001. };
  11002. AbstractMesh.prototype.releaseSubMeshes = function () {
  11003. if (this.subMeshes) {
  11004. while (this.subMeshes.length) {
  11005. this.subMeshes[0].dispose();
  11006. }
  11007. }
  11008. else {
  11009. this.subMeshes = new Array();
  11010. }
  11011. };
  11012. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11013. var _this = this;
  11014. var index;
  11015. // Action manager
  11016. if (this.actionManager) {
  11017. this.actionManager.dispose();
  11018. this.actionManager = null;
  11019. }
  11020. // Skeleton
  11021. this.skeleton = null;
  11022. // Animations
  11023. this.getScene().stopAnimation(this);
  11024. // Physics
  11025. if (this.physicsImpostor) {
  11026. this.physicsImpostor.dispose();
  11027. }
  11028. // Intersections in progress
  11029. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11030. var other = this._intersectionsInProgress[index];
  11031. var pos = other._intersectionsInProgress.indexOf(this);
  11032. other._intersectionsInProgress.splice(pos, 1);
  11033. }
  11034. this._intersectionsInProgress = [];
  11035. // Lights
  11036. var lights = this.getScene().lights;
  11037. lights.forEach(function (light) {
  11038. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11039. if (meshIndex !== -1) {
  11040. light.includedOnlyMeshes.splice(meshIndex, 1);
  11041. }
  11042. meshIndex = light.excludedMeshes.indexOf(_this);
  11043. if (meshIndex !== -1) {
  11044. light.excludedMeshes.splice(meshIndex, 1);
  11045. }
  11046. // Shadow generators
  11047. var generator = light.getShadowGenerator();
  11048. if (generator) {
  11049. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11050. if (meshIndex !== -1) {
  11051. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11052. }
  11053. }
  11054. });
  11055. // Edges
  11056. if (this._edgesRenderer) {
  11057. this._edgesRenderer.dispose();
  11058. this._edgesRenderer = null;
  11059. }
  11060. // SubMeshes
  11061. this.releaseSubMeshes();
  11062. // Engine
  11063. this.getScene().getEngine().unbindAllAttributes();
  11064. // Remove from scene
  11065. this.getScene().removeMesh(this);
  11066. if (!doNotRecurse) {
  11067. // Particles
  11068. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11069. if (this.getScene().particleSystems[index].emitter === this) {
  11070. this.getScene().particleSystems[index].dispose();
  11071. index--;
  11072. }
  11073. }
  11074. // Children
  11075. var objects = this.getDescendants(true);
  11076. for (index = 0; index < objects.length; index++) {
  11077. objects[index].dispose();
  11078. }
  11079. }
  11080. else {
  11081. var childMeshes = this.getChildMeshes(true);
  11082. for (index = 0; index < childMeshes.length; index++) {
  11083. var child = childMeshes[index];
  11084. child.parent = null;
  11085. child.computeWorldMatrix(true);
  11086. }
  11087. }
  11088. _super.prototype.dispose.call(this);
  11089. this.onAfterWorldMatrixUpdateObservable.clear();
  11090. this.onCollideObservable.clear();
  11091. this.onCollisionPositionChangeObservable.clear();
  11092. this._isDisposed = true;
  11093. // Callback
  11094. this.onDisposeObservable.notifyObservers(this);
  11095. this.onDisposeObservable.clear();
  11096. };
  11097. // Statics
  11098. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11099. AbstractMesh._BILLBOARDMODE_X = 1;
  11100. AbstractMesh._BILLBOARDMODE_Y = 2;
  11101. AbstractMesh._BILLBOARDMODE_Z = 4;
  11102. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11103. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11104. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11105. return AbstractMesh;
  11106. }(BABYLON.Node));
  11107. BABYLON.AbstractMesh = AbstractMesh;
  11108. })(BABYLON || (BABYLON = {}));
  11109. var BABYLON;
  11110. (function (BABYLON) {
  11111. var Light = (function (_super) {
  11112. __extends(Light, _super);
  11113. function Light(name, scene) {
  11114. _super.call(this, name, scene);
  11115. this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11116. this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11117. this.intensity = 1.0;
  11118. this.range = Number.MAX_VALUE;
  11119. this.includeOnlyWithLayerMask = 0;
  11120. this.includedOnlyMeshes = new Array();
  11121. this.excludedMeshes = new Array();
  11122. this.excludeWithLayerMask = 0;
  11123. this.lightmapMode = 0;
  11124. // PBR Properties.
  11125. this.radius = 0.00001;
  11126. this._excludedMeshesIds = new Array();
  11127. this._includedOnlyMeshesIds = new Array();
  11128. scene.addLight(this);
  11129. }
  11130. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11131. /**
  11132. * If every light affecting the material is in this lightmapMode,
  11133. * material.lightmapTexture adds or multiplies
  11134. * (depends on material.useLightmapAsShadowmap)
  11135. * after every other light calculations.
  11136. */
  11137. get: function () {
  11138. return Light._LIGHTMAP_DEFAULT;
  11139. },
  11140. enumerable: true,
  11141. configurable: true
  11142. });
  11143. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11144. /**
  11145. * material.lightmapTexture as only diffuse lighting from this light
  11146. * adds pnly specular lighting from this light
  11147. * adds dynamic shadows
  11148. */
  11149. get: function () {
  11150. return Light._LIGHTMAP_SPECULAR;
  11151. },
  11152. enumerable: true,
  11153. configurable: true
  11154. });
  11155. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11156. /**
  11157. * material.lightmapTexture as only lighting
  11158. * no light calculation from this light
  11159. * only adds dynamic shadows from this light
  11160. */
  11161. get: function () {
  11162. return Light._LIGHTMAP_SHADOWSONLY;
  11163. },
  11164. enumerable: true,
  11165. configurable: true
  11166. });
  11167. /**
  11168. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11169. */
  11170. Light.prototype.toString = function (fullDetails) {
  11171. var ret = "Name: " + this.name;
  11172. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11173. if (this.animations) {
  11174. for (var i = 0; i < this.animations.length; i++) {
  11175. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11176. }
  11177. }
  11178. if (fullDetails) {
  11179. }
  11180. return ret;
  11181. };
  11182. Light.prototype.getShadowGenerator = function () {
  11183. return this._shadowGenerator;
  11184. };
  11185. Light.prototype.getAbsolutePosition = function () {
  11186. return BABYLON.Vector3.Zero();
  11187. };
  11188. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11189. };
  11190. Light.prototype._getWorldMatrix = function () {
  11191. return BABYLON.Matrix.Identity();
  11192. };
  11193. Light.prototype.canAffectMesh = function (mesh) {
  11194. if (!mesh) {
  11195. return true;
  11196. }
  11197. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11198. return false;
  11199. }
  11200. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11201. return false;
  11202. }
  11203. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11204. return false;
  11205. }
  11206. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11207. return false;
  11208. }
  11209. return true;
  11210. };
  11211. Light.prototype.getWorldMatrix = function () {
  11212. this._currentRenderId = this.getScene().getRenderId();
  11213. var worldMatrix = this._getWorldMatrix();
  11214. if (this.parent && this.parent.getWorldMatrix) {
  11215. if (!this._parentedWorldMatrix) {
  11216. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11217. }
  11218. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11219. this._markSyncedWithParent();
  11220. return this._parentedWorldMatrix;
  11221. }
  11222. return worldMatrix;
  11223. };
  11224. Light.prototype.dispose = function () {
  11225. if (this._shadowGenerator) {
  11226. this._shadowGenerator.dispose();
  11227. this._shadowGenerator = null;
  11228. }
  11229. // Animations
  11230. this.getScene().stopAnimation(this);
  11231. // Remove from scene
  11232. this.getScene().removeLight(this);
  11233. _super.prototype.dispose.call(this);
  11234. };
  11235. Light.prototype.getTypeID = function () {
  11236. return 0;
  11237. };
  11238. Light.prototype.clone = function (name) {
  11239. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11240. };
  11241. Light.prototype.serialize = function () {
  11242. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11243. // Type
  11244. serializationObject.type = this.getTypeID();
  11245. // Parent
  11246. if (this.parent) {
  11247. serializationObject.parentId = this.parent.id;
  11248. }
  11249. // Inclusion / exclusions
  11250. if (this.excludedMeshes.length > 0) {
  11251. serializationObject.excludedMeshesIds = [];
  11252. this.excludedMeshes.forEach(function (mesh) {
  11253. serializationObject.excludedMeshesIds.push(mesh.id);
  11254. });
  11255. }
  11256. if (this.includedOnlyMeshes.length > 0) {
  11257. serializationObject.includedOnlyMeshesIds = [];
  11258. this.includedOnlyMeshes.forEach(function (mesh) {
  11259. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11260. });
  11261. }
  11262. // Animations
  11263. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11264. serializationObject.ranges = this.serializeAnimationRanges();
  11265. return serializationObject;
  11266. };
  11267. Light.GetConstructorFromName = function (type, name, scene) {
  11268. switch (type) {
  11269. case 0:
  11270. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11271. case 1:
  11272. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11273. case 2:
  11274. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11275. case 3:
  11276. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11277. }
  11278. };
  11279. Light.Parse = function (parsedLight, scene) {
  11280. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11281. // Inclusion / exclusions
  11282. if (parsedLight.excludedMeshesIds) {
  11283. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11284. }
  11285. if (parsedLight.includedOnlyMeshesIds) {
  11286. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11287. }
  11288. // Parent
  11289. if (parsedLight.parentId) {
  11290. light._waitingParentId = parsedLight.parentId;
  11291. }
  11292. // Animations
  11293. if (parsedLight.animations) {
  11294. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11295. var parsedAnimation = parsedLight.animations[animationIndex];
  11296. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11297. }
  11298. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11299. }
  11300. if (parsedLight.autoAnimate) {
  11301. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11302. }
  11303. return light;
  11304. };
  11305. //lightmapMode Consts
  11306. Light._LIGHTMAP_DEFAULT = 0;
  11307. Light._LIGHTMAP_SPECULAR = 1;
  11308. Light._LIGHTMAP_SHADOWSONLY = 2;
  11309. __decorate([
  11310. BABYLON.serializeAsColor3()
  11311. ], Light.prototype, "diffuse", void 0);
  11312. __decorate([
  11313. BABYLON.serializeAsColor3()
  11314. ], Light.prototype, "specular", void 0);
  11315. __decorate([
  11316. BABYLON.serialize()
  11317. ], Light.prototype, "intensity", void 0);
  11318. __decorate([
  11319. BABYLON.serialize()
  11320. ], Light.prototype, "range", void 0);
  11321. __decorate([
  11322. BABYLON.serialize()
  11323. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11324. __decorate([
  11325. BABYLON.serialize()
  11326. ], Light.prototype, "excludeWithLayerMask", void 0);
  11327. __decorate([
  11328. BABYLON.serialize()
  11329. ], Light.prototype, "lightmapMode", void 0);
  11330. __decorate([
  11331. BABYLON.serialize()
  11332. ], Light.prototype, "radius", void 0);
  11333. return Light;
  11334. }(BABYLON.Node));
  11335. BABYLON.Light = Light;
  11336. })(BABYLON || (BABYLON = {}));
  11337. var BABYLON;
  11338. (function (BABYLON) {
  11339. var PointLight = (function (_super) {
  11340. __extends(PointLight, _super);
  11341. function PointLight(name, position, scene) {
  11342. _super.call(this, name, scene);
  11343. this.position = position;
  11344. }
  11345. PointLight.prototype.getAbsolutePosition = function () {
  11346. return this.transformedPosition ? this.transformedPosition : this.position;
  11347. };
  11348. PointLight.prototype.computeTransformedPosition = function () {
  11349. if (this.parent && this.parent.getWorldMatrix) {
  11350. if (!this.transformedPosition) {
  11351. this.transformedPosition = BABYLON.Vector3.Zero();
  11352. }
  11353. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11354. return true;
  11355. }
  11356. return false;
  11357. };
  11358. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11359. if (this.parent && this.parent.getWorldMatrix) {
  11360. this.computeTransformedPosition();
  11361. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11362. return;
  11363. }
  11364. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11365. };
  11366. PointLight.prototype.needCube = function () {
  11367. return true;
  11368. };
  11369. PointLight.prototype.supportsVSM = function () {
  11370. return false;
  11371. };
  11372. PointLight.prototype.needRefreshPerFrame = function () {
  11373. return false;
  11374. };
  11375. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11376. switch (faceIndex) {
  11377. case 0:
  11378. return new BABYLON.Vector3(1, 0, 0);
  11379. case 1:
  11380. return new BABYLON.Vector3(-1, 0, 0);
  11381. case 2:
  11382. return new BABYLON.Vector3(0, -1, 0);
  11383. case 3:
  11384. return new BABYLON.Vector3(0, 1, 0);
  11385. case 4:
  11386. return new BABYLON.Vector3(0, 0, 1);
  11387. case 5:
  11388. return new BABYLON.Vector3(0, 0, -1);
  11389. }
  11390. return BABYLON.Vector3.Zero();
  11391. };
  11392. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11393. var activeCamera = this.getScene().activeCamera;
  11394. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11395. };
  11396. PointLight.prototype._getWorldMatrix = function () {
  11397. if (!this._worldMatrix) {
  11398. this._worldMatrix = BABYLON.Matrix.Identity();
  11399. }
  11400. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11401. return this._worldMatrix;
  11402. };
  11403. PointLight.prototype.getTypeID = function () {
  11404. return 0;
  11405. };
  11406. __decorate([
  11407. BABYLON.serializeAsVector3()
  11408. ], PointLight.prototype, "position", void 0);
  11409. return PointLight;
  11410. }(BABYLON.Light));
  11411. BABYLON.PointLight = PointLight;
  11412. })(BABYLON || (BABYLON = {}));
  11413. var BABYLON;
  11414. (function (BABYLON) {
  11415. var SpotLight = (function (_super) {
  11416. __extends(SpotLight, _super);
  11417. function SpotLight(name, position, direction, angle, exponent, scene) {
  11418. _super.call(this, name, scene);
  11419. this.position = position;
  11420. this.direction = direction;
  11421. this.angle = angle;
  11422. this.exponent = exponent;
  11423. }
  11424. SpotLight.prototype.getAbsolutePosition = function () {
  11425. return this.transformedPosition ? this.transformedPosition : this.position;
  11426. };
  11427. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11428. var activeCamera = this.getScene().activeCamera;
  11429. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11430. };
  11431. SpotLight.prototype.needCube = function () {
  11432. return false;
  11433. };
  11434. SpotLight.prototype.supportsVSM = function () {
  11435. return true;
  11436. };
  11437. SpotLight.prototype.needRefreshPerFrame = function () {
  11438. return false;
  11439. };
  11440. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11441. return this.direction;
  11442. };
  11443. SpotLight.prototype.setDirectionToTarget = function (target) {
  11444. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11445. return this.direction;
  11446. };
  11447. SpotLight.prototype.computeTransformedPosition = function () {
  11448. if (this.parent && this.parent.getWorldMatrix) {
  11449. if (!this.transformedPosition) {
  11450. this.transformedPosition = BABYLON.Vector3.Zero();
  11451. }
  11452. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11453. return true;
  11454. }
  11455. return false;
  11456. };
  11457. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11458. var normalizeDirection;
  11459. if (this.parent && this.parent.getWorldMatrix) {
  11460. if (!this._transformedDirection) {
  11461. this._transformedDirection = BABYLON.Vector3.Zero();
  11462. }
  11463. this.computeTransformedPosition();
  11464. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11465. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11466. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11467. }
  11468. else {
  11469. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11470. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11471. }
  11472. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11473. };
  11474. SpotLight.prototype._getWorldMatrix = function () {
  11475. if (!this._worldMatrix) {
  11476. this._worldMatrix = BABYLON.Matrix.Identity();
  11477. }
  11478. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11479. return this._worldMatrix;
  11480. };
  11481. SpotLight.prototype.getTypeID = function () {
  11482. return 2;
  11483. };
  11484. __decorate([
  11485. BABYLON.serializeAsVector3()
  11486. ], SpotLight.prototype, "position", void 0);
  11487. __decorate([
  11488. BABYLON.serializeAsVector3()
  11489. ], SpotLight.prototype, "direction", void 0);
  11490. __decorate([
  11491. BABYLON.serialize()
  11492. ], SpotLight.prototype, "angle", void 0);
  11493. __decorate([
  11494. BABYLON.serialize()
  11495. ], SpotLight.prototype, "exponent", void 0);
  11496. return SpotLight;
  11497. }(BABYLON.Light));
  11498. BABYLON.SpotLight = SpotLight;
  11499. })(BABYLON || (BABYLON = {}));
  11500. var BABYLON;
  11501. (function (BABYLON) {
  11502. var HemisphericLight = (function (_super) {
  11503. __extends(HemisphericLight, _super);
  11504. function HemisphericLight(name, direction, scene) {
  11505. _super.call(this, name, scene);
  11506. this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11507. this.direction = direction;
  11508. }
  11509. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11510. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11511. return this.direction;
  11512. };
  11513. HemisphericLight.prototype.getShadowGenerator = function () {
  11514. return null;
  11515. };
  11516. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11517. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11518. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11519. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11520. };
  11521. HemisphericLight.prototype._getWorldMatrix = function () {
  11522. if (!this._worldMatrix) {
  11523. this._worldMatrix = BABYLON.Matrix.Identity();
  11524. }
  11525. return this._worldMatrix;
  11526. };
  11527. HemisphericLight.prototype.getTypeID = function () {
  11528. return 3;
  11529. };
  11530. __decorate([
  11531. BABYLON.serializeAsColor3()
  11532. ], HemisphericLight.prototype, "groundColor", void 0);
  11533. __decorate([
  11534. BABYLON.serializeAsVector3()
  11535. ], HemisphericLight.prototype, "direction", void 0);
  11536. return HemisphericLight;
  11537. }(BABYLON.Light));
  11538. BABYLON.HemisphericLight = HemisphericLight;
  11539. })(BABYLON || (BABYLON = {}));
  11540. var BABYLON;
  11541. (function (BABYLON) {
  11542. var DirectionalLight = (function (_super) {
  11543. __extends(DirectionalLight, _super);
  11544. function DirectionalLight(name, direction, scene) {
  11545. _super.call(this, name, scene);
  11546. this.shadowOrthoScale = 0.5;
  11547. this.autoUpdateExtends = true;
  11548. // Cache
  11549. this._orthoLeft = Number.MAX_VALUE;
  11550. this._orthoRight = Number.MIN_VALUE;
  11551. this._orthoTop = Number.MIN_VALUE;
  11552. this._orthoBottom = Number.MAX_VALUE;
  11553. this.position = direction.scale(-1);
  11554. this.direction = direction;
  11555. }
  11556. DirectionalLight.prototype.getAbsolutePosition = function () {
  11557. return this.transformedPosition ? this.transformedPosition : this.position;
  11558. };
  11559. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11560. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11561. return this.direction;
  11562. };
  11563. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11564. var activeCamera = this.getScene().activeCamera;
  11565. // Check extends
  11566. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11567. var tempVector3 = BABYLON.Vector3.Zero();
  11568. this._orthoLeft = Number.MAX_VALUE;
  11569. this._orthoRight = Number.MIN_VALUE;
  11570. this._orthoTop = Number.MIN_VALUE;
  11571. this._orthoBottom = Number.MAX_VALUE;
  11572. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11573. var mesh = renderList[meshIndex];
  11574. if (!mesh) {
  11575. continue;
  11576. }
  11577. var boundingInfo = mesh.getBoundingInfo();
  11578. if (!boundingInfo) {
  11579. continue;
  11580. }
  11581. var boundingBox = boundingInfo.boundingBox;
  11582. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11583. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11584. if (tempVector3.x < this._orthoLeft)
  11585. this._orthoLeft = tempVector3.x;
  11586. if (tempVector3.y < this._orthoBottom)
  11587. this._orthoBottom = tempVector3.y;
  11588. if (tempVector3.x > this._orthoRight)
  11589. this._orthoRight = tempVector3.x;
  11590. if (tempVector3.y > this._orthoTop)
  11591. this._orthoTop = tempVector3.y;
  11592. }
  11593. }
  11594. }
  11595. var xOffset = this._orthoRight - this._orthoLeft;
  11596. var yOffset = this._orthoTop - this._orthoBottom;
  11597. 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);
  11598. };
  11599. DirectionalLight.prototype.supportsVSM = function () {
  11600. return true;
  11601. };
  11602. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11603. return true;
  11604. };
  11605. DirectionalLight.prototype.needCube = function () {
  11606. return false;
  11607. };
  11608. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11609. return this.direction;
  11610. };
  11611. DirectionalLight.prototype.computeTransformedPosition = function () {
  11612. if (this.parent && this.parent.getWorldMatrix) {
  11613. if (!this.transformedPosition) {
  11614. this.transformedPosition = BABYLON.Vector3.Zero();
  11615. }
  11616. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11617. return true;
  11618. }
  11619. return false;
  11620. };
  11621. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11622. if (this.parent && this.parent.getWorldMatrix) {
  11623. if (!this._transformedDirection) {
  11624. this._transformedDirection = BABYLON.Vector3.Zero();
  11625. }
  11626. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11627. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11628. return;
  11629. }
  11630. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11631. };
  11632. DirectionalLight.prototype._getWorldMatrix = function () {
  11633. if (!this._worldMatrix) {
  11634. this._worldMatrix = BABYLON.Matrix.Identity();
  11635. }
  11636. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11637. return this._worldMatrix;
  11638. };
  11639. DirectionalLight.prototype.getTypeID = function () {
  11640. return 1;
  11641. };
  11642. __decorate([
  11643. BABYLON.serializeAsVector3()
  11644. ], DirectionalLight.prototype, "position", void 0);
  11645. __decorate([
  11646. BABYLON.serializeAsVector3()
  11647. ], DirectionalLight.prototype, "direction", void 0);
  11648. __decorate([
  11649. BABYLON.serialize()
  11650. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11651. __decorate([
  11652. BABYLON.serialize()
  11653. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11654. return DirectionalLight;
  11655. }(BABYLON.Light));
  11656. BABYLON.DirectionalLight = DirectionalLight;
  11657. })(BABYLON || (BABYLON = {}));
  11658. var BABYLON;
  11659. (function (BABYLON) {
  11660. var ShadowGenerator = (function () {
  11661. function ShadowGenerator(mapSize, light) {
  11662. var _this = this;
  11663. // Members
  11664. this._filter = ShadowGenerator.FILTER_NONE;
  11665. this.blurScale = 2;
  11666. this._blurBoxOffset = 0;
  11667. this._bias = 0.00005;
  11668. this._lightDirection = BABYLON.Vector3.Zero();
  11669. this.forceBackFacesOnly = false;
  11670. this._darkness = 0;
  11671. this._transparencyShadow = false;
  11672. this._viewMatrix = BABYLON.Matrix.Zero();
  11673. this._projectionMatrix = BABYLON.Matrix.Zero();
  11674. this._transformMatrix = BABYLON.Matrix.Zero();
  11675. this._worldViewProjection = BABYLON.Matrix.Zero();
  11676. this._currentFaceIndex = 0;
  11677. this._currentFaceIndexCache = 0;
  11678. this._useFullFloat = true;
  11679. this._light = light;
  11680. this._scene = light.getScene();
  11681. this._mapSize = mapSize;
  11682. light._shadowGenerator = this;
  11683. // Texture type fallback from float to int if not supported.
  11684. var textureType;
  11685. var caps = this._scene.getEngine().getCaps();
  11686. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  11687. this._useFullFloat = true;
  11688. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  11689. }
  11690. else {
  11691. this._useFullFloat = false;
  11692. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  11693. }
  11694. // Render target
  11695. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  11696. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11697. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11698. this._shadowMap.anisotropicFilteringLevel = 1;
  11699. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11700. this._shadowMap.renderParticles = false;
  11701. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  11702. _this._currentFaceIndex = faceIndex;
  11703. });
  11704. this._shadowMap.onAfterUnbindObservable.add(function () {
  11705. if (!_this.useBlurVarianceShadowMap) {
  11706. return;
  11707. }
  11708. if (!_this._shadowMap2) {
  11709. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  11710. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11711. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  11712. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  11713. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  11714. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  11715. effect.setTexture("textureSampler", _this._shadowMap);
  11716. });
  11717. _this.blurBoxOffset = 1;
  11718. }
  11719. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  11720. });
  11721. // Custom render function
  11722. var renderSubMesh = function (subMesh) {
  11723. var mesh = subMesh.getRenderingMesh();
  11724. var scene = _this._scene;
  11725. var engine = scene.getEngine();
  11726. // Culling
  11727. engine.setState(subMesh.getMaterial().backFaceCulling);
  11728. // Managing instances
  11729. var batch = mesh._getInstancesRenderList(subMesh._id);
  11730. if (batch.mustReturn) {
  11731. return;
  11732. }
  11733. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  11734. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  11735. engine.enableEffect(_this._effect);
  11736. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  11737. var material = subMesh.getMaterial();
  11738. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  11739. _this._effect.setVector3("lightPosition", _this.getLight().position);
  11740. if (_this.getLight().needCube()) {
  11741. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  11742. }
  11743. // Alpha test
  11744. if (material && material.needAlphaTesting()) {
  11745. var alphaTexture = material.getAlphaTestTexture();
  11746. _this._effect.setTexture("diffuseSampler", alphaTexture);
  11747. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  11748. }
  11749. // Bones
  11750. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11751. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  11752. }
  11753. if (_this.forceBackFacesOnly) {
  11754. engine.setState(true, 0, false, true);
  11755. }
  11756. // Draw
  11757. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  11758. if (_this.forceBackFacesOnly) {
  11759. engine.setState(true, 0, false, false);
  11760. }
  11761. }
  11762. else {
  11763. // Need to reset refresh rate of the shadowMap
  11764. _this._shadowMap.resetRefreshCounter();
  11765. }
  11766. };
  11767. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  11768. var index;
  11769. for (index = 0; index < opaqueSubMeshes.length; index++) {
  11770. renderSubMesh(opaqueSubMeshes.data[index]);
  11771. }
  11772. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  11773. renderSubMesh(alphaTestSubMeshes.data[index]);
  11774. }
  11775. if (_this._transparencyShadow) {
  11776. for (index = 0; index < transparentSubMeshes.length; index++) {
  11777. renderSubMesh(transparentSubMeshes.data[index]);
  11778. }
  11779. }
  11780. };
  11781. this._shadowMap.onClearObservable.add(function (engine) {
  11782. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  11783. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  11784. }
  11785. else {
  11786. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  11787. }
  11788. });
  11789. }
  11790. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  11791. // Static
  11792. get: function () {
  11793. return ShadowGenerator._FILTER_NONE;
  11794. },
  11795. enumerable: true,
  11796. configurable: true
  11797. });
  11798. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  11799. get: function () {
  11800. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  11801. },
  11802. enumerable: true,
  11803. configurable: true
  11804. });
  11805. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  11806. get: function () {
  11807. return ShadowGenerator._FILTER_POISSONSAMPLING;
  11808. },
  11809. enumerable: true,
  11810. configurable: true
  11811. });
  11812. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  11813. get: function () {
  11814. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  11815. },
  11816. enumerable: true,
  11817. configurable: true
  11818. });
  11819. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  11820. get: function () {
  11821. return this._bias;
  11822. },
  11823. set: function (bias) {
  11824. this._bias = bias;
  11825. },
  11826. enumerable: true,
  11827. configurable: true
  11828. });
  11829. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  11830. get: function () {
  11831. return this._blurBoxOffset;
  11832. },
  11833. set: function (value) {
  11834. var _this = this;
  11835. if (this._blurBoxOffset === value) {
  11836. return;
  11837. }
  11838. this._blurBoxOffset = value;
  11839. if (this._boxBlurPostprocess) {
  11840. this._boxBlurPostprocess.dispose();
  11841. }
  11842. 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);
  11843. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  11844. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  11845. });
  11846. },
  11847. enumerable: true,
  11848. configurable: true
  11849. });
  11850. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  11851. get: function () {
  11852. return this._filter;
  11853. },
  11854. set: function (value) {
  11855. if (this._filter === value) {
  11856. return;
  11857. }
  11858. this._filter = value;
  11859. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  11860. this._shadowMap.anisotropicFilteringLevel = 16;
  11861. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  11862. }
  11863. else {
  11864. this._shadowMap.anisotropicFilteringLevel = 1;
  11865. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  11866. }
  11867. },
  11868. enumerable: true,
  11869. configurable: true
  11870. });
  11871. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  11872. get: function () {
  11873. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  11874. },
  11875. set: function (value) {
  11876. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11877. },
  11878. enumerable: true,
  11879. configurable: true
  11880. });
  11881. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  11882. get: function () {
  11883. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  11884. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  11885. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  11886. },
  11887. set: function (value) {
  11888. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  11889. },
  11890. enumerable: true,
  11891. configurable: true
  11892. });
  11893. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  11894. get: function () {
  11895. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  11896. },
  11897. set: function (value) {
  11898. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  11899. },
  11900. enumerable: true,
  11901. configurable: true
  11902. });
  11903. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  11904. var defines = [];
  11905. if (this._useFullFloat) {
  11906. defines.push("#define FULLFLOAT");
  11907. }
  11908. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  11909. defines.push("#define VSM");
  11910. }
  11911. if (this.getLight().needCube()) {
  11912. defines.push("#define CUBEMAP");
  11913. }
  11914. var attribs = [BABYLON.VertexBuffer.PositionKind];
  11915. var mesh = subMesh.getMesh();
  11916. var material = subMesh.getMaterial();
  11917. // Alpha test
  11918. if (material && material.needAlphaTesting()) {
  11919. defines.push("#define ALPHATEST");
  11920. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  11921. attribs.push(BABYLON.VertexBuffer.UVKind);
  11922. defines.push("#define UV1");
  11923. }
  11924. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  11925. var alphaTexture = material.getAlphaTestTexture();
  11926. if (alphaTexture.coordinatesIndex === 1) {
  11927. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  11928. defines.push("#define UV2");
  11929. }
  11930. }
  11931. }
  11932. // Bones
  11933. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  11934. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  11935. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  11936. if (mesh.numBoneInfluencers > 4) {
  11937. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  11938. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  11939. }
  11940. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  11941. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  11942. }
  11943. else {
  11944. defines.push("#define NUM_BONE_INFLUENCERS 0");
  11945. }
  11946. // Instances
  11947. if (useInstances) {
  11948. defines.push("#define INSTANCES");
  11949. attribs.push("world0");
  11950. attribs.push("world1");
  11951. attribs.push("world2");
  11952. attribs.push("world3");
  11953. }
  11954. // Get correct effect
  11955. var join = defines.join("\n");
  11956. if (this._cachedDefines !== join) {
  11957. this._cachedDefines = join;
  11958. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  11959. }
  11960. return this._effect.isReady();
  11961. };
  11962. ShadowGenerator.prototype.getShadowMap = function () {
  11963. return this._shadowMap;
  11964. };
  11965. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  11966. if (this._shadowMap2) {
  11967. return this._shadowMap2;
  11968. }
  11969. return this._shadowMap;
  11970. };
  11971. ShadowGenerator.prototype.getLight = function () {
  11972. return this._light;
  11973. };
  11974. // Methods
  11975. ShadowGenerator.prototype.getTransformMatrix = function () {
  11976. var scene = this._scene;
  11977. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  11978. return this._transformMatrix;
  11979. }
  11980. this._currentRenderID = scene.getRenderId();
  11981. this._currentFaceIndexCache = this._currentFaceIndex;
  11982. var lightPosition = this._light.position;
  11983. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  11984. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  11985. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  11986. }
  11987. if (this._light.computeTransformedPosition()) {
  11988. lightPosition = this._light.transformedPosition;
  11989. }
  11990. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  11991. this._cachedPosition = lightPosition.clone();
  11992. this._cachedDirection = this._lightDirection.clone();
  11993. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  11994. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  11995. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  11996. }
  11997. return this._transformMatrix;
  11998. };
  11999. ShadowGenerator.prototype.getDarkness = function () {
  12000. return this._darkness;
  12001. };
  12002. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12003. if (darkness >= 1.0)
  12004. this._darkness = 1.0;
  12005. else if (darkness <= 0.0)
  12006. this._darkness = 0.0;
  12007. else
  12008. this._darkness = darkness;
  12009. };
  12010. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12011. this._transparencyShadow = hasShadow;
  12012. };
  12013. ShadowGenerator.prototype._packHalf = function (depth) {
  12014. var scale = depth * 255.0;
  12015. var fract = scale - Math.floor(scale);
  12016. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12017. };
  12018. ShadowGenerator.prototype.dispose = function () {
  12019. this._shadowMap.dispose();
  12020. if (this._shadowMap2) {
  12021. this._shadowMap2.dispose();
  12022. }
  12023. if (this._downSamplePostprocess) {
  12024. this._downSamplePostprocess.dispose();
  12025. }
  12026. if (this._boxBlurPostprocess) {
  12027. this._boxBlurPostprocess.dispose();
  12028. }
  12029. };
  12030. ShadowGenerator.prototype.serialize = function () {
  12031. var serializationObject = {};
  12032. serializationObject.lightId = this._light.id;
  12033. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12034. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12035. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12036. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12037. serializationObject.renderList = [];
  12038. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12039. var mesh = this.getShadowMap().renderList[meshIndex];
  12040. serializationObject.renderList.push(mesh.id);
  12041. }
  12042. return serializationObject;
  12043. };
  12044. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12045. //casting to point light, as light is missing the position attr and typescript complains.
  12046. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12047. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12048. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12049. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12050. meshes.forEach(function (mesh) {
  12051. shadowGenerator.getShadowMap().renderList.push(mesh);
  12052. });
  12053. }
  12054. if (parsedShadowGenerator.usePoissonSampling) {
  12055. shadowGenerator.usePoissonSampling = true;
  12056. }
  12057. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12058. shadowGenerator.useVarianceShadowMap = true;
  12059. }
  12060. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12061. shadowGenerator.useBlurVarianceShadowMap = true;
  12062. if (parsedShadowGenerator.blurScale) {
  12063. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12064. }
  12065. if (parsedShadowGenerator.blurBoxOffset) {
  12066. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12067. }
  12068. }
  12069. if (parsedShadowGenerator.bias !== undefined) {
  12070. shadowGenerator.bias = parsedShadowGenerator.bias;
  12071. }
  12072. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12073. return shadowGenerator;
  12074. };
  12075. ShadowGenerator._FILTER_NONE = 0;
  12076. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12077. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12078. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12079. return ShadowGenerator;
  12080. }());
  12081. BABYLON.ShadowGenerator = ShadowGenerator;
  12082. })(BABYLON || (BABYLON = {}));
  12083. var BABYLON;
  12084. (function (BABYLON) {
  12085. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12086. if (boxMin.x > sphereCenter.x + sphereRadius)
  12087. return false;
  12088. if (sphereCenter.x - sphereRadius > boxMax.x)
  12089. return false;
  12090. if (boxMin.y > sphereCenter.y + sphereRadius)
  12091. return false;
  12092. if (sphereCenter.y - sphereRadius > boxMax.y)
  12093. return false;
  12094. if (boxMin.z > sphereCenter.z + sphereRadius)
  12095. return false;
  12096. if (sphereCenter.z - sphereRadius > boxMax.z)
  12097. return false;
  12098. return true;
  12099. };
  12100. var getLowestRoot = (function () {
  12101. var result = { root: 0, found: false };
  12102. return function (a, b, c, maxR) {
  12103. result.root = 0;
  12104. result.found = false;
  12105. var determinant = b * b - 4.0 * a * c;
  12106. if (determinant < 0)
  12107. return result;
  12108. var sqrtD = Math.sqrt(determinant);
  12109. var r1 = (-b - sqrtD) / (2.0 * a);
  12110. var r2 = (-b + sqrtD) / (2.0 * a);
  12111. if (r1 > r2) {
  12112. var temp = r2;
  12113. r2 = r1;
  12114. r1 = temp;
  12115. }
  12116. if (r1 > 0 && r1 < maxR) {
  12117. result.root = r1;
  12118. result.found = true;
  12119. return result;
  12120. }
  12121. if (r2 > 0 && r2 < maxR) {
  12122. result.root = r2;
  12123. result.found = true;
  12124. return result;
  12125. }
  12126. return result;
  12127. };
  12128. })();
  12129. var Collider = (function () {
  12130. function Collider() {
  12131. this.radius = new BABYLON.Vector3(1, 1, 1);
  12132. this.retry = 0;
  12133. this.basePointWorld = BABYLON.Vector3.Zero();
  12134. this.velocityWorld = BABYLON.Vector3.Zero();
  12135. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12136. this._collisionPoint = BABYLON.Vector3.Zero();
  12137. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12138. this._tempVector = BABYLON.Vector3.Zero();
  12139. this._tempVector2 = BABYLON.Vector3.Zero();
  12140. this._tempVector3 = BABYLON.Vector3.Zero();
  12141. this._tempVector4 = BABYLON.Vector3.Zero();
  12142. this._edge = BABYLON.Vector3.Zero();
  12143. this._baseToVertex = BABYLON.Vector3.Zero();
  12144. this._destinationPoint = BABYLON.Vector3.Zero();
  12145. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12146. this._displacementVector = BABYLON.Vector3.Zero();
  12147. }
  12148. // Methods
  12149. Collider.prototype._initialize = function (source, dir, e) {
  12150. this.velocity = dir;
  12151. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12152. this.basePoint = source;
  12153. source.multiplyToRef(this.radius, this.basePointWorld);
  12154. dir.multiplyToRef(this.radius, this.velocityWorld);
  12155. this.velocityWorldLength = this.velocityWorld.length();
  12156. this.epsilon = e;
  12157. this.collisionFound = false;
  12158. };
  12159. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12160. pa.subtractToRef(point, this._tempVector);
  12161. pb.subtractToRef(point, this._tempVector2);
  12162. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12163. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12164. if (d < 0)
  12165. return false;
  12166. pc.subtractToRef(point, this._tempVector3);
  12167. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12168. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12169. if (d < 0)
  12170. return false;
  12171. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12172. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12173. return d >= 0;
  12174. };
  12175. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12176. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12177. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12178. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12179. return false;
  12180. }
  12181. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12182. return false;
  12183. return true;
  12184. };
  12185. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12186. var t0;
  12187. var embeddedInPlane = false;
  12188. //defensive programming, actually not needed.
  12189. if (!trianglePlaneArray) {
  12190. trianglePlaneArray = [];
  12191. }
  12192. if (!trianglePlaneArray[faceIndex]) {
  12193. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12194. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12195. }
  12196. var trianglePlane = trianglePlaneArray[faceIndex];
  12197. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12198. return;
  12199. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12200. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12201. if (normalDotVelocity == 0) {
  12202. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12203. return;
  12204. embeddedInPlane = true;
  12205. t0 = 0;
  12206. }
  12207. else {
  12208. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12209. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12210. if (t0 > t1) {
  12211. var temp = t1;
  12212. t1 = t0;
  12213. t0 = temp;
  12214. }
  12215. if (t0 > 1.0 || t1 < 0.0)
  12216. return;
  12217. if (t0 < 0)
  12218. t0 = 0;
  12219. if (t0 > 1.0)
  12220. t0 = 1.0;
  12221. }
  12222. this._collisionPoint.copyFromFloats(0, 0, 0);
  12223. var found = false;
  12224. var t = 1.0;
  12225. if (!embeddedInPlane) {
  12226. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12227. this.velocity.scaleToRef(t0, this._tempVector);
  12228. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12229. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12230. found = true;
  12231. t = t0;
  12232. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12233. }
  12234. }
  12235. if (!found) {
  12236. var velocitySquaredLength = this.velocity.lengthSquared();
  12237. var a = velocitySquaredLength;
  12238. this.basePoint.subtractToRef(p1, this._tempVector);
  12239. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12240. var c = this._tempVector.lengthSquared() - 1.0;
  12241. var lowestRoot = getLowestRoot(a, b, c, t);
  12242. if (lowestRoot.found) {
  12243. t = lowestRoot.root;
  12244. found = true;
  12245. this._collisionPoint.copyFrom(p1);
  12246. }
  12247. this.basePoint.subtractToRef(p2, this._tempVector);
  12248. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12249. c = this._tempVector.lengthSquared() - 1.0;
  12250. lowestRoot = getLowestRoot(a, b, c, t);
  12251. if (lowestRoot.found) {
  12252. t = lowestRoot.root;
  12253. found = true;
  12254. this._collisionPoint.copyFrom(p2);
  12255. }
  12256. this.basePoint.subtractToRef(p3, this._tempVector);
  12257. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12258. c = this._tempVector.lengthSquared() - 1.0;
  12259. lowestRoot = getLowestRoot(a, b, c, t);
  12260. if (lowestRoot.found) {
  12261. t = lowestRoot.root;
  12262. found = true;
  12263. this._collisionPoint.copyFrom(p3);
  12264. }
  12265. p2.subtractToRef(p1, this._edge);
  12266. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12267. var edgeSquaredLength = this._edge.lengthSquared();
  12268. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12269. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12270. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12271. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12272. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12273. lowestRoot = getLowestRoot(a, b, c, t);
  12274. if (lowestRoot.found) {
  12275. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12276. if (f >= 0.0 && f <= 1.0) {
  12277. t = lowestRoot.root;
  12278. found = true;
  12279. this._edge.scaleInPlace(f);
  12280. p1.addToRef(this._edge, this._collisionPoint);
  12281. }
  12282. }
  12283. p3.subtractToRef(p2, this._edge);
  12284. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12285. edgeSquaredLength = this._edge.lengthSquared();
  12286. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12287. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12288. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12289. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12290. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12291. lowestRoot = getLowestRoot(a, b, c, t);
  12292. if (lowestRoot.found) {
  12293. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12294. if (f >= 0.0 && f <= 1.0) {
  12295. t = lowestRoot.root;
  12296. found = true;
  12297. this._edge.scaleInPlace(f);
  12298. p2.addToRef(this._edge, this._collisionPoint);
  12299. }
  12300. }
  12301. p1.subtractToRef(p3, this._edge);
  12302. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12303. edgeSquaredLength = this._edge.lengthSquared();
  12304. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12305. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12306. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12307. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12308. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12309. lowestRoot = getLowestRoot(a, b, c, t);
  12310. if (lowestRoot.found) {
  12311. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12312. if (f >= 0.0 && f <= 1.0) {
  12313. t = lowestRoot.root;
  12314. found = true;
  12315. this._edge.scaleInPlace(f);
  12316. p3.addToRef(this._edge, this._collisionPoint);
  12317. }
  12318. }
  12319. }
  12320. if (found) {
  12321. var distToCollision = t * this.velocity.length();
  12322. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12323. if (!this.intersectionPoint) {
  12324. this.intersectionPoint = this._collisionPoint.clone();
  12325. }
  12326. else {
  12327. this.intersectionPoint.copyFrom(this._collisionPoint);
  12328. }
  12329. this.nearestDistance = distToCollision;
  12330. this.collisionFound = true;
  12331. }
  12332. }
  12333. };
  12334. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12335. for (var i = indexStart; i < indexEnd; i += 3) {
  12336. var p1 = pts[indices[i] - decal];
  12337. var p2 = pts[indices[i + 1] - decal];
  12338. var p3 = pts[indices[i + 2] - decal];
  12339. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12340. }
  12341. };
  12342. Collider.prototype._getResponse = function (pos, vel) {
  12343. pos.addToRef(vel, this._destinationPoint);
  12344. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12345. this.basePoint.addToRef(vel, pos);
  12346. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12347. this._slidePlaneNormal.normalize();
  12348. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12349. pos.addInPlace(this._displacementVector);
  12350. this.intersectionPoint.addInPlace(this._displacementVector);
  12351. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12352. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12353. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12354. };
  12355. return Collider;
  12356. }());
  12357. BABYLON.Collider = Collider;
  12358. })(BABYLON || (BABYLON = {}));
  12359. var BABYLON;
  12360. (function (BABYLON) {
  12361. //WebWorker code will be inserted to this variable.
  12362. BABYLON.CollisionWorker = "";
  12363. (function (WorkerTaskType) {
  12364. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12365. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12366. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12367. })(BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12368. var WorkerTaskType = BABYLON.WorkerTaskType;
  12369. (function (WorkerReplyType) {
  12370. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12371. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12372. })(BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12373. var WorkerReplyType = BABYLON.WorkerReplyType;
  12374. var CollisionCoordinatorWorker = (function () {
  12375. function CollisionCoordinatorWorker() {
  12376. var _this = this;
  12377. this._scaledPosition = BABYLON.Vector3.Zero();
  12378. this._scaledVelocity = BABYLON.Vector3.Zero();
  12379. this.onMeshUpdated = function (mesh) {
  12380. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12381. };
  12382. this.onGeometryUpdated = function (geometry) {
  12383. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12384. };
  12385. this._afterRender = function () {
  12386. if (!_this._init)
  12387. return;
  12388. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12389. return;
  12390. }
  12391. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12392. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12393. if (_this._runningUpdated > 4) {
  12394. return;
  12395. }
  12396. ++_this._runningUpdated;
  12397. var payload = {
  12398. updatedMeshes: _this._addUpdateMeshesList,
  12399. updatedGeometries: _this._addUpdateGeometriesList,
  12400. removedGeometries: _this._toRemoveGeometryArray,
  12401. removedMeshes: _this._toRemoveMeshesArray
  12402. };
  12403. var message = {
  12404. payload: payload,
  12405. taskType: WorkerTaskType.UPDATE
  12406. };
  12407. var serializable = [];
  12408. for (var id in payload.updatedGeometries) {
  12409. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12410. //prepare transferables
  12411. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12412. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12413. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12414. }
  12415. }
  12416. _this._worker.postMessage(message, serializable);
  12417. _this._addUpdateMeshesList = {};
  12418. _this._addUpdateGeometriesList = {};
  12419. _this._toRemoveGeometryArray = [];
  12420. _this._toRemoveMeshesArray = [];
  12421. };
  12422. this._onMessageFromWorker = function (e) {
  12423. var returnData = e.data;
  12424. if (returnData.error != WorkerReplyType.SUCCESS) {
  12425. //TODO what errors can be returned from the worker?
  12426. BABYLON.Tools.Warn("error returned from worker!");
  12427. return;
  12428. }
  12429. switch (returnData.taskType) {
  12430. case WorkerTaskType.INIT:
  12431. _this._init = true;
  12432. //Update the worked with ALL of the scene's current state
  12433. _this._scene.meshes.forEach(function (mesh) {
  12434. _this.onMeshAdded(mesh);
  12435. });
  12436. _this._scene.getGeometries().forEach(function (geometry) {
  12437. _this.onGeometryAdded(geometry);
  12438. });
  12439. break;
  12440. case WorkerTaskType.UPDATE:
  12441. _this._runningUpdated--;
  12442. break;
  12443. case WorkerTaskType.COLLIDE:
  12444. _this._runningCollisionTask = false;
  12445. var returnPayload = returnData.payload;
  12446. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12447. return;
  12448. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12449. //cleanup
  12450. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12451. break;
  12452. }
  12453. };
  12454. this._collisionsCallbackArray = [];
  12455. this._init = false;
  12456. this._runningUpdated = 0;
  12457. this._runningCollisionTask = false;
  12458. this._addUpdateMeshesList = {};
  12459. this._addUpdateGeometriesList = {};
  12460. this._toRemoveGeometryArray = [];
  12461. this._toRemoveMeshesArray = [];
  12462. }
  12463. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12464. if (!this._init)
  12465. return;
  12466. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12467. return;
  12468. position.divideToRef(collider.radius, this._scaledPosition);
  12469. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12470. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12471. var payload = {
  12472. collider: {
  12473. position: this._scaledPosition.asArray(),
  12474. velocity: this._scaledVelocity.asArray(),
  12475. radius: collider.radius.asArray()
  12476. },
  12477. collisionId: collisionIndex,
  12478. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12479. maximumRetry: maximumRetry
  12480. };
  12481. var message = {
  12482. payload: payload,
  12483. taskType: WorkerTaskType.COLLIDE
  12484. };
  12485. this._worker.postMessage(message);
  12486. };
  12487. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12488. this._scene = scene;
  12489. this._scene.registerAfterRender(this._afterRender);
  12490. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12491. this._worker = new Worker(workerUrl);
  12492. this._worker.onmessage = this._onMessageFromWorker;
  12493. var message = {
  12494. payload: {},
  12495. taskType: WorkerTaskType.INIT
  12496. };
  12497. this._worker.postMessage(message);
  12498. };
  12499. CollisionCoordinatorWorker.prototype.destroy = function () {
  12500. this._scene.unregisterAfterRender(this._afterRender);
  12501. this._worker.terminate();
  12502. };
  12503. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12504. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12505. this.onMeshUpdated(mesh);
  12506. };
  12507. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12508. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12509. };
  12510. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12511. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12512. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12513. this.onGeometryUpdated(geometry);
  12514. };
  12515. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12516. this._toRemoveGeometryArray.push(geometry.id);
  12517. };
  12518. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12519. var submeshes = [];
  12520. if (mesh.subMeshes) {
  12521. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12522. return {
  12523. position: idx,
  12524. verticesStart: sm.verticesStart,
  12525. verticesCount: sm.verticesCount,
  12526. indexStart: sm.indexStart,
  12527. indexCount: sm.indexCount,
  12528. hasMaterial: !!sm.getMaterial(),
  12529. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12530. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12531. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12532. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12533. };
  12534. });
  12535. }
  12536. var geometryId = null;
  12537. if (mesh instanceof BABYLON.Mesh) {
  12538. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12539. }
  12540. else if (mesh instanceof BABYLON.InstancedMesh) {
  12541. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12542. }
  12543. return {
  12544. uniqueId: mesh.uniqueId,
  12545. id: mesh.id,
  12546. name: mesh.name,
  12547. geometryId: geometryId,
  12548. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12549. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12550. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12551. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12552. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12553. subMeshes: submeshes,
  12554. checkCollisions: mesh.checkCollisions
  12555. };
  12556. };
  12557. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12558. return {
  12559. id: geometry.id,
  12560. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12561. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12562. indices: new Int32Array(geometry.getIndices() || []),
  12563. };
  12564. };
  12565. return CollisionCoordinatorWorker;
  12566. }());
  12567. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12568. var CollisionCoordinatorLegacy = (function () {
  12569. function CollisionCoordinatorLegacy() {
  12570. this._scaledPosition = BABYLON.Vector3.Zero();
  12571. this._scaledVelocity = BABYLON.Vector3.Zero();
  12572. this._finalPosition = BABYLON.Vector3.Zero();
  12573. }
  12574. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12575. position.divideToRef(collider.radius, this._scaledPosition);
  12576. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12577. collider.collidedMesh = null;
  12578. collider.retry = 0;
  12579. collider.initialVelocity = this._scaledVelocity;
  12580. collider.initialPosition = this._scaledPosition;
  12581. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12582. this._finalPosition.multiplyInPlace(collider.radius);
  12583. //run the callback
  12584. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12585. };
  12586. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12587. this._scene = scene;
  12588. };
  12589. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12590. //Legacy need no destruction method.
  12591. };
  12592. //No update in legacy mode
  12593. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12594. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12595. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12596. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12597. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12598. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12599. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12600. if (excludedMesh === void 0) { excludedMesh = null; }
  12601. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12602. if (collider.retry >= maximumRetry) {
  12603. finalPosition.copyFrom(position);
  12604. return;
  12605. }
  12606. collider._initialize(position, velocity, closeDistance);
  12607. // Check all meshes
  12608. for (var index = 0; index < this._scene.meshes.length; index++) {
  12609. var mesh = this._scene.meshes[index];
  12610. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12611. mesh._checkCollision(collider);
  12612. }
  12613. }
  12614. if (!collider.collisionFound) {
  12615. position.addToRef(velocity, finalPosition);
  12616. return;
  12617. }
  12618. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12619. collider._getResponse(position, velocity);
  12620. }
  12621. if (velocity.length() <= closeDistance) {
  12622. finalPosition.copyFrom(position);
  12623. return;
  12624. }
  12625. collider.retry++;
  12626. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12627. };
  12628. return CollisionCoordinatorLegacy;
  12629. }());
  12630. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12631. })(BABYLON || (BABYLON = {}));
  12632. var BABYLON;
  12633. (function (BABYLON) {
  12634. var Camera = (function (_super) {
  12635. __extends(Camera, _super);
  12636. function Camera(name, position, scene) {
  12637. _super.call(this, name, scene);
  12638. this.upVector = BABYLON.Vector3.Up();
  12639. this.orthoLeft = null;
  12640. this.orthoRight = null;
  12641. this.orthoBottom = null;
  12642. this.orthoTop = null;
  12643. this.fov = 0.8;
  12644. this.minZ = 1.0;
  12645. this.maxZ = 10000.0;
  12646. this.inertia = 0.9;
  12647. this.mode = Camera.PERSPECTIVE_CAMERA;
  12648. this.isIntermediate = false;
  12649. this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12650. this.layerMask = 0x0FFFFFFF;
  12651. this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12652. // Camera rig members
  12653. this.cameraRigMode = Camera.RIG_MODE_NONE;
  12654. this._rigCameras = new Array();
  12655. // Cache
  12656. this._computedViewMatrix = BABYLON.Matrix.Identity();
  12657. this._projectionMatrix = new BABYLON.Matrix();
  12658. this._doNotComputeProjectionMatrix = false;
  12659. this._postProcesses = new Array();
  12660. this._transformMatrix = BABYLON.Matrix.Zero();
  12661. this._webvrViewMatrix = BABYLON.Matrix.Identity();
  12662. this._activeMeshes = new BABYLON.SmartArray(256);
  12663. this._globalPosition = BABYLON.Vector3.Zero();
  12664. this._refreshFrustumPlanes = true;
  12665. scene.addCamera(this);
  12666. if (!scene.activeCamera) {
  12667. scene.activeCamera = this;
  12668. }
  12669. this.position = position;
  12670. }
  12671. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  12672. get: function () {
  12673. return Camera._PERSPECTIVE_CAMERA;
  12674. },
  12675. enumerable: true,
  12676. configurable: true
  12677. });
  12678. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  12679. get: function () {
  12680. return Camera._ORTHOGRAPHIC_CAMERA;
  12681. },
  12682. enumerable: true,
  12683. configurable: true
  12684. });
  12685. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  12686. get: function () {
  12687. return Camera._FOVMODE_VERTICAL_FIXED;
  12688. },
  12689. enumerable: true,
  12690. configurable: true
  12691. });
  12692. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  12693. get: function () {
  12694. return Camera._FOVMODE_HORIZONTAL_FIXED;
  12695. },
  12696. enumerable: true,
  12697. configurable: true
  12698. });
  12699. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  12700. get: function () {
  12701. return Camera._RIG_MODE_NONE;
  12702. },
  12703. enumerable: true,
  12704. configurable: true
  12705. });
  12706. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  12707. get: function () {
  12708. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  12709. },
  12710. enumerable: true,
  12711. configurable: true
  12712. });
  12713. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  12714. get: function () {
  12715. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  12716. },
  12717. enumerable: true,
  12718. configurable: true
  12719. });
  12720. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  12721. get: function () {
  12722. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  12723. },
  12724. enumerable: true,
  12725. configurable: true
  12726. });
  12727. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  12728. get: function () {
  12729. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  12730. },
  12731. enumerable: true,
  12732. configurable: true
  12733. });
  12734. Object.defineProperty(Camera, "RIG_MODE_VR", {
  12735. get: function () {
  12736. return Camera._RIG_MODE_VR;
  12737. },
  12738. enumerable: true,
  12739. configurable: true
  12740. });
  12741. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  12742. get: function () {
  12743. return Camera._RIG_MODE_WEBVR;
  12744. },
  12745. enumerable: true,
  12746. configurable: true
  12747. });
  12748. /**
  12749. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12750. */
  12751. Camera.prototype.toString = function (fullDetails) {
  12752. var ret = "Name: " + this.name;
  12753. ret += ", type: " + this.getTypeName();
  12754. if (this.animations) {
  12755. for (var i = 0; i < this.animations.length; i++) {
  12756. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12757. }
  12758. }
  12759. if (fullDetails) {
  12760. }
  12761. return ret;
  12762. };
  12763. Object.defineProperty(Camera.prototype, "globalPosition", {
  12764. get: function () {
  12765. return this._globalPosition;
  12766. },
  12767. enumerable: true,
  12768. configurable: true
  12769. });
  12770. Camera.prototype.getActiveMeshes = function () {
  12771. return this._activeMeshes;
  12772. };
  12773. Camera.prototype.isActiveMesh = function (mesh) {
  12774. return (this._activeMeshes.indexOf(mesh) !== -1);
  12775. };
  12776. //Cache
  12777. Camera.prototype._initCache = function () {
  12778. _super.prototype._initCache.call(this);
  12779. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12780. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  12781. this._cache.mode = undefined;
  12782. this._cache.minZ = undefined;
  12783. this._cache.maxZ = undefined;
  12784. this._cache.fov = undefined;
  12785. this._cache.fovMode = undefined;
  12786. this._cache.aspectRatio = undefined;
  12787. this._cache.orthoLeft = undefined;
  12788. this._cache.orthoRight = undefined;
  12789. this._cache.orthoBottom = undefined;
  12790. this._cache.orthoTop = undefined;
  12791. this._cache.renderWidth = undefined;
  12792. this._cache.renderHeight = undefined;
  12793. };
  12794. Camera.prototype._updateCache = function (ignoreParentClass) {
  12795. if (!ignoreParentClass) {
  12796. _super.prototype._updateCache.call(this);
  12797. }
  12798. var engine = this.getEngine();
  12799. this._cache.position.copyFrom(this.position);
  12800. this._cache.upVector.copyFrom(this.upVector);
  12801. this._cache.mode = this.mode;
  12802. this._cache.minZ = this.minZ;
  12803. this._cache.maxZ = this.maxZ;
  12804. this._cache.fov = this.fov;
  12805. this._cache.fovMode = this.fovMode;
  12806. this._cache.aspectRatio = engine.getAspectRatio(this);
  12807. this._cache.orthoLeft = this.orthoLeft;
  12808. this._cache.orthoRight = this.orthoRight;
  12809. this._cache.orthoBottom = this.orthoBottom;
  12810. this._cache.orthoTop = this.orthoTop;
  12811. this._cache.renderWidth = engine.getRenderWidth();
  12812. this._cache.renderHeight = engine.getRenderHeight();
  12813. };
  12814. Camera.prototype._updateFromScene = function () {
  12815. this.updateCache();
  12816. this.update();
  12817. };
  12818. // Synchronized
  12819. Camera.prototype._isSynchronized = function () {
  12820. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  12821. };
  12822. Camera.prototype._isSynchronizedViewMatrix = function () {
  12823. if (!_super.prototype._isSynchronized.call(this))
  12824. return false;
  12825. return this._cache.position.equals(this.position)
  12826. && this._cache.upVector.equals(this.upVector)
  12827. && this.isSynchronizedWithParent();
  12828. };
  12829. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  12830. var check = this._cache.mode === this.mode
  12831. && this._cache.minZ === this.minZ
  12832. && this._cache.maxZ === this.maxZ;
  12833. if (!check) {
  12834. return false;
  12835. }
  12836. var engine = this.getEngine();
  12837. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12838. check = this._cache.fov === this.fov
  12839. && this._cache.fovMode === this.fovMode
  12840. && this._cache.aspectRatio === engine.getAspectRatio(this);
  12841. }
  12842. else {
  12843. check = this._cache.orthoLeft === this.orthoLeft
  12844. && this._cache.orthoRight === this.orthoRight
  12845. && this._cache.orthoBottom === this.orthoBottom
  12846. && this._cache.orthoTop === this.orthoTop
  12847. && this._cache.renderWidth === engine.getRenderWidth()
  12848. && this._cache.renderHeight === engine.getRenderHeight();
  12849. }
  12850. return check;
  12851. };
  12852. // Controls
  12853. Camera.prototype.attachControl = function (element, noPreventDefault) {
  12854. };
  12855. Camera.prototype.detachControl = function (element) {
  12856. };
  12857. Camera.prototype.update = function () {
  12858. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  12859. this._updateRigCameras();
  12860. }
  12861. this._checkInputs();
  12862. };
  12863. Camera.prototype._checkInputs = function () {
  12864. };
  12865. Camera.prototype._cascadePostProcessesToRigCams = function () {
  12866. // invalidate framebuffer
  12867. if (this._postProcesses.length > 0) {
  12868. this._postProcesses[0].markTextureDirty();
  12869. }
  12870. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  12871. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  12872. var cam = this._rigCameras[i];
  12873. var rigPostProcess = cam._rigPostProcess;
  12874. // for VR rig, there does not have to be a post process
  12875. if (rigPostProcess) {
  12876. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  12877. if (isPass) {
  12878. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  12879. cam.isIntermediate = this._postProcesses.length === 0;
  12880. }
  12881. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  12882. rigPostProcess.markTextureDirty();
  12883. }
  12884. else {
  12885. cam._postProcesses = this._postProcesses.slice(0);
  12886. }
  12887. }
  12888. };
  12889. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  12890. if (insertAt === void 0) { insertAt = null; }
  12891. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  12892. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  12893. return 0;
  12894. }
  12895. if (insertAt == null || insertAt < 0) {
  12896. this._postProcesses.push(postProcess);
  12897. }
  12898. else {
  12899. this._postProcesses.splice(insertAt, 0, postProcess);
  12900. }
  12901. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12902. return this._postProcesses.indexOf(postProcess);
  12903. };
  12904. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  12905. if (atIndices === void 0) { atIndices = null; }
  12906. var result = [];
  12907. var i;
  12908. var index;
  12909. if (!atIndices) {
  12910. var idx = this._postProcesses.indexOf(postProcess);
  12911. if (idx !== -1) {
  12912. this._postProcesses.splice(idx, 1);
  12913. }
  12914. }
  12915. else {
  12916. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  12917. // iterate descending, so can just splice as we go
  12918. for (i = atIndices.length - 1; i >= 0; i--) {
  12919. if (this._postProcesses[atIndices[i]] !== postProcess) {
  12920. result.push(i);
  12921. continue;
  12922. }
  12923. this._postProcesses.splice(index, 1);
  12924. }
  12925. }
  12926. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  12927. return result;
  12928. };
  12929. Camera.prototype.getWorldMatrix = function () {
  12930. if (!this._worldMatrix) {
  12931. this._worldMatrix = BABYLON.Matrix.Identity();
  12932. }
  12933. var viewMatrix = this.getViewMatrix();
  12934. viewMatrix.invertToRef(this._worldMatrix);
  12935. return this._worldMatrix;
  12936. };
  12937. Camera.prototype._getViewMatrix = function () {
  12938. return BABYLON.Matrix.Identity();
  12939. };
  12940. Camera.prototype.getViewMatrix = function (force) {
  12941. this._computedViewMatrix = this._computeViewMatrix(force);
  12942. if (!force && this._isSynchronizedViewMatrix()) {
  12943. return this._computedViewMatrix;
  12944. }
  12945. this._refreshFrustumPlanes = true;
  12946. if (!this.parent || !this.parent.getWorldMatrix) {
  12947. this._globalPosition.copyFrom(this.position);
  12948. }
  12949. else {
  12950. if (!this._worldMatrix) {
  12951. this._worldMatrix = BABYLON.Matrix.Identity();
  12952. }
  12953. this._computedViewMatrix.invertToRef(this._worldMatrix);
  12954. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  12955. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  12956. this._computedViewMatrix.invert();
  12957. this._markSyncedWithParent();
  12958. }
  12959. this._currentRenderId = this.getScene().getRenderId();
  12960. return this._computedViewMatrix;
  12961. };
  12962. Camera.prototype._computeViewMatrix = function (force) {
  12963. if (!force && this._isSynchronizedViewMatrix()) {
  12964. return this._computedViewMatrix;
  12965. }
  12966. this._computedViewMatrix = this._getViewMatrix();
  12967. this._currentRenderId = this.getScene().getRenderId();
  12968. return this._computedViewMatrix;
  12969. };
  12970. Camera.prototype.freezeProjectionMatrix = function (projection) {
  12971. this._doNotComputeProjectionMatrix = true;
  12972. if (projection !== undefined) {
  12973. this._projectionMatrix = projection;
  12974. }
  12975. };
  12976. ;
  12977. Camera.prototype.unfreezeProjectionMatrix = function () {
  12978. this._doNotComputeProjectionMatrix = false;
  12979. };
  12980. ;
  12981. Camera.prototype.getProjectionMatrix = function (force) {
  12982. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  12983. return this._projectionMatrix;
  12984. }
  12985. this._refreshFrustumPlanes = true;
  12986. var engine = this.getEngine();
  12987. var scene = this.getScene();
  12988. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  12989. if (this.minZ <= 0) {
  12990. this.minZ = 0.1;
  12991. }
  12992. if (scene.useRightHandedSystem) {
  12993. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12994. }
  12995. else {
  12996. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  12997. }
  12998. return this._projectionMatrix;
  12999. }
  13000. var halfWidth = engine.getRenderWidth() / 2.0;
  13001. var halfHeight = engine.getRenderHeight() / 2.0;
  13002. if (scene.useRightHandedSystem) {
  13003. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13004. }
  13005. else {
  13006. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13007. }
  13008. return this._projectionMatrix;
  13009. };
  13010. Camera.prototype.getTranformationMatrix = function () {
  13011. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13012. return this._transformMatrix;
  13013. };
  13014. Camera.prototype.updateFrustumPlanes = function () {
  13015. if (!this._refreshFrustumPlanes) {
  13016. return;
  13017. }
  13018. this.getTranformationMatrix();
  13019. if (!this._frustumPlanes) {
  13020. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13021. }
  13022. else {
  13023. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13024. }
  13025. this._refreshFrustumPlanes = false;
  13026. };
  13027. Camera.prototype.isInFrustum = function (target) {
  13028. this.updateFrustumPlanes();
  13029. return target.isInFrustum(this._frustumPlanes);
  13030. };
  13031. Camera.prototype.isCompletelyInFrustum = function (target) {
  13032. this.updateFrustumPlanes();
  13033. return target.isCompletelyInFrustum(this._frustumPlanes);
  13034. };
  13035. Camera.prototype.dispose = function () {
  13036. // Animations
  13037. this.getScene().stopAnimation(this);
  13038. // Remove from scene
  13039. this.getScene().removeCamera(this);
  13040. while (this._rigCameras.length > 0) {
  13041. this._rigCameras.pop().dispose();
  13042. }
  13043. // Postprocesses
  13044. for (var i = 0; i < this._postProcesses.length; ++i) {
  13045. this._postProcesses[i].dispose(this);
  13046. }
  13047. _super.prototype.dispose.call(this);
  13048. };
  13049. // ---- Camera rigs section ----
  13050. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13051. while (this._rigCameras.length > 0) {
  13052. this._rigCameras.pop().dispose();
  13053. }
  13054. this.cameraRigMode = mode;
  13055. this._cameraRigParams = {};
  13056. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13057. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13058. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13059. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13060. // create the rig cameras, unless none
  13061. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13062. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13063. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13064. }
  13065. switch (this.cameraRigMode) {
  13066. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13067. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13068. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13069. break;
  13070. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13071. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13072. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13073. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13074. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13075. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13076. break;
  13077. case Camera.RIG_MODE_VR:
  13078. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13079. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13080. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13081. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13082. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13083. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13084. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13085. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13086. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13087. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13088. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13089. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13090. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13091. if (metrics.compensateDistortion) {
  13092. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13093. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13094. }
  13095. break;
  13096. case Camera.RIG_MODE_WEBVR:
  13097. if (rigParams.vrDisplay) {
  13098. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13099. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13100. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13101. this._rigCameras[0].setCameraRigParameter("left", true);
  13102. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13103. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13104. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13105. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13106. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13107. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13108. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13109. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13110. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13111. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13112. }
  13113. break;
  13114. }
  13115. this._cascadePostProcessesToRigCams();
  13116. this.
  13117. update();
  13118. };
  13119. Camera.prototype._getVRProjectionMatrix = function () {
  13120. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13121. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13122. return this._projectionMatrix;
  13123. };
  13124. Camera.prototype._getWebVRProjectionMatrix = function () {
  13125. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  13126. //babylon compatible matrix
  13127. [8, 9, 10, 11].forEach(function (num) {
  13128. projectionArray[num] *= -1;
  13129. });
  13130. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  13131. return this._projectionMatrix;
  13132. };
  13133. //Can be used, but we'll use the free camera's view matrix calculation
  13134. Camera.prototype._getWebVRViewMatrix = function () {
  13135. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  13136. //babylon compatible matrix
  13137. [8, 9, 10, 11].forEach(function (num) {
  13138. projectionArray[num] *= -1;
  13139. });
  13140. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  13141. return this._webvrViewMatrix;
  13142. };
  13143. Camera.prototype.setCameraRigParameter = function (name, value) {
  13144. if (!this._cameraRigParams) {
  13145. this._cameraRigParams = {};
  13146. }
  13147. this._cameraRigParams[name] = value;
  13148. //provisionnally:
  13149. if (name === "interaxialDistance") {
  13150. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13151. }
  13152. };
  13153. /**
  13154. * needs to be overridden by children so sub has required properties to be copied
  13155. */
  13156. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13157. return null;
  13158. };
  13159. /**
  13160. * May need to be overridden by children
  13161. */
  13162. Camera.prototype._updateRigCameras = function () {
  13163. for (var i = 0; i < this._rigCameras.length; i++) {
  13164. this._rigCameras[i].minZ = this.minZ;
  13165. this._rigCameras[i].maxZ = this.maxZ;
  13166. this._rigCameras[i].fov = this.fov;
  13167. }
  13168. // only update viewport when ANAGLYPH
  13169. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13170. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13171. }
  13172. };
  13173. Camera.prototype._setupInputs = function () {
  13174. };
  13175. Camera.prototype.serialize = function () {
  13176. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13177. // Type
  13178. serializationObject.type = this.getTypeName();
  13179. // Parent
  13180. if (this.parent) {
  13181. serializationObject.parentId = this.parent.id;
  13182. }
  13183. if (this.inputs) {
  13184. this.inputs.serialize(serializationObject);
  13185. }
  13186. // Animations
  13187. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13188. serializationObject.ranges = this.serializeAnimationRanges();
  13189. return serializationObject;
  13190. };
  13191. Camera.prototype.getTypeName = function () {
  13192. return "Camera";
  13193. };
  13194. Camera.prototype.clone = function (name) {
  13195. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getTypeName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13196. };
  13197. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13198. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13199. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13200. switch (type) {
  13201. case "ArcRotateCamera":
  13202. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13203. case "DeviceOrientationCamera":
  13204. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13205. case "FollowCamera":
  13206. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13207. case "ArcFollowCamera":
  13208. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13209. case "GamepadCamera":
  13210. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13211. case "TouchCamera":
  13212. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13213. case "VirtualJoysticksCamera":
  13214. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13215. case "WebVRFreeCamera":
  13216. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13217. case "VRDeviceOrientationFreeCamera":
  13218. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13219. case "AnaglyphArcRotateCamera":
  13220. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13221. case "AnaglyphFreeCamera":
  13222. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13223. case "AnaglyphGamepadCamera":
  13224. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13225. case "AnaglyphUniversalCamera":
  13226. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13227. case "StereoscopicArcRotateCamera":
  13228. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13229. case "StereoscopicFreeCamera":
  13230. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13231. case "StereoscopicGamepadCamera":
  13232. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13233. case "StereoscopicUniversalCamera":
  13234. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13235. case "FreeCamera":
  13236. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13237. default:
  13238. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13239. }
  13240. };
  13241. Camera.Parse = function (parsedCamera, scene) {
  13242. var type = parsedCamera.type;
  13243. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13244. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13245. // Parent
  13246. if (parsedCamera.parentId) {
  13247. camera._waitingParentId = parsedCamera.parentId;
  13248. }
  13249. //If camera has an input manager, let it parse inputs settings
  13250. if (camera.inputs) {
  13251. camera.inputs.parse(parsedCamera);
  13252. camera._setupInputs();
  13253. }
  13254. // Target
  13255. if (parsedCamera.target) {
  13256. if (camera.setTarget) {
  13257. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13258. }
  13259. }
  13260. // Apply 3d rig, when found
  13261. if (parsedCamera.cameraRigMode) {
  13262. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13263. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13264. }
  13265. // Animations
  13266. if (parsedCamera.animations) {
  13267. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13268. var parsedAnimation = parsedCamera.animations[animationIndex];
  13269. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13270. }
  13271. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13272. }
  13273. if (parsedCamera.autoAnimate) {
  13274. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13275. }
  13276. return camera;
  13277. };
  13278. // Statics
  13279. Camera._PERSPECTIVE_CAMERA = 0;
  13280. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13281. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13282. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13283. Camera._RIG_MODE_NONE = 0;
  13284. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13285. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13286. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13287. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13288. Camera._RIG_MODE_VR = 20;
  13289. Camera._RIG_MODE_WEBVR = 21;
  13290. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13291. __decorate([
  13292. BABYLON.serializeAsVector3()
  13293. ], Camera.prototype, "position", void 0);
  13294. __decorate([
  13295. BABYLON.serializeAsVector3()
  13296. ], Camera.prototype, "upVector", void 0);
  13297. __decorate([
  13298. BABYLON.serialize()
  13299. ], Camera.prototype, "orthoLeft", void 0);
  13300. __decorate([
  13301. BABYLON.serialize()
  13302. ], Camera.prototype, "orthoRight", void 0);
  13303. __decorate([
  13304. BABYLON.serialize()
  13305. ], Camera.prototype, "orthoBottom", void 0);
  13306. __decorate([
  13307. BABYLON.serialize()
  13308. ], Camera.prototype, "orthoTop", void 0);
  13309. __decorate([
  13310. BABYLON.serialize()
  13311. ], Camera.prototype, "fov", void 0);
  13312. __decorate([
  13313. BABYLON.serialize()
  13314. ], Camera.prototype, "minZ", void 0);
  13315. __decorate([
  13316. BABYLON.serialize()
  13317. ], Camera.prototype, "maxZ", void 0);
  13318. __decorate([
  13319. BABYLON.serialize()
  13320. ], Camera.prototype, "inertia", void 0);
  13321. __decorate([
  13322. BABYLON.serialize()
  13323. ], Camera.prototype, "mode", void 0);
  13324. __decorate([
  13325. BABYLON.serialize()
  13326. ], Camera.prototype, "layerMask", void 0);
  13327. __decorate([
  13328. BABYLON.serialize()
  13329. ], Camera.prototype, "fovMode", void 0);
  13330. __decorate([
  13331. BABYLON.serialize()
  13332. ], Camera.prototype, "cameraRigMode", void 0);
  13333. __decorate([
  13334. BABYLON.serialize()
  13335. ], Camera.prototype, "interaxialDistance", void 0);
  13336. __decorate([
  13337. BABYLON.serialize()
  13338. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13339. return Camera;
  13340. }(BABYLON.Node));
  13341. BABYLON.Camera = Camera;
  13342. })(BABYLON || (BABYLON = {}));
  13343. var BABYLON;
  13344. (function (BABYLON) {
  13345. BABYLON.CameraInputTypes = {};
  13346. var CameraInputsManager = (function () {
  13347. function CameraInputsManager(camera) {
  13348. this.attached = {};
  13349. this.camera = camera;
  13350. this.checkInputs = function () { };
  13351. }
  13352. CameraInputsManager.prototype.add = function (input) {
  13353. var type = input.getSimpleName();
  13354. if (this.attached[type]) {
  13355. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13356. return;
  13357. }
  13358. this.attached[type] = input;
  13359. input.camera = this.camera;
  13360. //for checkInputs, we are dynamically creating a function
  13361. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13362. if (input.checkInputs) {
  13363. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13364. }
  13365. if (this.attachedElement) {
  13366. input.attachControl(this.attachedElement);
  13367. }
  13368. };
  13369. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13370. for (var cam in this.attached) {
  13371. var input = this.attached[cam];
  13372. if (input === inputToRemove) {
  13373. input.detachControl(this.attachedElement);
  13374. delete this.attached[cam];
  13375. this.rebuildInputCheck();
  13376. }
  13377. }
  13378. };
  13379. CameraInputsManager.prototype.removeByType = function (inputType) {
  13380. for (var cam in this.attached) {
  13381. var input = this.attached[cam];
  13382. if (input.getTypeName() === inputType) {
  13383. input.detachControl(this.attachedElement);
  13384. delete this.attached[cam];
  13385. this.rebuildInputCheck();
  13386. }
  13387. }
  13388. };
  13389. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13390. var current = this.checkInputs;
  13391. return function () {
  13392. current();
  13393. fn();
  13394. };
  13395. };
  13396. CameraInputsManager.prototype.attachInput = function (input) {
  13397. input.attachControl(this.attachedElement, this.noPreventDefault);
  13398. };
  13399. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13400. if (this.attachedElement) {
  13401. return;
  13402. }
  13403. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13404. this.attachedElement = element;
  13405. this.noPreventDefault = noPreventDefault;
  13406. for (var cam in this.attached) {
  13407. var input = this.attached[cam];
  13408. this.attached[cam].attachControl(element, noPreventDefault);
  13409. }
  13410. };
  13411. CameraInputsManager.prototype.detachElement = function (element) {
  13412. if (this.attachedElement !== element) {
  13413. return;
  13414. }
  13415. for (var cam in this.attached) {
  13416. var input = this.attached[cam];
  13417. this.attached[cam].detachControl(element);
  13418. }
  13419. this.attachedElement = null;
  13420. };
  13421. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13422. this.checkInputs = function () { };
  13423. for (var cam in this.attached) {
  13424. var input = this.attached[cam];
  13425. if (input.checkInputs) {
  13426. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13427. }
  13428. }
  13429. };
  13430. CameraInputsManager.prototype.clear = function () {
  13431. if (this.attachedElement) {
  13432. this.detachElement(this.attachedElement);
  13433. }
  13434. this.attached = {};
  13435. this.attachedElement = null;
  13436. this.checkInputs = function () { };
  13437. };
  13438. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13439. var inputs = {};
  13440. for (var cam in this.attached) {
  13441. var input = this.attached[cam];
  13442. var res = BABYLON.SerializationHelper.Serialize(input);
  13443. inputs[input.getTypeName()] = res;
  13444. }
  13445. serializedCamera.inputsmgr = inputs;
  13446. };
  13447. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13448. var parsedInputs = parsedCamera.inputsmgr;
  13449. if (parsedInputs) {
  13450. this.clear();
  13451. for (var n in parsedInputs) {
  13452. var construct = BABYLON.CameraInputTypes[n];
  13453. if (construct) {
  13454. var parsedinput = parsedInputs[n];
  13455. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13456. this.add(input);
  13457. }
  13458. }
  13459. }
  13460. else {
  13461. //2016-03-08 this part is for managing backward compatibility
  13462. for (var n in this.attached) {
  13463. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13464. if (construct) {
  13465. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13466. this.remove(this.attached[n]);
  13467. this.add(input);
  13468. }
  13469. }
  13470. }
  13471. };
  13472. return CameraInputsManager;
  13473. }());
  13474. BABYLON.CameraInputsManager = CameraInputsManager;
  13475. })(BABYLON || (BABYLON = {}));
  13476. var BABYLON;
  13477. (function (BABYLON) {
  13478. var FreeCameraMouseInput = (function () {
  13479. function FreeCameraMouseInput(touchEnabled) {
  13480. if (touchEnabled === void 0) { touchEnabled = true; }
  13481. this.touchEnabled = touchEnabled;
  13482. this.angularSensibility = 2000.0;
  13483. }
  13484. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13485. var _this = this;
  13486. var engine = this.camera.getEngine();
  13487. if (!this._pointerInput) {
  13488. this._pointerInput = function (p, s) {
  13489. var evt = p.event;
  13490. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13491. return;
  13492. }
  13493. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13494. try {
  13495. evt.srcElement.setPointerCapture(evt.pointerId);
  13496. }
  13497. catch (e) {
  13498. }
  13499. _this.previousPosition = {
  13500. x: evt.clientX,
  13501. y: evt.clientY
  13502. };
  13503. if (!noPreventDefault) {
  13504. evt.preventDefault();
  13505. element.focus();
  13506. }
  13507. }
  13508. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13509. try {
  13510. evt.srcElement.releasePointerCapture(evt.pointerId);
  13511. }
  13512. catch (e) {
  13513. }
  13514. _this.previousPosition = null;
  13515. if (!noPreventDefault) {
  13516. evt.preventDefault();
  13517. }
  13518. }
  13519. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13520. if (!_this.previousPosition || engine.isPointerLock) {
  13521. return;
  13522. }
  13523. var offsetX = evt.clientX - _this.previousPosition.x;
  13524. var offsetY = evt.clientY - _this.previousPosition.y;
  13525. if (_this.camera.getScene().useRightHandedSystem) {
  13526. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13527. }
  13528. else {
  13529. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13530. }
  13531. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13532. _this.previousPosition = {
  13533. x: evt.clientX,
  13534. y: evt.clientY
  13535. };
  13536. if (!noPreventDefault) {
  13537. evt.preventDefault();
  13538. }
  13539. }
  13540. };
  13541. }
  13542. this._onMouseMove = function (evt) {
  13543. if (!engine.isPointerLock) {
  13544. return;
  13545. }
  13546. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13547. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13548. if (_this.camera.getScene().useRightHandedSystem) {
  13549. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13550. }
  13551. else {
  13552. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13553. }
  13554. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13555. _this.previousPosition = null;
  13556. if (!noPreventDefault) {
  13557. evt.preventDefault();
  13558. }
  13559. };
  13560. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13561. element.addEventListener("mousemove", this._onMouseMove, false);
  13562. };
  13563. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13564. if (this._observer && element) {
  13565. this.camera.getScene().onPointerObservable.remove(this._observer);
  13566. element.removeEventListener("mousemove", this._onMouseMove);
  13567. this._observer = null;
  13568. this._onMouseMove = null;
  13569. this.previousPosition = null;
  13570. }
  13571. };
  13572. FreeCameraMouseInput.prototype.getTypeName = function () {
  13573. return "FreeCameraMouseInput";
  13574. };
  13575. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13576. return "mouse";
  13577. };
  13578. __decorate([
  13579. BABYLON.serialize()
  13580. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13581. return FreeCameraMouseInput;
  13582. }());
  13583. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13584. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13585. })(BABYLON || (BABYLON = {}));
  13586. var BABYLON;
  13587. (function (BABYLON) {
  13588. var FreeCameraKeyboardMoveInput = (function () {
  13589. function FreeCameraKeyboardMoveInput() {
  13590. this._keys = [];
  13591. this.keysUp = [38];
  13592. this.keysDown = [40];
  13593. this.keysLeft = [37];
  13594. this.keysRight = [39];
  13595. }
  13596. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13597. var _this = this;
  13598. if (!this._onKeyDown) {
  13599. element.tabIndex = 1;
  13600. this._onKeyDown = function (evt) {
  13601. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13602. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13603. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13604. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13605. var index = _this._keys.indexOf(evt.keyCode);
  13606. if (index === -1) {
  13607. _this._keys.push(evt.keyCode);
  13608. }
  13609. if (!noPreventDefault) {
  13610. evt.preventDefault();
  13611. }
  13612. }
  13613. };
  13614. this._onKeyUp = function (evt) {
  13615. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13616. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13617. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13618. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13619. var index = _this._keys.indexOf(evt.keyCode);
  13620. if (index >= 0) {
  13621. _this._keys.splice(index, 1);
  13622. }
  13623. if (!noPreventDefault) {
  13624. evt.preventDefault();
  13625. }
  13626. }
  13627. };
  13628. element.addEventListener("keydown", this._onKeyDown, false);
  13629. element.addEventListener("keyup", this._onKeyUp, false);
  13630. BABYLON.Tools.RegisterTopRootEvents([
  13631. { name: "blur", handler: this._onLostFocus }
  13632. ]);
  13633. }
  13634. };
  13635. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13636. if (this._onKeyDown) {
  13637. element.removeEventListener("keydown", this._onKeyDown);
  13638. element.removeEventListener("keyup", this._onKeyUp);
  13639. BABYLON.Tools.UnregisterTopRootEvents([
  13640. { name: "blur", handler: this._onLostFocus }
  13641. ]);
  13642. this._keys = [];
  13643. this._onKeyDown = null;
  13644. this._onKeyUp = null;
  13645. }
  13646. };
  13647. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  13648. if (this._onKeyDown) {
  13649. var camera = this.camera;
  13650. // Keyboard
  13651. for (var index = 0; index < this._keys.length; index++) {
  13652. var keyCode = this._keys[index];
  13653. var speed = camera._computeLocalCameraSpeed();
  13654. if (this.keysLeft.indexOf(keyCode) !== -1) {
  13655. camera._localDirection.copyFromFloats(-speed, 0, 0);
  13656. }
  13657. else if (this.keysUp.indexOf(keyCode) !== -1) {
  13658. camera._localDirection.copyFromFloats(0, 0, speed);
  13659. }
  13660. else if (this.keysRight.indexOf(keyCode) !== -1) {
  13661. camera._localDirection.copyFromFloats(speed, 0, 0);
  13662. }
  13663. else if (this.keysDown.indexOf(keyCode) !== -1) {
  13664. camera._localDirection.copyFromFloats(0, 0, -speed);
  13665. }
  13666. if (camera.getScene().useRightHandedSystem) {
  13667. camera._localDirection.z *= -1;
  13668. }
  13669. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  13670. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  13671. camera.cameraDirection.addInPlace(camera._transformedDirection);
  13672. }
  13673. }
  13674. };
  13675. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  13676. return "FreeCameraKeyboardMoveInput";
  13677. };
  13678. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  13679. this._keys = [];
  13680. };
  13681. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  13682. return "keyboard";
  13683. };
  13684. __decorate([
  13685. BABYLON.serialize()
  13686. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  13687. __decorate([
  13688. BABYLON.serialize()
  13689. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  13690. __decorate([
  13691. BABYLON.serialize()
  13692. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  13693. __decorate([
  13694. BABYLON.serialize()
  13695. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  13696. return FreeCameraKeyboardMoveInput;
  13697. }());
  13698. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  13699. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  13700. })(BABYLON || (BABYLON = {}));
  13701. var BABYLON;
  13702. (function (BABYLON) {
  13703. var FreeCameraTouchInput = (function () {
  13704. function FreeCameraTouchInput() {
  13705. this._offsetX = null;
  13706. this._offsetY = null;
  13707. this._pointerCount = 0;
  13708. this._pointerPressed = [];
  13709. this.touchAngularSensibility = 200000.0;
  13710. this.touchMoveSensibility = 250.0;
  13711. }
  13712. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  13713. var _this = this;
  13714. var previousPosition;
  13715. if (this._pointerInput === undefined) {
  13716. this._onLostFocus = function (evt) {
  13717. _this._offsetX = null;
  13718. _this._offsetY = null;
  13719. };
  13720. this._pointerInput = function (p, s) {
  13721. var evt = p.event;
  13722. if (evt.pointerType === "mouse") {
  13723. return;
  13724. }
  13725. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13726. if (!noPreventDefault) {
  13727. evt.preventDefault();
  13728. }
  13729. _this._pointerPressed.push(evt.pointerId);
  13730. if (_this._pointerPressed.length !== 1) {
  13731. return;
  13732. }
  13733. previousPosition = {
  13734. x: evt.clientX,
  13735. y: evt.clientY
  13736. };
  13737. }
  13738. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13739. if (!noPreventDefault) {
  13740. evt.preventDefault();
  13741. }
  13742. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13743. if (index === -1) {
  13744. return;
  13745. }
  13746. _this._pointerPressed.splice(index, 1);
  13747. if (index != 0) {
  13748. return;
  13749. }
  13750. previousPosition = null;
  13751. _this._offsetX = null;
  13752. _this._offsetY = null;
  13753. }
  13754. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13755. if (!noPreventDefault) {
  13756. evt.preventDefault();
  13757. }
  13758. if (!previousPosition) {
  13759. return;
  13760. }
  13761. var index = _this._pointerPressed.indexOf(evt.pointerId);
  13762. if (index != 0) {
  13763. return;
  13764. }
  13765. _this._offsetX = evt.clientX - previousPosition.x;
  13766. _this._offsetY = -(evt.clientY - previousPosition.y);
  13767. }
  13768. };
  13769. }
  13770. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13771. element.addEventListener("blur", this._onLostFocus);
  13772. };
  13773. FreeCameraTouchInput.prototype.detachControl = function (element) {
  13774. if (this._pointerInput && element) {
  13775. this.camera.getScene().onPointerObservable.remove(this._observer);
  13776. this._observer = null;
  13777. element.removeEventListener("blur", this._onLostFocus);
  13778. this._onLostFocus = null;
  13779. this._pointerPressed = [];
  13780. this._offsetX = null;
  13781. this._offsetY = null;
  13782. this._pointerCount = 0;
  13783. }
  13784. };
  13785. FreeCameraTouchInput.prototype.checkInputs = function () {
  13786. if (this._offsetX) {
  13787. var camera = this.camera;
  13788. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  13789. if (this._pointerPressed.length > 1) {
  13790. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  13791. }
  13792. else {
  13793. var speed = camera._computeLocalCameraSpeed();
  13794. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  13795. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  13796. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  13797. }
  13798. }
  13799. };
  13800. FreeCameraTouchInput.prototype.getTypeName = function () {
  13801. return "FreeCameraTouchInput";
  13802. };
  13803. FreeCameraTouchInput.prototype.getSimpleName = function () {
  13804. return "touch";
  13805. };
  13806. __decorate([
  13807. BABYLON.serialize()
  13808. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  13809. __decorate([
  13810. BABYLON.serialize()
  13811. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  13812. return FreeCameraTouchInput;
  13813. }());
  13814. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  13815. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  13816. })(BABYLON || (BABYLON = {}));
  13817. var BABYLON;
  13818. (function (BABYLON) {
  13819. var FreeCameraDeviceOrientationInput = (function () {
  13820. function FreeCameraDeviceOrientationInput() {
  13821. var _this = this;
  13822. this._screenOrientationAngle = 0;
  13823. this._screenQuaternion = new BABYLON.Quaternion();
  13824. this._alpha = 0;
  13825. this._beta = 0;
  13826. this._gamma = 0;
  13827. this._orientationChanged = function () {
  13828. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  13829. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  13830. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  13831. };
  13832. this._deviceOrientation = function (evt) {
  13833. _this._alpha = evt.alpha;
  13834. _this._beta = evt.beta;
  13835. _this._gamma = evt.gamma;
  13836. };
  13837. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  13838. this._orientationChanged();
  13839. }
  13840. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  13841. get: function () {
  13842. return this._camera;
  13843. },
  13844. set: function (camera) {
  13845. this._camera = camera;
  13846. if (!this._camera.rotationQuaternion)
  13847. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  13848. },
  13849. enumerable: true,
  13850. configurable: true
  13851. });
  13852. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  13853. window.addEventListener("orientationchange", this._orientationChanged);
  13854. window.addEventListener("deviceorientation", this._deviceOrientation);
  13855. //In certain cases, the attach control is called AFTER orientation was changed,
  13856. //So this is needed.
  13857. this._orientationChanged();
  13858. };
  13859. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  13860. window.removeEventListener("orientationchange", this._orientationChanged);
  13861. window.removeEventListener("deviceorientation", this._deviceOrientation);
  13862. };
  13863. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  13864. //if no device orientation provided, don't update the rotation.
  13865. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  13866. if (!this._alpha)
  13867. return;
  13868. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  13869. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  13870. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  13871. //Mirror on XY Plane
  13872. this._camera.rotationQuaternion.z *= -1;
  13873. this._camera.rotationQuaternion.w *= -1;
  13874. };
  13875. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  13876. return "FreeCameraDeviceOrientationInput";
  13877. };
  13878. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  13879. return "deviceOrientation";
  13880. };
  13881. return FreeCameraDeviceOrientationInput;
  13882. }());
  13883. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  13884. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  13885. })(BABYLON || (BABYLON = {}));
  13886. var BABYLON;
  13887. (function (BABYLON) {
  13888. var FreeCameraGamepadInput = (function () {
  13889. function FreeCameraGamepadInput() {
  13890. this.gamepadAngularSensibility = 200;
  13891. this.gamepadMoveSensibility = 40;
  13892. }
  13893. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  13894. var _this = this;
  13895. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  13896. };
  13897. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  13898. if (this._gamepads) {
  13899. this._gamepads.dispose();
  13900. }
  13901. this.gamepad = null;
  13902. };
  13903. FreeCameraGamepadInput.prototype.checkInputs = function () {
  13904. if (this.gamepad) {
  13905. var camera = this.camera;
  13906. var LSValues = this.gamepad.leftStick;
  13907. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  13908. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  13909. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  13910. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  13911. var RSValues = this.gamepad.rightStick;
  13912. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  13913. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  13914. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  13915. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  13916. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  13917. var speed = camera._computeLocalCameraSpeed() * 50.0;
  13918. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  13919. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  13920. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  13921. }
  13922. };
  13923. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  13924. // Only the first gamepad can control the camera
  13925. if (gamepad.index === 0) {
  13926. this.gamepad = gamepad;
  13927. }
  13928. };
  13929. FreeCameraGamepadInput.prototype.getTypeName = function () {
  13930. return "FreeCameraGamepadInput";
  13931. };
  13932. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  13933. return "gamepad";
  13934. };
  13935. __decorate([
  13936. BABYLON.serialize()
  13937. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  13938. __decorate([
  13939. BABYLON.serialize()
  13940. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  13941. return FreeCameraGamepadInput;
  13942. }());
  13943. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  13944. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  13945. })(BABYLON || (BABYLON = {}));
  13946. var BABYLON;
  13947. (function (BABYLON) {
  13948. var ArcRotateCameraKeyboardMoveInput = (function () {
  13949. function ArcRotateCameraKeyboardMoveInput() {
  13950. this._keys = [];
  13951. this.keysUp = [38];
  13952. this.keysDown = [40];
  13953. this.keysLeft = [37];
  13954. this.keysRight = [39];
  13955. }
  13956. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13957. var _this = this;
  13958. element.tabIndex = 1;
  13959. this._onKeyDown = function (evt) {
  13960. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13961. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13962. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13963. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13964. var index = _this._keys.indexOf(evt.keyCode);
  13965. if (index === -1) {
  13966. _this._keys.push(evt.keyCode);
  13967. }
  13968. if (evt.preventDefault) {
  13969. if (!noPreventDefault) {
  13970. evt.preventDefault();
  13971. }
  13972. }
  13973. }
  13974. };
  13975. this._onKeyUp = function (evt) {
  13976. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13977. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13978. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13979. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13980. var index = _this._keys.indexOf(evt.keyCode);
  13981. if (index >= 0) {
  13982. _this._keys.splice(index, 1);
  13983. }
  13984. if (evt.preventDefault) {
  13985. if (!noPreventDefault) {
  13986. evt.preventDefault();
  13987. }
  13988. }
  13989. }
  13990. };
  13991. this._onLostFocus = function () {
  13992. _this._keys = [];
  13993. };
  13994. element.addEventListener("keydown", this._onKeyDown, false);
  13995. element.addEventListener("keyup", this._onKeyUp, false);
  13996. BABYLON.Tools.RegisterTopRootEvents([
  13997. { name: "blur", handler: this._onLostFocus }
  13998. ]);
  13999. };
  14000. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14001. if (element) {
  14002. element.removeEventListener("keydown", this._onKeyDown);
  14003. element.removeEventListener("keyup", this._onKeyUp);
  14004. }
  14005. BABYLON.Tools.UnregisterTopRootEvents([
  14006. { name: "blur", handler: this._onLostFocus }
  14007. ]);
  14008. this._keys = [];
  14009. this._onKeyDown = null;
  14010. this._onKeyUp = null;
  14011. this._onLostFocus = null;
  14012. };
  14013. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14014. if (this._onKeyDown) {
  14015. var camera = this.camera;
  14016. for (var index = 0; index < this._keys.length; index++) {
  14017. var keyCode = this._keys[index];
  14018. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14019. camera.inertialAlphaOffset -= 0.01;
  14020. }
  14021. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14022. camera.inertialBetaOffset -= 0.01;
  14023. }
  14024. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14025. camera.inertialAlphaOffset += 0.01;
  14026. }
  14027. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14028. camera.inertialBetaOffset += 0.01;
  14029. }
  14030. }
  14031. }
  14032. };
  14033. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14034. return "ArcRotateCameraKeyboardMoveInput";
  14035. };
  14036. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14037. return "keyboard";
  14038. };
  14039. __decorate([
  14040. BABYLON.serialize()
  14041. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14042. __decorate([
  14043. BABYLON.serialize()
  14044. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14045. __decorate([
  14046. BABYLON.serialize()
  14047. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14048. __decorate([
  14049. BABYLON.serialize()
  14050. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14051. return ArcRotateCameraKeyboardMoveInput;
  14052. }());
  14053. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14054. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14055. })(BABYLON || (BABYLON = {}));
  14056. var BABYLON;
  14057. (function (BABYLON) {
  14058. var ArcRotateCameraMouseWheelInput = (function () {
  14059. function ArcRotateCameraMouseWheelInput() {
  14060. this.wheelPrecision = 3.0;
  14061. }
  14062. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14063. var _this = this;
  14064. this._wheel = function (p, s) {
  14065. //sanity check - this should be a PointerWheel event.
  14066. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14067. return;
  14068. var event = p.event;
  14069. var delta = 0;
  14070. if (event.wheelDelta) {
  14071. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14072. }
  14073. else if (event.detail) {
  14074. delta = -event.detail / _this.wheelPrecision;
  14075. }
  14076. if (delta)
  14077. _this.camera.inertialRadiusOffset += delta;
  14078. if (event.preventDefault) {
  14079. if (!noPreventDefault) {
  14080. event.preventDefault();
  14081. }
  14082. }
  14083. };
  14084. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14085. };
  14086. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14087. if (this._observer && element) {
  14088. this.camera.getScene().onPointerObservable.remove(this._observer);
  14089. this._observer = null;
  14090. this._wheel = null;
  14091. }
  14092. };
  14093. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14094. return "ArcRotateCameraMouseWheelInput";
  14095. };
  14096. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14097. return "mousewheel";
  14098. };
  14099. __decorate([
  14100. BABYLON.serialize()
  14101. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14102. return ArcRotateCameraMouseWheelInput;
  14103. }());
  14104. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14105. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14106. })(BABYLON || (BABYLON = {}));
  14107. var BABYLON;
  14108. (function (BABYLON) {
  14109. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14110. var ArcRotateCameraPointersInput = (function () {
  14111. function ArcRotateCameraPointersInput() {
  14112. this.angularSensibilityX = 1000.0;
  14113. this.angularSensibilityY = 1000.0;
  14114. this.pinchPrecision = 6.0;
  14115. this.panningSensibility = 50.0;
  14116. this._isPanClick = false;
  14117. this.pinchInwards = true;
  14118. }
  14119. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14120. var _this = this;
  14121. var engine = this.camera.getEngine();
  14122. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14123. var pointA, pointB;
  14124. var previousPinchDistance = 0;
  14125. this._pointerInput = function (p, s) {
  14126. var evt = p.event;
  14127. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14128. try {
  14129. evt.srcElement.setPointerCapture(evt.pointerId);
  14130. }
  14131. catch (e) {
  14132. }
  14133. // Manage panning with pan button click
  14134. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14135. // manage pointers
  14136. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14137. if (pointA === undefined) {
  14138. pointA = cacheSoloPointer;
  14139. }
  14140. else if (pointB === undefined) {
  14141. pointB = cacheSoloPointer;
  14142. }
  14143. if (!noPreventDefault) {
  14144. evt.preventDefault();
  14145. element.focus();
  14146. }
  14147. }
  14148. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14149. try {
  14150. evt.srcElement.releasePointerCapture(evt.pointerId);
  14151. }
  14152. catch (e) {
  14153. }
  14154. cacheSoloPointer = null;
  14155. previousPinchDistance = 0;
  14156. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14157. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14158. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14159. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14160. pointA = pointB = undefined;
  14161. if (!noPreventDefault) {
  14162. evt.preventDefault();
  14163. }
  14164. }
  14165. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14166. if (!noPreventDefault) {
  14167. evt.preventDefault();
  14168. }
  14169. // One button down
  14170. if (pointA && pointB === undefined) {
  14171. if (_this.panningSensibility !== 0 &&
  14172. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14173. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14174. _this.camera
  14175. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14176. _this.camera
  14177. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14178. }
  14179. else {
  14180. var offsetX = evt.clientX - cacheSoloPointer.x;
  14181. var offsetY = evt.clientY - cacheSoloPointer.y;
  14182. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14183. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14184. }
  14185. cacheSoloPointer.x = evt.clientX;
  14186. cacheSoloPointer.y = evt.clientY;
  14187. }
  14188. else if (pointA && pointB) {
  14189. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14190. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14191. ed.x = evt.clientX;
  14192. ed.y = evt.clientY;
  14193. var direction = _this.pinchInwards ? 1 : -1;
  14194. var distX = pointA.x - pointB.x;
  14195. var distY = pointA.y - pointB.y;
  14196. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14197. if (previousPinchDistance === 0) {
  14198. previousPinchDistance = pinchSquaredDistance;
  14199. return;
  14200. }
  14201. if (pinchSquaredDistance !== previousPinchDistance) {
  14202. _this.camera
  14203. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14204. (_this.pinchPrecision *
  14205. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14206. direction);
  14207. previousPinchDistance = pinchSquaredDistance;
  14208. }
  14209. }
  14210. }
  14211. };
  14212. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14213. this._onContextMenu = function (evt) {
  14214. evt.preventDefault();
  14215. };
  14216. if (!this.camera._useCtrlForPanning) {
  14217. element.addEventListener("contextmenu", this._onContextMenu, false);
  14218. }
  14219. this._onLostFocus = function () {
  14220. //this._keys = [];
  14221. pointA = pointB = undefined;
  14222. previousPinchDistance = 0;
  14223. cacheSoloPointer = null;
  14224. };
  14225. this._onMouseMove = function (evt) {
  14226. if (!engine.isPointerLock) {
  14227. return;
  14228. }
  14229. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14230. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14231. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14232. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14233. if (!noPreventDefault) {
  14234. evt.preventDefault();
  14235. }
  14236. };
  14237. this._onGestureStart = function (e) {
  14238. if (window.MSGesture === undefined) {
  14239. return;
  14240. }
  14241. if (!_this._MSGestureHandler) {
  14242. _this._MSGestureHandler = new MSGesture();
  14243. _this._MSGestureHandler.target = element;
  14244. }
  14245. _this._MSGestureHandler.addPointer(e.pointerId);
  14246. };
  14247. this._onGesture = function (e) {
  14248. _this.camera.radius *= e.scale;
  14249. if (e.preventDefault) {
  14250. if (!noPreventDefault) {
  14251. e.stopPropagation();
  14252. e.preventDefault();
  14253. }
  14254. }
  14255. };
  14256. element.addEventListener("mousemove", this._onMouseMove, false);
  14257. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14258. element.addEventListener("MSGestureChange", this._onGesture, false);
  14259. element.addEventListener("keydown", this._onKeyDown, false);
  14260. element.addEventListener("keyup", this._onKeyUp, false);
  14261. BABYLON.Tools.RegisterTopRootEvents([
  14262. { name: "blur", handler: this._onLostFocus }
  14263. ]);
  14264. };
  14265. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14266. if (element && this._observer) {
  14267. this.camera.getScene().onPointerObservable.remove(this._observer);
  14268. this._observer = null;
  14269. element.removeEventListener("contextmenu", this._onContextMenu);
  14270. element.removeEventListener("mousemove", this._onMouseMove);
  14271. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14272. element.removeEventListener("MSGestureChange", this._onGesture);
  14273. element.removeEventListener("keydown", this._onKeyDown);
  14274. element.removeEventListener("keyup", this._onKeyUp);
  14275. this._isPanClick = false;
  14276. this.pinchInwards = true;
  14277. this._onKeyDown = null;
  14278. this._onKeyUp = null;
  14279. this._onMouseMove = null;
  14280. this._onGestureStart = null;
  14281. this._onGesture = null;
  14282. this._MSGestureHandler = null;
  14283. this._onLostFocus = null;
  14284. this._onContextMenu = null;
  14285. }
  14286. BABYLON.Tools.UnregisterTopRootEvents([
  14287. { name: "blur", handler: this._onLostFocus }
  14288. ]);
  14289. };
  14290. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14291. return "ArcRotateCameraPointersInput";
  14292. };
  14293. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14294. return "pointers";
  14295. };
  14296. __decorate([
  14297. BABYLON.serialize()
  14298. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14299. __decorate([
  14300. BABYLON.serialize()
  14301. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14302. __decorate([
  14303. BABYLON.serialize()
  14304. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14305. __decorate([
  14306. BABYLON.serialize()
  14307. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14308. return ArcRotateCameraPointersInput;
  14309. }());
  14310. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14311. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14312. })(BABYLON || (BABYLON = {}));
  14313. var BABYLON;
  14314. (function (BABYLON) {
  14315. var ArcRotateCameraGamepadInput = (function () {
  14316. function ArcRotateCameraGamepadInput() {
  14317. this.gamepadRotationSensibility = 80;
  14318. this.gamepadMoveSensibility = 40;
  14319. }
  14320. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14321. var _this = this;
  14322. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14323. };
  14324. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14325. if (this._gamepads) {
  14326. this._gamepads.dispose();
  14327. }
  14328. this.gamepad = null;
  14329. };
  14330. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14331. if (this.gamepad) {
  14332. var camera = this.camera;
  14333. var RSValues = this.gamepad.rightStick;
  14334. if (RSValues.x != 0) {
  14335. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14336. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14337. camera.inertialAlphaOffset += normalizedRX;
  14338. }
  14339. }
  14340. if (RSValues.y != 0) {
  14341. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14342. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14343. camera.inertialBetaOffset += normalizedRY;
  14344. }
  14345. }
  14346. var LSValues = this.gamepad.leftStick;
  14347. if (LSValues.y != 0) {
  14348. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14349. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14350. this.camera.inertialRadiusOffset -= normalizedLY;
  14351. }
  14352. }
  14353. }
  14354. };
  14355. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14356. // Only the first gamepad can control the camera
  14357. if (gamepad.index === 0) {
  14358. this.gamepad = gamepad;
  14359. }
  14360. };
  14361. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14362. return "ArcRotateCameraGamepadInput";
  14363. };
  14364. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14365. return "gamepad";
  14366. };
  14367. __decorate([
  14368. BABYLON.serialize()
  14369. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14370. __decorate([
  14371. BABYLON.serialize()
  14372. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14373. return ArcRotateCameraGamepadInput;
  14374. }());
  14375. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14376. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14377. })(BABYLON || (BABYLON = {}));
  14378. var BABYLON;
  14379. (function (BABYLON) {
  14380. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14381. function ArcRotateCameraVRDeviceOrientationInput() {
  14382. this.alphaCorrection = 1;
  14383. this.betaCorrection = 1;
  14384. this.gammaCorrection = 1;
  14385. this._alpha = 0;
  14386. this._beta = 0;
  14387. this._gamma = 0;
  14388. this._dirty = false;
  14389. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14390. }
  14391. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14392. this.camera.attachControl(element, noPreventDefault);
  14393. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14394. };
  14395. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14396. var camera = this.camera;
  14397. this._alpha = +evt.alpha | 0;
  14398. this._beta = +evt.beta | 0;
  14399. this._gamma = +evt.gamma | 0;
  14400. this._dirty = true;
  14401. };
  14402. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14403. if (this._dirty) {
  14404. this._dirty = false;
  14405. if (this._gamma < 0) {
  14406. this._gamma = 180 + this._gamma;
  14407. }
  14408. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14409. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14410. }
  14411. };
  14412. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14413. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14414. };
  14415. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14416. return "ArcRotateCameraVRDeviceOrientationInput";
  14417. };
  14418. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14419. return "VRDeviceOrientation";
  14420. };
  14421. return ArcRotateCameraVRDeviceOrientationInput;
  14422. }());
  14423. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14424. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14425. })(BABYLON || (BABYLON = {}));
  14426. var BABYLON;
  14427. (function (BABYLON) {
  14428. var TargetCamera = (function (_super) {
  14429. __extends(TargetCamera, _super);
  14430. function TargetCamera(name, position, scene) {
  14431. _super.call(this, name, position, scene);
  14432. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14433. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14434. this.rotation = new BABYLON.Vector3(0, 0, 0);
  14435. this.speed = 2.0;
  14436. this.noRotationConstraint = false;
  14437. this.lockedTarget = null;
  14438. this._currentTarget = BABYLON.Vector3.Zero();
  14439. this._viewMatrix = BABYLON.Matrix.Zero();
  14440. this._camMatrix = BABYLON.Matrix.Zero();
  14441. this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14442. this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14443. this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14444. this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14445. this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14446. this._lookAtTemp = BABYLON.Matrix.Zero();
  14447. this._tempMatrix = BABYLON.Matrix.Zero();
  14448. }
  14449. TargetCamera.prototype.getFrontPosition = function (distance) {
  14450. var direction = this.getTarget().subtract(this.position);
  14451. direction.normalize();
  14452. direction.scaleInPlace(distance);
  14453. return this.globalPosition.add(direction);
  14454. };
  14455. TargetCamera.prototype._getLockedTargetPosition = function () {
  14456. if (!this.lockedTarget) {
  14457. return null;
  14458. }
  14459. return this.lockedTarget.position || this.lockedTarget;
  14460. };
  14461. // Cache
  14462. TargetCamera.prototype._initCache = function () {
  14463. _super.prototype._initCache.call(this);
  14464. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14465. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14466. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14467. };
  14468. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14469. if (!ignoreParentClass) {
  14470. _super.prototype._updateCache.call(this);
  14471. }
  14472. var lockedTargetPosition = this._getLockedTargetPosition();
  14473. if (!lockedTargetPosition) {
  14474. this._cache.lockedTarget = null;
  14475. }
  14476. else {
  14477. if (!this._cache.lockedTarget) {
  14478. this._cache.lockedTarget = lockedTargetPosition.clone();
  14479. }
  14480. else {
  14481. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14482. }
  14483. }
  14484. this._cache.rotation.copyFrom(this.rotation);
  14485. if (this.rotationQuaternion)
  14486. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14487. };
  14488. // Synchronized
  14489. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14490. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14491. return false;
  14492. }
  14493. var lockedTargetPosition = this._getLockedTargetPosition();
  14494. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14495. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14496. };
  14497. // Methods
  14498. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14499. var engine = this.getEngine();
  14500. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14501. };
  14502. // Target
  14503. TargetCamera.prototype.setTarget = function (target) {
  14504. this.upVector.normalize();
  14505. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14506. this._camMatrix.invert();
  14507. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14508. var vDir = target.subtract(this.position);
  14509. if (vDir.x >= 0.0) {
  14510. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14511. }
  14512. else {
  14513. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14514. }
  14515. this.rotation.z = 0;
  14516. if (isNaN(this.rotation.x)) {
  14517. this.rotation.x = 0;
  14518. }
  14519. if (isNaN(this.rotation.y)) {
  14520. this.rotation.y = 0;
  14521. }
  14522. if (isNaN(this.rotation.z)) {
  14523. this.rotation.z = 0;
  14524. }
  14525. if (this.rotationQuaternion) {
  14526. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14527. }
  14528. };
  14529. TargetCamera.prototype.getTarget = function () {
  14530. return this._currentTarget;
  14531. };
  14532. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14533. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14534. };
  14535. TargetCamera.prototype._updatePosition = function () {
  14536. this.position.addInPlace(this.cameraDirection);
  14537. };
  14538. TargetCamera.prototype._checkInputs = function () {
  14539. var needToMove = this._decideIfNeedsToMove();
  14540. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14541. // Move
  14542. if (needToMove) {
  14543. this._updatePosition();
  14544. }
  14545. // Rotate
  14546. if (needToRotate) {
  14547. this.rotation.x += this.cameraRotation.x;
  14548. this.rotation.y += this.cameraRotation.y;
  14549. if (!this.noRotationConstraint) {
  14550. var limit = (Math.PI / 2) * 0.95;
  14551. if (this.rotation.x > limit)
  14552. this.rotation.x = limit;
  14553. if (this.rotation.x < -limit)
  14554. this.rotation.x = -limit;
  14555. }
  14556. }
  14557. // Inertia
  14558. if (needToMove) {
  14559. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14560. this.cameraDirection.x = 0;
  14561. }
  14562. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14563. this.cameraDirection.y = 0;
  14564. }
  14565. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14566. this.cameraDirection.z = 0;
  14567. }
  14568. this.cameraDirection.scaleInPlace(this.inertia);
  14569. }
  14570. if (needToRotate) {
  14571. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14572. this.cameraRotation.x = 0;
  14573. }
  14574. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14575. this.cameraRotation.y = 0;
  14576. }
  14577. this.cameraRotation.scaleInPlace(this.inertia);
  14578. }
  14579. _super.prototype._checkInputs.call(this);
  14580. };
  14581. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14582. if (this.rotationQuaternion) {
  14583. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14584. //update the up vector!
  14585. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14586. }
  14587. else {
  14588. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14589. }
  14590. };
  14591. TargetCamera.prototype._getViewMatrix = function () {
  14592. if (!this.lockedTarget) {
  14593. // Compute
  14594. this._updateCameraRotationMatrix();
  14595. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14596. // Computing target and final matrix
  14597. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14598. }
  14599. else {
  14600. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14601. }
  14602. if (this.getScene().useRightHandedSystem) {
  14603. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14604. }
  14605. else {
  14606. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14607. }
  14608. return this._viewMatrix;
  14609. };
  14610. /**
  14611. * @override
  14612. * Override Camera.createRigCamera
  14613. */
  14614. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14615. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14616. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14617. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14618. if (!this.rotationQuaternion) {
  14619. this.rotationQuaternion = new BABYLON.Quaternion();
  14620. }
  14621. rigCamera._cameraRigParams = {};
  14622. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  14623. }
  14624. return rigCamera;
  14625. }
  14626. return null;
  14627. };
  14628. /**
  14629. * @override
  14630. * Override Camera._updateRigCameras
  14631. */
  14632. TargetCamera.prototype._updateRigCameras = function () {
  14633. var camLeft = this._rigCameras[0];
  14634. var camRight = this._rigCameras[1];
  14635. switch (this.cameraRigMode) {
  14636. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14637. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14638. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14639. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14640. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  14641. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  14642. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  14643. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  14644. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  14645. camLeft.setTarget(this.getTarget());
  14646. camRight.setTarget(this.getTarget());
  14647. break;
  14648. case BABYLON.Camera.RIG_MODE_VR:
  14649. case BABYLON.Camera.RIG_MODE_WEBVR:
  14650. if (camLeft.rotationQuaternion) {
  14651. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14652. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14653. }
  14654. else {
  14655. camLeft.rotation.copyFrom(this.rotation);
  14656. camRight.rotation.copyFrom(this.rotation);
  14657. }
  14658. camLeft.position.copyFrom(this.position);
  14659. camRight.position.copyFrom(this.position);
  14660. break;
  14661. }
  14662. _super.prototype._updateRigCameras.call(this);
  14663. };
  14664. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  14665. if (!this._rigCamTransformMatrix) {
  14666. this._rigCamTransformMatrix = new BABYLON.Matrix();
  14667. }
  14668. var target = this.getTarget();
  14669. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  14670. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  14671. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  14672. };
  14673. TargetCamera.prototype.getTypeName = function () {
  14674. return "TargetCamera";
  14675. };
  14676. __decorate([
  14677. BABYLON.serializeAsVector3()
  14678. ], TargetCamera.prototype, "rotation", void 0);
  14679. __decorate([
  14680. BABYLON.serialize()
  14681. ], TargetCamera.prototype, "speed", void 0);
  14682. __decorate([
  14683. BABYLON.serializeAsMeshReference("lockedTargetId")
  14684. ], TargetCamera.prototype, "lockedTarget", void 0);
  14685. return TargetCamera;
  14686. }(BABYLON.Camera));
  14687. BABYLON.TargetCamera = TargetCamera;
  14688. })(BABYLON || (BABYLON = {}));
  14689. var BABYLON;
  14690. (function (BABYLON) {
  14691. var FreeCamera = (function (_super) {
  14692. __extends(FreeCamera, _super);
  14693. function FreeCamera(name, position, scene) {
  14694. var _this = this;
  14695. _super.call(this, name, position, scene);
  14696. this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  14697. this.checkCollisions = false;
  14698. this.applyGravity = false;
  14699. this._collider = new BABYLON.Collider();
  14700. this._needMoveForGravity = false;
  14701. this._oldPosition = BABYLON.Vector3.Zero();
  14702. this._diffPosition = BABYLON.Vector3.Zero();
  14703. this._newPosition = BABYLON.Vector3.Zero();
  14704. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  14705. if (collidedMesh === void 0) { collidedMesh = null; }
  14706. //TODO move this to the collision coordinator!
  14707. if (_this.getScene().workerCollisions)
  14708. newPosition.multiplyInPlace(_this._collider.radius);
  14709. var updatePosition = function (newPos) {
  14710. _this._newPosition.copyFrom(newPos);
  14711. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  14712. var oldPosition = _this.position.clone();
  14713. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  14714. _this.position.addInPlace(_this._diffPosition);
  14715. if (_this.onCollide && collidedMesh) {
  14716. _this.onCollide(collidedMesh);
  14717. }
  14718. }
  14719. };
  14720. updatePosition(newPosition);
  14721. };
  14722. this.inputs = new BABYLON.FreeCameraInputsManager(this);
  14723. this.inputs.addKeyboard().addMouse();
  14724. }
  14725. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  14726. //-- begin properties for backward compatibility for inputs
  14727. get: function () {
  14728. var mouse = this.inputs.attached["mouse"];
  14729. if (mouse)
  14730. return mouse.angularSensibility;
  14731. },
  14732. set: function (value) {
  14733. var mouse = this.inputs.attached["mouse"];
  14734. if (mouse)
  14735. mouse.angularSensibility = value;
  14736. },
  14737. enumerable: true,
  14738. configurable: true
  14739. });
  14740. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  14741. get: function () {
  14742. var keyboard = this.inputs.attached["keyboard"];
  14743. if (keyboard)
  14744. return keyboard.keysUp;
  14745. },
  14746. set: function (value) {
  14747. var keyboard = this.inputs.attached["keyboard"];
  14748. if (keyboard)
  14749. keyboard.keysUp = value;
  14750. },
  14751. enumerable: true,
  14752. configurable: true
  14753. });
  14754. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  14755. get: function () {
  14756. var keyboard = this.inputs.attached["keyboard"];
  14757. if (keyboard)
  14758. return keyboard.keysDown;
  14759. },
  14760. set: function (value) {
  14761. var keyboard = this.inputs.attached["keyboard"];
  14762. if (keyboard)
  14763. keyboard.keysDown = value;
  14764. },
  14765. enumerable: true,
  14766. configurable: true
  14767. });
  14768. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  14769. get: function () {
  14770. var keyboard = this.inputs.attached["keyboard"];
  14771. if (keyboard)
  14772. return keyboard.keysLeft;
  14773. },
  14774. set: function (value) {
  14775. var keyboard = this.inputs.attached["keyboard"];
  14776. if (keyboard)
  14777. keyboard.keysLeft = value;
  14778. },
  14779. enumerable: true,
  14780. configurable: true
  14781. });
  14782. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  14783. get: function () {
  14784. var keyboard = this.inputs.attached["keyboard"];
  14785. if (keyboard)
  14786. return keyboard.keysRight;
  14787. },
  14788. set: function (value) {
  14789. var keyboard = this.inputs.attached["keyboard"];
  14790. if (keyboard)
  14791. keyboard.keysRight = value;
  14792. },
  14793. enumerable: true,
  14794. configurable: true
  14795. });
  14796. // Controls
  14797. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  14798. this.inputs.attachElement(element, noPreventDefault);
  14799. };
  14800. FreeCamera.prototype.detachControl = function (element) {
  14801. this.inputs.detachElement(element);
  14802. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14803. this.cameraRotation = new BABYLON.Vector2(0, 0);
  14804. };
  14805. FreeCamera.prototype._collideWithWorld = function (velocity) {
  14806. var globalPosition;
  14807. if (this.parent) {
  14808. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  14809. }
  14810. else {
  14811. globalPosition = this.position;
  14812. }
  14813. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  14814. this._collider.radius = this.ellipsoid;
  14815. //no need for clone, as long as gravity is not on.
  14816. var actualVelocity = velocity;
  14817. //add gravity to the velocity to prevent the dual-collision checking
  14818. if (this.applyGravity) {
  14819. //this prevents mending with cameraDirection, a global variable of the free camera class.
  14820. actualVelocity = velocity.add(this.getScene().gravity);
  14821. }
  14822. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  14823. };
  14824. FreeCamera.prototype._checkInputs = function () {
  14825. if (!this._localDirection) {
  14826. this._localDirection = BABYLON.Vector3.Zero();
  14827. this._transformedDirection = BABYLON.Vector3.Zero();
  14828. }
  14829. this.inputs.checkInputs();
  14830. _super.prototype._checkInputs.call(this);
  14831. };
  14832. FreeCamera.prototype._decideIfNeedsToMove = function () {
  14833. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14834. };
  14835. FreeCamera.prototype._updatePosition = function () {
  14836. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  14837. this._collideWithWorld(this.cameraDirection);
  14838. }
  14839. else {
  14840. this.position.addInPlace(this.cameraDirection);
  14841. }
  14842. };
  14843. FreeCamera.prototype.dispose = function () {
  14844. this.inputs.clear();
  14845. _super.prototype.dispose.call(this);
  14846. };
  14847. FreeCamera.prototype.getTypeName = function () {
  14848. return "FreeCamera";
  14849. };
  14850. __decorate([
  14851. BABYLON.serializeAsVector3()
  14852. ], FreeCamera.prototype, "ellipsoid", void 0);
  14853. __decorate([
  14854. BABYLON.serialize()
  14855. ], FreeCamera.prototype, "checkCollisions", void 0);
  14856. __decorate([
  14857. BABYLON.serialize()
  14858. ], FreeCamera.prototype, "applyGravity", void 0);
  14859. return FreeCamera;
  14860. }(BABYLON.TargetCamera));
  14861. BABYLON.FreeCamera = FreeCamera;
  14862. })(BABYLON || (BABYLON = {}));
  14863. var BABYLON;
  14864. (function (BABYLON) {
  14865. var FreeCameraInputsManager = (function (_super) {
  14866. __extends(FreeCameraInputsManager, _super);
  14867. function FreeCameraInputsManager(camera) {
  14868. _super.call(this, camera);
  14869. }
  14870. FreeCameraInputsManager.prototype.addKeyboard = function () {
  14871. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  14872. return this;
  14873. };
  14874. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  14875. if (touchEnabled === void 0) { touchEnabled = true; }
  14876. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  14877. return this;
  14878. };
  14879. FreeCameraInputsManager.prototype.addGamepad = function () {
  14880. this.add(new BABYLON.FreeCameraGamepadInput());
  14881. return this;
  14882. };
  14883. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  14884. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  14885. return this;
  14886. };
  14887. FreeCameraInputsManager.prototype.addTouch = function () {
  14888. this.add(new BABYLON.FreeCameraTouchInput());
  14889. return this;
  14890. };
  14891. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  14892. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  14893. return this;
  14894. };
  14895. return FreeCameraInputsManager;
  14896. }(BABYLON.CameraInputsManager));
  14897. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  14898. })(BABYLON || (BABYLON = {}));
  14899. var BABYLON;
  14900. (function (BABYLON) {
  14901. var FollowCamera = (function (_super) {
  14902. __extends(FollowCamera, _super);
  14903. function FollowCamera(name, position, scene, target) {
  14904. _super.call(this, name, position, scene);
  14905. this.radius = 12;
  14906. this.rotationOffset = 0;
  14907. this.heightOffset = 4;
  14908. this.cameraAcceleration = 0.05;
  14909. this.maxCameraSpeed = 20;
  14910. this.target = target;
  14911. }
  14912. FollowCamera.prototype.getRadians = function (degrees) {
  14913. return degrees * Math.PI / 180;
  14914. };
  14915. FollowCamera.prototype.follow = function (cameraTarget) {
  14916. if (!cameraTarget)
  14917. return;
  14918. var yRotation;
  14919. if (cameraTarget.rotationQuaternion) {
  14920. var rotMatrix = new BABYLON.Matrix();
  14921. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  14922. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  14923. }
  14924. else {
  14925. yRotation = cameraTarget.rotation.y;
  14926. }
  14927. var radians = this.getRadians(this.rotationOffset) + yRotation;
  14928. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  14929. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  14930. var dx = targetX - this.position.x;
  14931. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  14932. var dz = (targetZ) - this.position.z;
  14933. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  14934. var vy = dy * this.cameraAcceleration;
  14935. var vz = dz * this.cameraAcceleration * 2;
  14936. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  14937. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14938. }
  14939. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  14940. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14941. }
  14942. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  14943. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  14944. }
  14945. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  14946. this.setTarget(cameraTarget.position);
  14947. };
  14948. FollowCamera.prototype._checkInputs = function () {
  14949. _super.prototype._checkInputs.call(this);
  14950. this.follow(this.target);
  14951. };
  14952. FollowCamera.prototype.getTypeName = function () {
  14953. return "FollowCamera";
  14954. };
  14955. __decorate([
  14956. BABYLON.serialize()
  14957. ], FollowCamera.prototype, "radius", void 0);
  14958. __decorate([
  14959. BABYLON.serialize()
  14960. ], FollowCamera.prototype, "rotationOffset", void 0);
  14961. __decorate([
  14962. BABYLON.serialize()
  14963. ], FollowCamera.prototype, "heightOffset", void 0);
  14964. __decorate([
  14965. BABYLON.serialize()
  14966. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  14967. __decorate([
  14968. BABYLON.serialize()
  14969. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  14970. __decorate([
  14971. BABYLON.serializeAsMeshReference("lockedTargetId")
  14972. ], FollowCamera.prototype, "target", void 0);
  14973. return FollowCamera;
  14974. }(BABYLON.TargetCamera));
  14975. BABYLON.FollowCamera = FollowCamera;
  14976. var ArcFollowCamera = (function (_super) {
  14977. __extends(ArcFollowCamera, _super);
  14978. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  14979. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  14980. this.alpha = alpha;
  14981. this.beta = beta;
  14982. this.radius = radius;
  14983. this.target = target;
  14984. this._cartesianCoordinates = BABYLON.Vector3.Zero();
  14985. this.follow();
  14986. }
  14987. ArcFollowCamera.prototype.follow = function () {
  14988. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  14989. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  14990. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  14991. this.position = this.target.position.add(this._cartesianCoordinates);
  14992. this.setTarget(this.target.position);
  14993. };
  14994. ArcFollowCamera.prototype._checkInputs = function () {
  14995. _super.prototype._checkInputs.call(this);
  14996. this.follow();
  14997. };
  14998. ArcFollowCamera.prototype.getTypeName = function () {
  14999. return "ArcFollowCamera";
  15000. };
  15001. return ArcFollowCamera;
  15002. }(BABYLON.TargetCamera));
  15003. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15004. })(BABYLON || (BABYLON = {}));
  15005. var BABYLON;
  15006. (function (BABYLON) {
  15007. // We're mainly based on the logic defined into the FreeCamera code
  15008. var TouchCamera = (function (_super) {
  15009. __extends(TouchCamera, _super);
  15010. //-- end properties for backward compatibility for inputs
  15011. function TouchCamera(name, position, scene) {
  15012. _super.call(this, name, position, scene);
  15013. this.inputs.addTouch();
  15014. this._setupInputs();
  15015. }
  15016. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15017. //-- Begin properties for backward compatibility for inputs
  15018. get: function () {
  15019. var touch = this.inputs.attached["touch"];
  15020. if (touch)
  15021. return touch.touchAngularSensibility;
  15022. },
  15023. set: function (value) {
  15024. var touch = this.inputs.attached["touch"];
  15025. if (touch)
  15026. touch.touchAngularSensibility = value;
  15027. },
  15028. enumerable: true,
  15029. configurable: true
  15030. });
  15031. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  15032. get: function () {
  15033. var touch = this.inputs.attached["touch"];
  15034. if (touch)
  15035. return touch.touchMoveSensibility;
  15036. },
  15037. set: function (value) {
  15038. var touch = this.inputs.attached["touch"];
  15039. if (touch)
  15040. touch.touchMoveSensibility = value;
  15041. },
  15042. enumerable: true,
  15043. configurable: true
  15044. });
  15045. TouchCamera.prototype.getTypeName = function () {
  15046. return "TouchCamera";
  15047. };
  15048. TouchCamera.prototype._setupInputs = function () {
  15049. var mouse = this.inputs.attached["mouse"];
  15050. if (mouse) {
  15051. mouse.touchEnabled = false;
  15052. }
  15053. };
  15054. return TouchCamera;
  15055. }(BABYLON.FreeCamera));
  15056. BABYLON.TouchCamera = TouchCamera;
  15057. })(BABYLON || (BABYLON = {}));
  15058. var BABYLON;
  15059. (function (BABYLON) {
  15060. var ArcRotateCamera = (function (_super) {
  15061. __extends(ArcRotateCamera, _super);
  15062. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15063. var _this = this;
  15064. _super.call(this, name, BABYLON.Vector3.Zero(), scene);
  15065. this.inertialAlphaOffset = 0;
  15066. this.inertialBetaOffset = 0;
  15067. this.inertialRadiusOffset = 0;
  15068. this.lowerAlphaLimit = null;
  15069. this.upperAlphaLimit = null;
  15070. this.lowerBetaLimit = 0.01;
  15071. this.upperBetaLimit = Math.PI;
  15072. this.lowerRadiusLimit = null;
  15073. this.upperRadiusLimit = null;
  15074. this.inertialPanningX = 0;
  15075. this.inertialPanningY = 0;
  15076. //-- end properties for backward compatibility for inputs
  15077. this.zoomOnFactor = 1;
  15078. this.targetScreenOffset = BABYLON.Vector2.Zero();
  15079. this.allowUpsideDown = true;
  15080. this._viewMatrix = new BABYLON.Matrix();
  15081. // Panning
  15082. this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15083. this.checkCollisions = false;
  15084. this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15085. this._collider = new BABYLON.Collider();
  15086. this._previousPosition = BABYLON.Vector3.Zero();
  15087. this._collisionVelocity = BABYLON.Vector3.Zero();
  15088. this._newPosition = BABYLON.Vector3.Zero();
  15089. this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15090. if (collidedMesh === void 0) { collidedMesh = null; }
  15091. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15092. newPosition.multiplyInPlace(_this._collider.radius);
  15093. }
  15094. if (!collidedMesh) {
  15095. _this._previousPosition.copyFrom(_this.position);
  15096. }
  15097. else {
  15098. _this.setPosition(newPosition);
  15099. if (_this.onCollide) {
  15100. _this.onCollide(collidedMesh);
  15101. }
  15102. }
  15103. // Recompute because of constraints
  15104. var cosa = Math.cos(_this.alpha);
  15105. var sina = Math.sin(_this.alpha);
  15106. var cosb = Math.cos(_this.beta);
  15107. var sinb = Math.sin(_this.beta);
  15108. if (sinb === 0) {
  15109. sinb = 0.0001;
  15110. }
  15111. var target = _this._getTargetPosition();
  15112. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15113. _this.position.copyFrom(_this._newPosition);
  15114. var up = _this.upVector;
  15115. if (_this.allowUpsideDown && _this.beta < 0) {
  15116. up = up.clone();
  15117. up = up.negate();
  15118. }
  15119. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15120. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15121. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15122. _this._collisionTriggered = false;
  15123. };
  15124. if (!target) {
  15125. this.target = BABYLON.Vector3.Zero();
  15126. }
  15127. else {
  15128. this.target = target;
  15129. }
  15130. this.alpha = alpha;
  15131. this.beta = beta;
  15132. this.radius = radius;
  15133. this.getViewMatrix();
  15134. this.inputs = new BABYLON.ArcRotateCameraInputsManager(this);
  15135. this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15136. }
  15137. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15138. //-- begin properties for backward compatibility for inputs
  15139. get: function () {
  15140. var pointers = this.inputs.attached["pointers"];
  15141. if (pointers)
  15142. return pointers.angularSensibilityX;
  15143. },
  15144. set: function (value) {
  15145. var pointers = this.inputs.attached["pointers"];
  15146. if (pointers) {
  15147. pointers.angularSensibilityX = value;
  15148. }
  15149. },
  15150. enumerable: true,
  15151. configurable: true
  15152. });
  15153. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15154. get: function () {
  15155. var pointers = this.inputs.attached["pointers"];
  15156. if (pointers)
  15157. return pointers.angularSensibilityY;
  15158. },
  15159. set: function (value) {
  15160. var pointers = this.inputs.attached["pointers"];
  15161. if (pointers) {
  15162. pointers.angularSensibilityY = value;
  15163. }
  15164. },
  15165. enumerable: true,
  15166. configurable: true
  15167. });
  15168. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15169. get: function () {
  15170. var pointers = this.inputs.attached["pointers"];
  15171. if (pointers)
  15172. return pointers.pinchPrecision;
  15173. },
  15174. set: function (value) {
  15175. var pointers = this.inputs.attached["pointers"];
  15176. if (pointers) {
  15177. pointers.pinchPrecision = value;
  15178. }
  15179. },
  15180. enumerable: true,
  15181. configurable: true
  15182. });
  15183. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15184. get: function () {
  15185. var pointers = this.inputs.attached["pointers"];
  15186. if (pointers)
  15187. return pointers.panningSensibility;
  15188. },
  15189. set: function (value) {
  15190. var pointers = this.inputs.attached["pointers"];
  15191. if (pointers) {
  15192. pointers.panningSensibility = value;
  15193. }
  15194. },
  15195. enumerable: true,
  15196. configurable: true
  15197. });
  15198. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15199. get: function () {
  15200. var keyboard = this.inputs.attached["keyboard"];
  15201. if (keyboard)
  15202. return keyboard.keysUp;
  15203. },
  15204. set: function (value) {
  15205. var keyboard = this.inputs.attached["keyboard"];
  15206. if (keyboard)
  15207. keyboard.keysUp = value;
  15208. },
  15209. enumerable: true,
  15210. configurable: true
  15211. });
  15212. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15213. get: function () {
  15214. var keyboard = this.inputs.attached["keyboard"];
  15215. if (keyboard)
  15216. return keyboard.keysDown;
  15217. },
  15218. set: function (value) {
  15219. var keyboard = this.inputs.attached["keyboard"];
  15220. if (keyboard)
  15221. keyboard.keysDown = value;
  15222. },
  15223. enumerable: true,
  15224. configurable: true
  15225. });
  15226. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15227. get: function () {
  15228. var keyboard = this.inputs.attached["keyboard"];
  15229. if (keyboard)
  15230. return keyboard.keysLeft;
  15231. },
  15232. set: function (value) {
  15233. var keyboard = this.inputs.attached["keyboard"];
  15234. if (keyboard)
  15235. keyboard.keysLeft = value;
  15236. },
  15237. enumerable: true,
  15238. configurable: true
  15239. });
  15240. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15241. get: function () {
  15242. var keyboard = this.inputs.attached["keyboard"];
  15243. if (keyboard)
  15244. return keyboard.keysRight;
  15245. },
  15246. set: function (value) {
  15247. var keyboard = this.inputs.attached["keyboard"];
  15248. if (keyboard)
  15249. keyboard.keysRight = value;
  15250. },
  15251. enumerable: true,
  15252. configurable: true
  15253. });
  15254. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15255. get: function () {
  15256. var mousewheel = this.inputs.attached["mousewheel"];
  15257. if (mousewheel)
  15258. return mousewheel.wheelPrecision;
  15259. },
  15260. set: function (value) {
  15261. var mousewheel = this.inputs.attached["mousewheel"];
  15262. if (mousewheel)
  15263. mousewheel.wheelPrecision = value;
  15264. },
  15265. enumerable: true,
  15266. configurable: true
  15267. });
  15268. // Cache
  15269. ArcRotateCamera.prototype._initCache = function () {
  15270. _super.prototype._initCache.call(this);
  15271. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15272. this._cache.alpha = undefined;
  15273. this._cache.beta = undefined;
  15274. this._cache.radius = undefined;
  15275. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15276. };
  15277. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15278. if (!ignoreParentClass) {
  15279. _super.prototype._updateCache.call(this);
  15280. }
  15281. this._cache.target.copyFrom(this._getTargetPosition());
  15282. this._cache.alpha = this.alpha;
  15283. this._cache.beta = this.beta;
  15284. this._cache.radius = this.radius;
  15285. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15286. };
  15287. ArcRotateCamera.prototype._getTargetPosition = function () {
  15288. if (this.target.getAbsolutePosition) {
  15289. var pos = this.target.getAbsolutePosition();
  15290. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15291. }
  15292. return this.target;
  15293. };
  15294. // Synchronized
  15295. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15296. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15297. return false;
  15298. return this._cache.target.equals(this.target)
  15299. && this._cache.alpha === this.alpha
  15300. && this._cache.beta === this.beta
  15301. && this._cache.radius === this.radius
  15302. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15303. };
  15304. // Methods
  15305. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15306. var _this = this;
  15307. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15308. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15309. this._useCtrlForPanning = useCtrlForPanning;
  15310. this._panningMouseButton = panningMouseButton;
  15311. this.inputs.attachElement(element, noPreventDefault);
  15312. this._reset = function () {
  15313. _this.inertialAlphaOffset = 0;
  15314. _this.inertialBetaOffset = 0;
  15315. _this.inertialRadiusOffset = 0;
  15316. };
  15317. };
  15318. ArcRotateCamera.prototype.detachControl = function (element) {
  15319. this.inputs.detachElement(element);
  15320. if (this._reset) {
  15321. this._reset();
  15322. }
  15323. };
  15324. ArcRotateCamera.prototype._checkInputs = function () {
  15325. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15326. if (this._collisionTriggered) {
  15327. return;
  15328. }
  15329. this.inputs.checkInputs();
  15330. // Inertia
  15331. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15332. this.beta += this.inertialBetaOffset;
  15333. if (this.getScene().useRightHandedSystem) {
  15334. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15335. }
  15336. else {
  15337. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15338. }
  15339. this.radius -= this.inertialRadiusOffset;
  15340. this.inertialAlphaOffset *= this.inertia;
  15341. this.inertialBetaOffset *= this.inertia;
  15342. this.inertialRadiusOffset *= this.inertia;
  15343. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15344. this.inertialAlphaOffset = 0;
  15345. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15346. this.inertialBetaOffset = 0;
  15347. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15348. this.inertialRadiusOffset = 0;
  15349. }
  15350. // Panning inertia
  15351. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15352. if (!this._localDirection) {
  15353. this._localDirection = BABYLON.Vector3.Zero();
  15354. this._transformedDirection = BABYLON.Vector3.Zero();
  15355. }
  15356. this.inertialPanningX *= this.inertia;
  15357. this.inertialPanningY *= this.inertia;
  15358. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15359. this.inertialPanningX = 0;
  15360. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15361. this.inertialPanningY = 0;
  15362. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15363. this._localDirection.multiplyInPlace(this.panningAxis);
  15364. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15365. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15366. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15367. if (!this.panningAxis.y) {
  15368. this._transformedDirection.y = 0;
  15369. }
  15370. if (!this.target.getAbsolutePosition) {
  15371. this.target.addInPlace(this._transformedDirection);
  15372. }
  15373. }
  15374. // Limits
  15375. this._checkLimits();
  15376. _super.prototype._checkInputs.call(this);
  15377. };
  15378. ArcRotateCamera.prototype._checkLimits = function () {
  15379. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15380. if (this.allowUpsideDown && this.beta > Math.PI) {
  15381. this.beta = this.beta - (2 * Math.PI);
  15382. }
  15383. }
  15384. else {
  15385. if (this.beta < this.lowerBetaLimit) {
  15386. this.beta = this.lowerBetaLimit;
  15387. }
  15388. }
  15389. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15390. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15391. this.beta = this.beta + (2 * Math.PI);
  15392. }
  15393. }
  15394. else {
  15395. if (this.beta > this.upperBetaLimit) {
  15396. this.beta = this.upperBetaLimit;
  15397. }
  15398. }
  15399. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15400. this.alpha = this.lowerAlphaLimit;
  15401. }
  15402. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15403. this.alpha = this.upperAlphaLimit;
  15404. }
  15405. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15406. this.radius = this.lowerRadiusLimit;
  15407. }
  15408. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15409. this.radius = this.upperRadiusLimit;
  15410. }
  15411. };
  15412. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15413. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15414. this.radius = radiusv3.length();
  15415. // Alpha
  15416. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15417. if (radiusv3.z < 0) {
  15418. this.alpha = 2 * Math.PI - this.alpha;
  15419. }
  15420. // Beta
  15421. this.beta = Math.acos(radiusv3.y / this.radius);
  15422. this._checkLimits();
  15423. };
  15424. ArcRotateCamera.prototype.setPosition = function (position) {
  15425. if (this.position.equals(position)) {
  15426. return;
  15427. }
  15428. this.position.copyFrom(position);
  15429. this.rebuildAnglesAndRadius();
  15430. };
  15431. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15432. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15433. if (this._getTargetPosition().equals(target)) {
  15434. return;
  15435. }
  15436. if (toBoundingCenter && target.getBoundingInfo) {
  15437. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15438. }
  15439. else {
  15440. this._targetBoundingCenter = null;
  15441. }
  15442. this.target = target;
  15443. this.rebuildAnglesAndRadius();
  15444. };
  15445. ArcRotateCamera.prototype._getViewMatrix = function () {
  15446. // Compute
  15447. var cosa = Math.cos(this.alpha);
  15448. var sina = Math.sin(this.alpha);
  15449. var cosb = Math.cos(this.beta);
  15450. var sinb = Math.sin(this.beta);
  15451. if (sinb === 0) {
  15452. sinb = 0.0001;
  15453. }
  15454. var target = this._getTargetPosition();
  15455. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15456. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15457. this._collider.radius = this.collisionRadius;
  15458. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15459. this._collisionTriggered = true;
  15460. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15461. }
  15462. else {
  15463. this.position.copyFrom(this._newPosition);
  15464. var up = this.upVector;
  15465. if (this.allowUpsideDown && this.beta < 0) {
  15466. up = up.clone();
  15467. up = up.negate();
  15468. }
  15469. if (this.getScene().useRightHandedSystem) {
  15470. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15471. }
  15472. else {
  15473. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15474. }
  15475. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15476. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15477. }
  15478. return this._viewMatrix;
  15479. };
  15480. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15481. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15482. meshes = meshes || this.getScene().meshes;
  15483. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15484. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15485. this.radius = distance * this.zoomOnFactor;
  15486. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15487. };
  15488. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15489. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15490. var meshesOrMinMaxVector;
  15491. var distance;
  15492. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15493. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15494. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15495. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15496. }
  15497. else {
  15498. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15499. distance = meshesOrMinMaxVectorAndDistance.distance;
  15500. }
  15501. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15502. if (!doNotUpdateMaxZ) {
  15503. this.maxZ = distance * 2;
  15504. }
  15505. };
  15506. /**
  15507. * @override
  15508. * Override Camera.createRigCamera
  15509. */
  15510. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15511. var alphaShift;
  15512. switch (this.cameraRigMode) {
  15513. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15514. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15515. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15516. case BABYLON.Camera.RIG_MODE_VR:
  15517. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15518. break;
  15519. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15520. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15521. break;
  15522. }
  15523. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15524. rigCam._cameraRigParams = {};
  15525. return rigCam;
  15526. };
  15527. /**
  15528. * @override
  15529. * Override Camera._updateRigCameras
  15530. */
  15531. ArcRotateCamera.prototype._updateRigCameras = function () {
  15532. var camLeft = this._rigCameras[0];
  15533. var camRight = this._rigCameras[1];
  15534. camLeft.beta = camRight.beta = this.beta;
  15535. camLeft.radius = camRight.radius = this.radius;
  15536. switch (this.cameraRigMode) {
  15537. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15538. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15539. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15540. case BABYLON.Camera.RIG_MODE_VR:
  15541. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15542. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15543. break;
  15544. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15545. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15546. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15547. break;
  15548. }
  15549. _super.prototype._updateRigCameras.call(this);
  15550. };
  15551. ArcRotateCamera.prototype.dispose = function () {
  15552. this.inputs.clear();
  15553. _super.prototype.dispose.call(this);
  15554. };
  15555. ArcRotateCamera.prototype.getTypeName = function () {
  15556. return "ArcRotateCamera";
  15557. };
  15558. __decorate([
  15559. BABYLON.serialize()
  15560. ], ArcRotateCamera.prototype, "alpha", void 0);
  15561. __decorate([
  15562. BABYLON.serialize()
  15563. ], ArcRotateCamera.prototype, "beta", void 0);
  15564. __decorate([
  15565. BABYLON.serialize()
  15566. ], ArcRotateCamera.prototype, "radius", void 0);
  15567. __decorate([
  15568. BABYLON.serializeAsVector3()
  15569. ], ArcRotateCamera.prototype, "target", void 0);
  15570. __decorate([
  15571. BABYLON.serialize()
  15572. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15573. __decorate([
  15574. BABYLON.serialize()
  15575. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15576. __decorate([
  15577. BABYLON.serialize()
  15578. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15579. __decorate([
  15580. BABYLON.serialize()
  15581. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15582. __decorate([
  15583. BABYLON.serialize()
  15584. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15585. __decorate([
  15586. BABYLON.serialize()
  15587. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15588. __decorate([
  15589. BABYLON.serialize()
  15590. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15591. __decorate([
  15592. BABYLON.serialize()
  15593. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15594. __decorate([
  15595. BABYLON.serialize()
  15596. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15597. __decorate([
  15598. BABYLON.serialize()
  15599. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15600. __decorate([
  15601. BABYLON.serialize()
  15602. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15603. __decorate([
  15604. BABYLON.serialize()
  15605. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15606. __decorate([
  15607. BABYLON.serialize()
  15608. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  15609. return ArcRotateCamera;
  15610. }(BABYLON.TargetCamera));
  15611. BABYLON.ArcRotateCamera = ArcRotateCamera;
  15612. })(BABYLON || (BABYLON = {}));
  15613. var BABYLON;
  15614. (function (BABYLON) {
  15615. var ArcRotateCameraInputsManager = (function (_super) {
  15616. __extends(ArcRotateCameraInputsManager, _super);
  15617. function ArcRotateCameraInputsManager(camera) {
  15618. _super.call(this, camera);
  15619. }
  15620. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  15621. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  15622. return this;
  15623. };
  15624. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  15625. this.add(new BABYLON.ArcRotateCameraPointersInput());
  15626. return this;
  15627. };
  15628. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  15629. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  15630. return this;
  15631. };
  15632. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  15633. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  15634. return this;
  15635. };
  15636. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  15637. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  15638. return this;
  15639. };
  15640. return ArcRotateCameraInputsManager;
  15641. }(BABYLON.CameraInputsManager));
  15642. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  15643. })(BABYLON || (BABYLON = {}));
  15644. var BABYLON;
  15645. (function (BABYLON) {
  15646. var RenderingManager = (function () {
  15647. function RenderingManager(scene) {
  15648. this._renderingGroups = new Array();
  15649. this._autoClearDepthStencil = {};
  15650. this._customOpaqueSortCompareFn = {};
  15651. this._customAlphaTestSortCompareFn = {};
  15652. this._customTransparentSortCompareFn = {};
  15653. this._renderinGroupInfo = null;
  15654. this._scene = scene;
  15655. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15656. this._autoClearDepthStencil[i] = true;
  15657. }
  15658. }
  15659. RenderingManager.prototype._renderParticles = function (index, activeMeshes) {
  15660. if (this._scene._activeParticleSystems.length === 0) {
  15661. return;
  15662. }
  15663. // Particles
  15664. var activeCamera = this._scene.activeCamera;
  15665. this._scene._particlesDuration.beginMonitoring();
  15666. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  15667. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  15668. if (particleSystem.renderingGroupId !== index) {
  15669. continue;
  15670. }
  15671. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  15672. continue;
  15673. }
  15674. this._clearDepthStencilBuffer();
  15675. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  15676. this._scene._activeParticles.addCount(particleSystem.render(), false);
  15677. }
  15678. }
  15679. this._scene._particlesDuration.endMonitoring(false);
  15680. };
  15681. RenderingManager.prototype._renderSprites = function (index) {
  15682. if (!this._scene.spritesEnabled || this._scene.spriteManagers.length === 0) {
  15683. return;
  15684. }
  15685. // Sprites
  15686. var activeCamera = this._scene.activeCamera;
  15687. this._scene._spritesDuration.beginMonitoring();
  15688. for (var id = 0; id < this._scene.spriteManagers.length; id++) {
  15689. var spriteManager = this._scene.spriteManagers[id];
  15690. if (spriteManager.renderingGroupId === index && ((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  15691. this._clearDepthStencilBuffer();
  15692. spriteManager.render();
  15693. }
  15694. }
  15695. this._scene._spritesDuration.endMonitoring(false);
  15696. };
  15697. RenderingManager.prototype._clearDepthStencilBuffer = function () {
  15698. if (this._depthStencilBufferAlreadyCleaned) {
  15699. return;
  15700. }
  15701. this._scene.getEngine().clear(0, false, true, true);
  15702. this._depthStencilBufferAlreadyCleaned = true;
  15703. };
  15704. RenderingManager.prototype._renderSpritesAndParticles = function () {
  15705. if (this._currentRenderSprites) {
  15706. this._renderSprites(this._currentIndex);
  15707. }
  15708. if (this._currentRenderParticles) {
  15709. this._renderParticles(this._currentIndex, this._currentActiveMeshes);
  15710. }
  15711. };
  15712. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15713. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15714. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15715. var info = null;
  15716. if (observable) {
  15717. if (!this._renderinGroupInfo) {
  15718. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15719. }
  15720. info = this._renderinGroupInfo;
  15721. info.scene = this._scene;
  15722. info.camera = this._scene.activeCamera;
  15723. }
  15724. this._currentActiveMeshes = activeMeshes;
  15725. this._currentRenderParticles = renderParticles;
  15726. this._currentRenderSprites = renderSprites;
  15727. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15728. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15729. var renderingGroup = this._renderingGroups[index];
  15730. var needToStepBack = false;
  15731. this._currentIndex = index;
  15732. if (renderingGroup) {
  15733. var renderingGroupMask = 0;
  15734. // Fire PRECLEAR stage
  15735. if (observable) {
  15736. renderingGroupMask = Math.pow(2, index);
  15737. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15738. info.renderingGroupId = index;
  15739. observable.notifyObservers(info, renderingGroupMask);
  15740. }
  15741. // Clear depth/stencil if needed
  15742. if (this._autoClearDepthStencil[index]) {
  15743. this._clearDepthStencilBuffer();
  15744. }
  15745. // Fire PREOPAQUE stage
  15746. if (observable) {
  15747. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15748. observable.notifyObservers(info, renderingGroupMask);
  15749. }
  15750. if (!renderingGroup.onBeforeTransparentRendering) {
  15751. renderingGroup.onBeforeTransparentRendering = this._renderSpritesAndParticles.bind(this);
  15752. }
  15753. // Fire PRETRANSPARENT stage
  15754. if (observable) {
  15755. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15756. observable.notifyObservers(info, renderingGroupMask);
  15757. }
  15758. if (!renderingGroup.render(customRenderFunction)) {
  15759. this._renderingGroups.splice(index, 1);
  15760. needToStepBack = true;
  15761. this._renderSpritesAndParticles();
  15762. }
  15763. // Fire POSTTRANSPARENT stage
  15764. if (observable) {
  15765. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15766. observable.notifyObservers(info, renderingGroupMask);
  15767. }
  15768. }
  15769. else {
  15770. this._renderSpritesAndParticles();
  15771. if (observable) {
  15772. var renderingGroupMask = Math.pow(2, index);
  15773. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15774. info.renderingGroupId = index;
  15775. observable.notifyObservers(info, renderingGroupMask);
  15776. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15777. observable.notifyObservers(info, renderingGroupMask);
  15778. }
  15779. }
  15780. if (needToStepBack) {
  15781. index--;
  15782. }
  15783. }
  15784. };
  15785. RenderingManager.prototype.reset = function () {
  15786. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15787. var renderingGroup = this._renderingGroups[index];
  15788. if (renderingGroup) {
  15789. renderingGroup.prepare();
  15790. }
  15791. }
  15792. };
  15793. RenderingManager.prototype.dispatch = function (subMesh) {
  15794. var mesh = subMesh.getMesh();
  15795. var renderingGroupId = mesh.renderingGroupId || 0;
  15796. if (!this._renderingGroups[renderingGroupId]) {
  15797. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15798. }
  15799. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15800. };
  15801. /**
  15802. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15803. * This allowed control for front to back rendering or reversly depending of the special needs.
  15804. *
  15805. * @param renderingGroupId The rendering group id corresponding to its index
  15806. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15807. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15808. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15809. */
  15810. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15811. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15812. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15813. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15814. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15815. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15816. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15817. if (this._renderingGroups[renderingGroupId]) {
  15818. var group = this._renderingGroups[renderingGroupId];
  15819. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15820. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15821. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15822. }
  15823. };
  15824. /**
  15825. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15826. *
  15827. * @param renderingGroupId The rendering group id corresponding to its index
  15828. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15829. */
  15830. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  15831. this._autoClearDepthStencil[renderingGroupId] = autoClearDepthStencil;
  15832. };
  15833. /**
  15834. * The max id used for rendering groups (not included)
  15835. */
  15836. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15837. /**
  15838. * The min id used for rendering groups (included)
  15839. */
  15840. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15841. return RenderingManager;
  15842. }());
  15843. BABYLON.RenderingManager = RenderingManager;
  15844. })(BABYLON || (BABYLON = {}));
  15845. var BABYLON;
  15846. (function (BABYLON) {
  15847. var RenderingGroup = (function () {
  15848. /**
  15849. * Creates a new rendering group.
  15850. * @param index The rendering group index
  15851. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15852. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15853. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15854. */
  15855. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15856. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15857. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15858. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15859. this.index = index;
  15860. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15861. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15862. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15863. this._scene = scene;
  15864. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15865. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15866. this.transparentSortCompareFn = transparentSortCompareFn;
  15867. }
  15868. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15869. /**
  15870. * Set the opaque sort comparison function.
  15871. * If null the sub meshes will be render in the order they were created
  15872. */
  15873. set: function (value) {
  15874. this._opaqueSortCompareFn = value;
  15875. if (value) {
  15876. this._renderOpaque = this.renderOpaqueSorted;
  15877. }
  15878. else {
  15879. this._renderOpaque = RenderingGroup.renderUnsorted;
  15880. }
  15881. },
  15882. enumerable: true,
  15883. configurable: true
  15884. });
  15885. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15886. /**
  15887. * Set the alpha test sort comparison function.
  15888. * If null the sub meshes will be render in the order they were created
  15889. */
  15890. set: function (value) {
  15891. this._alphaTestSortCompareFn = value;
  15892. if (value) {
  15893. this._renderAlphaTest = this.renderAlphaTestSorted;
  15894. }
  15895. else {
  15896. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15897. }
  15898. },
  15899. enumerable: true,
  15900. configurable: true
  15901. });
  15902. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15903. /**
  15904. * Set the transparent sort comparison function.
  15905. * If null the sub meshes will be render in the order they were created
  15906. */
  15907. set: function (value) {
  15908. if (value) {
  15909. this._transparentSortCompareFn = value;
  15910. }
  15911. else {
  15912. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15913. }
  15914. this._renderTransparent = this.renderTransparentSorted;
  15915. },
  15916. enumerable: true,
  15917. configurable: true
  15918. });
  15919. /**
  15920. * Render all the sub meshes contained in the group.
  15921. * @param customRenderFunction Used to override the default render behaviour of the group.
  15922. * @returns true if rendered some submeshes.
  15923. */
  15924. RenderingGroup.prototype.render = function (customRenderFunction) {
  15925. if (customRenderFunction) {
  15926. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15927. return true;
  15928. }
  15929. if (this._opaqueSubMeshes.length === 0 && this._alphaTestSubMeshes.length === 0 && this._transparentSubMeshes.length === 0) {
  15930. if (this.onBeforeTransparentRendering) {
  15931. this.onBeforeTransparentRendering();
  15932. }
  15933. return false;
  15934. }
  15935. var engine = this._scene.getEngine();
  15936. // Opaque
  15937. this._renderOpaque(this._opaqueSubMeshes);
  15938. // Alpha test
  15939. engine.setAlphaTesting(true);
  15940. this._renderAlphaTest(this._alphaTestSubMeshes);
  15941. engine.setAlphaTesting(false);
  15942. if (this.onBeforeTransparentRendering) {
  15943. this.onBeforeTransparentRendering();
  15944. }
  15945. // Transparent
  15946. this._renderTransparent(this._transparentSubMeshes);
  15947. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15948. return true;
  15949. };
  15950. /**
  15951. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15952. * @param subMeshes The submeshes to render
  15953. */
  15954. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15955. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15956. };
  15957. /**
  15958. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15959. * @param subMeshes The submeshes to render
  15960. */
  15961. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15962. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15963. };
  15964. /**
  15965. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15966. * @param subMeshes The submeshes to render
  15967. */
  15968. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15969. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15970. };
  15971. /**
  15972. * Renders the submeshes in a specified order.
  15973. * @param subMeshes The submeshes to sort before render
  15974. * @param sortCompareFn The comparison function use to sort
  15975. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15976. * @param transparent Specifies to activate blending if true
  15977. */
  15978. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15979. var subIndex = 0;
  15980. var subMesh;
  15981. for (; subIndex < subMeshes.length; subIndex++) {
  15982. subMesh = subMeshes.data[subIndex];
  15983. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15984. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15985. }
  15986. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15987. sortedArray.sort(sortCompareFn);
  15988. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15989. subMesh = sortedArray[subIndex];
  15990. subMesh.render(transparent);
  15991. }
  15992. };
  15993. /**
  15994. * Renders the submeshes in the order they were dispatched (no sort applied).
  15995. * @param subMeshes The submeshes to render
  15996. */
  15997. RenderingGroup.renderUnsorted = function (subMeshes) {
  15998. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15999. var submesh = subMeshes.data[subIndex];
  16000. submesh.render(false);
  16001. }
  16002. };
  16003. /**
  16004. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16005. * are rendered back to front if in the same alpha index.
  16006. *
  16007. * @param a The first submesh
  16008. * @param b The second submesh
  16009. * @returns The result of the comparison
  16010. */
  16011. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16012. // Alpha index first
  16013. if (a._alphaIndex > b._alphaIndex) {
  16014. return 1;
  16015. }
  16016. if (a._alphaIndex < b._alphaIndex) {
  16017. return -1;
  16018. }
  16019. // Then distance to camera
  16020. return RenderingGroup.backToFrontSortCompare(a, b);
  16021. };
  16022. /**
  16023. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16024. * are rendered back to front.
  16025. *
  16026. * @param a The first submesh
  16027. * @param b The second submesh
  16028. * @returns The result of the comparison
  16029. */
  16030. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16031. // Then distance to camera
  16032. if (a._distanceToCamera < b._distanceToCamera) {
  16033. return 1;
  16034. }
  16035. if (a._distanceToCamera > b._distanceToCamera) {
  16036. return -1;
  16037. }
  16038. return 0;
  16039. };
  16040. /**
  16041. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16042. * are rendered front to back (prevent overdraw).
  16043. *
  16044. * @param a The first submesh
  16045. * @param b The second submesh
  16046. * @returns The result of the comparison
  16047. */
  16048. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16049. // Then distance to camera
  16050. if (a._distanceToCamera < b._distanceToCamera) {
  16051. return -1;
  16052. }
  16053. if (a._distanceToCamera > b._distanceToCamera) {
  16054. return 1;
  16055. }
  16056. return 0;
  16057. };
  16058. /**
  16059. * Resets the different lists of submeshes to prepare a new frame.
  16060. */
  16061. RenderingGroup.prototype.prepare = function () {
  16062. this._opaqueSubMeshes.reset();
  16063. this._transparentSubMeshes.reset();
  16064. this._alphaTestSubMeshes.reset();
  16065. };
  16066. /**
  16067. * Inserts the submesh in its correct queue depending on its material.
  16068. * @param subMesh The submesh to dispatch
  16069. */
  16070. RenderingGroup.prototype.dispatch = function (subMesh) {
  16071. var material = subMesh.getMaterial();
  16072. var mesh = subMesh.getMesh();
  16073. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16074. this._transparentSubMeshes.push(subMesh);
  16075. }
  16076. else if (material.needAlphaTesting()) {
  16077. this._alphaTestSubMeshes.push(subMesh);
  16078. }
  16079. else {
  16080. this._opaqueSubMeshes.push(subMesh); // Opaque
  16081. }
  16082. };
  16083. return RenderingGroup;
  16084. }());
  16085. BABYLON.RenderingGroup = RenderingGroup;
  16086. })(BABYLON || (BABYLON = {}));
  16087. var BABYLON;
  16088. (function (BABYLON) {
  16089. var PointerEventTypes = (function () {
  16090. function PointerEventTypes() {
  16091. }
  16092. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16093. get: function () {
  16094. return PointerEventTypes._POINTERDOWN;
  16095. },
  16096. enumerable: true,
  16097. configurable: true
  16098. });
  16099. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16100. get: function () {
  16101. return PointerEventTypes._POINTERUP;
  16102. },
  16103. enumerable: true,
  16104. configurable: true
  16105. });
  16106. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16107. get: function () {
  16108. return PointerEventTypes._POINTERMOVE;
  16109. },
  16110. enumerable: true,
  16111. configurable: true
  16112. });
  16113. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16114. get: function () {
  16115. return PointerEventTypes._POINTERWHEEL;
  16116. },
  16117. enumerable: true,
  16118. configurable: true
  16119. });
  16120. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16121. get: function () {
  16122. return PointerEventTypes._POINTERPICK;
  16123. },
  16124. enumerable: true,
  16125. configurable: true
  16126. });
  16127. PointerEventTypes._POINTERDOWN = 0x01;
  16128. PointerEventTypes._POINTERUP = 0x02;
  16129. PointerEventTypes._POINTERMOVE = 0x04;
  16130. PointerEventTypes._POINTERWHEEL = 0x08;
  16131. PointerEventTypes._POINTERPICK = 0x10;
  16132. return PointerEventTypes;
  16133. }());
  16134. BABYLON.PointerEventTypes = PointerEventTypes;
  16135. var PointerInfoBase = (function () {
  16136. function PointerInfoBase(type, event) {
  16137. this.type = type;
  16138. this.event = event;
  16139. }
  16140. return PointerInfoBase;
  16141. }());
  16142. BABYLON.PointerInfoBase = PointerInfoBase;
  16143. /**
  16144. * This class is used to store pointer related info for the onPrePointerObservable event.
  16145. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16146. */
  16147. var PointerInfoPre = (function (_super) {
  16148. __extends(PointerInfoPre, _super);
  16149. function PointerInfoPre(type, event, localX, localY) {
  16150. _super.call(this, type, event);
  16151. this.skipOnPointerObservable = false;
  16152. this.localPosition = new BABYLON.Vector2(localX, localY);
  16153. }
  16154. return PointerInfoPre;
  16155. }(PointerInfoBase));
  16156. BABYLON.PointerInfoPre = PointerInfoPre;
  16157. /**
  16158. * This type contains all the data related to a pointer event in Babylon.js.
  16159. * 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.
  16160. */
  16161. var PointerInfo = (function (_super) {
  16162. __extends(PointerInfo, _super);
  16163. function PointerInfo(type, event, pickInfo) {
  16164. _super.call(this, type, event);
  16165. this.pickInfo = pickInfo;
  16166. }
  16167. return PointerInfo;
  16168. }(PointerInfoBase));
  16169. BABYLON.PointerInfo = PointerInfo;
  16170. /**
  16171. * This class is used by the onRenderingGroupObservable
  16172. */
  16173. var RenderingGroupInfo = (function () {
  16174. function RenderingGroupInfo() {
  16175. }
  16176. /**
  16177. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16178. * This stage will be fired no matter what
  16179. */
  16180. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16181. /**
  16182. * Called before opaque object are rendered.
  16183. * This stage will be fired only if there's 3D Opaque content to render
  16184. */
  16185. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16186. /**
  16187. * Called after the opaque objects are rendered and before the transparent ones
  16188. * This stage will be fired only if there's 3D transparent content to render
  16189. */
  16190. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16191. /**
  16192. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16193. * This stage will be fired no matter what
  16194. */
  16195. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16196. return RenderingGroupInfo;
  16197. }());
  16198. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16199. /**
  16200. * Represents a scene to be rendered by the engine.
  16201. * @see http://doc.babylonjs.com/page.php?p=21911
  16202. */
  16203. var Scene = (function () {
  16204. /**
  16205. * @constructor
  16206. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16207. */
  16208. function Scene(engine) {
  16209. // Members
  16210. this.autoClear = true;
  16211. this.clearColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16212. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16213. this.forceWireframe = false;
  16214. this.forcePointsCloud = false;
  16215. this.forceShowBoundingBoxes = false;
  16216. this.animationsEnabled = true;
  16217. this.constantlyUpdateMeshUnderPointer = false;
  16218. this.useRightHandedSystem = false;
  16219. this.hoverCursor = "pointer";
  16220. // Events
  16221. /**
  16222. * An event triggered when the scene is disposed.
  16223. * @type {BABYLON.Observable}
  16224. */
  16225. this.onDisposeObservable = new BABYLON.Observable();
  16226. /**
  16227. * An event triggered before rendering the scene
  16228. * @type {BABYLON.Observable}
  16229. */
  16230. this.onBeforeRenderObservable = new BABYLON.Observable();
  16231. /**
  16232. * An event triggered after rendering the scene
  16233. * @type {BABYLON.Observable}
  16234. */
  16235. this.onAfterRenderObservable = new BABYLON.Observable();
  16236. /**
  16237. * An event triggered when the scene is ready
  16238. * @type {BABYLON.Observable}
  16239. */
  16240. this.onReadyObservable = new BABYLON.Observable();
  16241. /**
  16242. * An event triggered before rendering a camera
  16243. * @type {BABYLON.Observable}
  16244. */
  16245. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16246. /**
  16247. * An event triggered after rendering a camera
  16248. * @type {BABYLON.Observable}
  16249. */
  16250. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16251. /**
  16252. * An event triggered when a camera is created
  16253. * @type {BABYLON.Observable}
  16254. */
  16255. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16256. /**
  16257. * An event triggered when a camera is removed
  16258. * @type {BABYLON.Observable}
  16259. */
  16260. this.onCameraRemovedObservable = new BABYLON.Observable();
  16261. /**
  16262. * An event triggered when a light is created
  16263. * @type {BABYLON.Observable}
  16264. */
  16265. this.onNewLightAddedObservable = new BABYLON.Observable();
  16266. /**
  16267. * An event triggered when a light is removed
  16268. * @type {BABYLON.Observable}
  16269. */
  16270. this.onLightRemovedObservable = new BABYLON.Observable();
  16271. /**
  16272. * An event triggered when a geometry is created
  16273. * @type {BABYLON.Observable}
  16274. */
  16275. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16276. /**
  16277. * An event triggered when a geometry is removed
  16278. * @type {BABYLON.Observable}
  16279. */
  16280. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16281. /**
  16282. * An event triggered when a mesh is created
  16283. * @type {BABYLON.Observable}
  16284. */
  16285. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16286. /**
  16287. * An event triggered when a mesh is removed
  16288. * @type {BABYLON.Observable}
  16289. */
  16290. this.onMeshRemovedObservable = new BABYLON.Observable();
  16291. /**
  16292. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16293. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16294. * 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)
  16295. */
  16296. this.onRenderingGroupObservable = new BABYLON.Observable();
  16297. // Animations
  16298. this.animations = [];
  16299. /**
  16300. * 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).
  16301. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16302. */
  16303. this.onPrePointerObservable = new BABYLON.Observable();
  16304. /**
  16305. * Observable event triggered each time an input event is received from the rendering canvas
  16306. */
  16307. this.onPointerObservable = new BABYLON.Observable();
  16308. 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
  16309. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16310. this._startingPointerTime = 0;
  16311. // Fog
  16312. /**
  16313. * is fog enabled on this scene.
  16314. * @type {boolean}
  16315. */
  16316. this.fogEnabled = true;
  16317. this.fogMode = Scene.FOGMODE_NONE;
  16318. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16319. this.fogDensity = 0.1;
  16320. this.fogStart = 0;
  16321. this.fogEnd = 1000.0;
  16322. // Lights
  16323. /**
  16324. * is shadow enabled on this scene.
  16325. * @type {boolean}
  16326. */
  16327. this.shadowsEnabled = true;
  16328. /**
  16329. * is light enabled on this scene.
  16330. * @type {boolean}
  16331. */
  16332. this.lightsEnabled = true;
  16333. /**
  16334. * All of the lights added to this scene.
  16335. * @see BABYLON.Light
  16336. * @type {BABYLON.Light[]}
  16337. */
  16338. this.lights = new Array();
  16339. // Cameras
  16340. /**
  16341. * All of the cameras added to this scene.
  16342. * @see BABYLON.Camera
  16343. * @type {BABYLON.Camera[]}
  16344. */
  16345. this.cameras = new Array();
  16346. this.activeCameras = new Array();
  16347. // Meshes
  16348. /**
  16349. * All of the (abstract) meshes added to this scene.
  16350. * @see BABYLON.AbstractMesh
  16351. * @type {BABYLON.AbstractMesh[]}
  16352. */
  16353. this.meshes = new Array();
  16354. // Geometries
  16355. this._geometries = new Array();
  16356. this.materials = new Array();
  16357. this.multiMaterials = new Array();
  16358. // Textures
  16359. this.texturesEnabled = true;
  16360. this.textures = new Array();
  16361. // Particles
  16362. this.particlesEnabled = true;
  16363. this.particleSystems = new Array();
  16364. // Sprites
  16365. this.spritesEnabled = true;
  16366. this.spriteManagers = new Array();
  16367. // Layers
  16368. this.layers = new Array();
  16369. this.highlightLayers = new Array();
  16370. // Skeletons
  16371. this.skeletonsEnabled = true;
  16372. this.skeletons = new Array();
  16373. // Lens flares
  16374. this.lensFlaresEnabled = true;
  16375. this.lensFlareSystems = new Array();
  16376. // Collisions
  16377. this.collisionsEnabled = true;
  16378. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16379. // Postprocesses
  16380. this.postProcessesEnabled = true;
  16381. // Customs render targets
  16382. this.renderTargetsEnabled = true;
  16383. this.dumpNextRenderTargets = false;
  16384. this.customRenderTargets = new Array();
  16385. // Imported meshes
  16386. this.importedMeshesFiles = new Array();
  16387. // Probes
  16388. this.probesEnabled = true;
  16389. this.reflectionProbes = new Array();
  16390. this._actionManagers = new Array();
  16391. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16392. // Procedural textures
  16393. this.proceduralTexturesEnabled = true;
  16394. this._proceduralTextures = new Array();
  16395. this.soundTracks = new Array();
  16396. this._audioEnabled = true;
  16397. this._headphone = false;
  16398. // Performance counters
  16399. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16400. this._totalLightsCounter = new BABYLON.PerfCounter();
  16401. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16402. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16403. this._totalVertices = new BABYLON.PerfCounter();
  16404. this._activeIndices = new BABYLON.PerfCounter();
  16405. this._activeParticles = new BABYLON.PerfCounter();
  16406. this._lastFrameDuration = new BABYLON.PerfCounter();
  16407. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16408. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16409. this._particlesDuration = new BABYLON.PerfCounter();
  16410. this._renderDuration = new BABYLON.PerfCounter();
  16411. this._spritesDuration = new BABYLON.PerfCounter();
  16412. this._activeBones = new BABYLON.PerfCounter();
  16413. this._renderId = 0;
  16414. this._executeWhenReadyTimeoutId = -1;
  16415. this._intermediateRendering = false;
  16416. this._toBeDisposed = new BABYLON.SmartArray(256);
  16417. this._pendingData = []; //ANY
  16418. this._activeMeshes = new BABYLON.SmartArray(256);
  16419. this._processedMaterials = new BABYLON.SmartArray(256);
  16420. this._renderTargets = new BABYLON.SmartArray(256);
  16421. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16422. this._activeSkeletons = new BABYLON.SmartArray(32);
  16423. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16424. this._activeAnimatables = new Array();
  16425. this._transformMatrix = BABYLON.Matrix.Zero();
  16426. this._edgesRenderers = new BABYLON.SmartArray(16);
  16427. this._uniqueIdCounter = 0;
  16428. this._engine = engine;
  16429. engine.scenes.push(this);
  16430. this._externalData = new BABYLON.StringDictionary();
  16431. this._uid = null;
  16432. this._renderingManager = new BABYLON.RenderingManager(this);
  16433. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16434. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16435. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16436. if (BABYLON.OutlineRenderer) {
  16437. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16438. }
  16439. this.attachControl();
  16440. if (BABYLON.SoundTrack) {
  16441. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16442. }
  16443. //simplification queue
  16444. if (BABYLON.SimplificationQueue) {
  16445. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16446. }
  16447. //collision coordinator initialization. For now legacy per default.
  16448. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16449. }
  16450. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16451. get: function () {
  16452. return Scene._FOGMODE_NONE;
  16453. },
  16454. enumerable: true,
  16455. configurable: true
  16456. });
  16457. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16458. get: function () {
  16459. return Scene._FOGMODE_EXP;
  16460. },
  16461. enumerable: true,
  16462. configurable: true
  16463. });
  16464. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16465. get: function () {
  16466. return Scene._FOGMODE_EXP2;
  16467. },
  16468. enumerable: true,
  16469. configurable: true
  16470. });
  16471. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16472. get: function () {
  16473. return Scene._FOGMODE_LINEAR;
  16474. },
  16475. enumerable: true,
  16476. configurable: true
  16477. });
  16478. Object.defineProperty(Scene.prototype, "onDispose", {
  16479. set: function (callback) {
  16480. if (this._onDisposeObserver) {
  16481. this.onDisposeObservable.remove(this._onDisposeObserver);
  16482. }
  16483. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16484. },
  16485. enumerable: true,
  16486. configurable: true
  16487. });
  16488. Object.defineProperty(Scene.prototype, "beforeRender", {
  16489. set: function (callback) {
  16490. if (this._onBeforeRenderObserver) {
  16491. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16492. }
  16493. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16494. },
  16495. enumerable: true,
  16496. configurable: true
  16497. });
  16498. Object.defineProperty(Scene.prototype, "afterRender", {
  16499. set: function (callback) {
  16500. if (this._onAfterRenderObserver) {
  16501. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16502. }
  16503. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16504. },
  16505. enumerable: true,
  16506. configurable: true
  16507. });
  16508. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16509. set: function (callback) {
  16510. if (this._onBeforeCameraRenderObserver) {
  16511. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16512. }
  16513. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16514. },
  16515. enumerable: true,
  16516. configurable: true
  16517. });
  16518. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16519. set: function (callback) {
  16520. if (this._onAfterCameraRenderObserver) {
  16521. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16522. }
  16523. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16524. },
  16525. enumerable: true,
  16526. configurable: true
  16527. });
  16528. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16529. get: function () {
  16530. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16531. },
  16532. enumerable: true,
  16533. configurable: true
  16534. });
  16535. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16536. get: function () {
  16537. if (!this._defaultMaterial) {
  16538. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16539. }
  16540. return this._defaultMaterial;
  16541. },
  16542. enumerable: true,
  16543. configurable: true
  16544. });
  16545. Object.defineProperty(Scene.prototype, "debugLayer", {
  16546. // Properties
  16547. get: function () {
  16548. if (!this._debugLayer) {
  16549. this._debugLayer = new BABYLON.DebugLayer(this);
  16550. }
  16551. return this._debugLayer;
  16552. },
  16553. enumerable: true,
  16554. configurable: true
  16555. });
  16556. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16557. get: function () {
  16558. return this._workerCollisions;
  16559. },
  16560. set: function (enabled) {
  16561. enabled = (enabled && !!Worker);
  16562. this._workerCollisions = enabled;
  16563. if (this.collisionCoordinator) {
  16564. this.collisionCoordinator.destroy();
  16565. }
  16566. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16567. this.collisionCoordinator.init(this);
  16568. },
  16569. enumerable: true,
  16570. configurable: true
  16571. });
  16572. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16573. get: function () {
  16574. return this._selectionOctree;
  16575. },
  16576. enumerable: true,
  16577. configurable: true
  16578. });
  16579. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16580. /**
  16581. * The mesh that is currently under the pointer.
  16582. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16583. */
  16584. get: function () {
  16585. return this._pointerOverMesh;
  16586. },
  16587. enumerable: true,
  16588. configurable: true
  16589. });
  16590. Object.defineProperty(Scene.prototype, "pointerX", {
  16591. /**
  16592. * Current on-screen X position of the pointer
  16593. * @return {number} X position of the pointer
  16594. */
  16595. get: function () {
  16596. return this._pointerX;
  16597. },
  16598. enumerable: true,
  16599. configurable: true
  16600. });
  16601. Object.defineProperty(Scene.prototype, "pointerY", {
  16602. /**
  16603. * Current on-screen Y position of the pointer
  16604. * @return {number} Y position of the pointer
  16605. */
  16606. get: function () {
  16607. return this._pointerY;
  16608. },
  16609. enumerable: true,
  16610. configurable: true
  16611. });
  16612. Scene.prototype.getCachedMaterial = function () {
  16613. return this._cachedMaterial;
  16614. };
  16615. Scene.prototype.getBoundingBoxRenderer = function () {
  16616. return this._boundingBoxRenderer;
  16617. };
  16618. Scene.prototype.getOutlineRenderer = function () {
  16619. return this._outlineRenderer;
  16620. };
  16621. Scene.prototype.getEngine = function () {
  16622. return this._engine;
  16623. };
  16624. Scene.prototype.getTotalVertices = function () {
  16625. return this._totalVertices.current;
  16626. };
  16627. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16628. get: function () {
  16629. return this._totalVertices;
  16630. },
  16631. enumerable: true,
  16632. configurable: true
  16633. });
  16634. Scene.prototype.getActiveIndices = function () {
  16635. return this._activeIndices.current;
  16636. };
  16637. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16638. get: function () {
  16639. return this._activeIndices;
  16640. },
  16641. enumerable: true,
  16642. configurable: true
  16643. });
  16644. Scene.prototype.getActiveParticles = function () {
  16645. return this._activeParticles.current;
  16646. };
  16647. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16648. get: function () {
  16649. return this._activeParticles;
  16650. },
  16651. enumerable: true,
  16652. configurable: true
  16653. });
  16654. Scene.prototype.getActiveBones = function () {
  16655. return this._activeBones.current;
  16656. };
  16657. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16658. get: function () {
  16659. return this._activeBones;
  16660. },
  16661. enumerable: true,
  16662. configurable: true
  16663. });
  16664. // Stats
  16665. Scene.prototype.getLastFrameDuration = function () {
  16666. return this._lastFrameDuration.current;
  16667. };
  16668. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16669. get: function () {
  16670. return this._lastFrameDuration;
  16671. },
  16672. enumerable: true,
  16673. configurable: true
  16674. });
  16675. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16676. return this._evaluateActiveMeshesDuration.current;
  16677. };
  16678. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16679. get: function () {
  16680. return this._evaluateActiveMeshesDuration;
  16681. },
  16682. enumerable: true,
  16683. configurable: true
  16684. });
  16685. Scene.prototype.getActiveMeshes = function () {
  16686. return this._activeMeshes;
  16687. };
  16688. Scene.prototype.getRenderTargetsDuration = function () {
  16689. return this._renderTargetsDuration.current;
  16690. };
  16691. Scene.prototype.getRenderDuration = function () {
  16692. return this._renderDuration.current;
  16693. };
  16694. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16695. get: function () {
  16696. return this._renderDuration;
  16697. },
  16698. enumerable: true,
  16699. configurable: true
  16700. });
  16701. Scene.prototype.getParticlesDuration = function () {
  16702. return this._particlesDuration.current;
  16703. };
  16704. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16705. get: function () {
  16706. return this._particlesDuration;
  16707. },
  16708. enumerable: true,
  16709. configurable: true
  16710. });
  16711. Scene.prototype.getSpritesDuration = function () {
  16712. return this._spritesDuration.current;
  16713. };
  16714. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16715. get: function () {
  16716. return this._spritesDuration;
  16717. },
  16718. enumerable: true,
  16719. configurable: true
  16720. });
  16721. Scene.prototype.getAnimationRatio = function () {
  16722. return this._animationRatio;
  16723. };
  16724. Scene.prototype.getRenderId = function () {
  16725. return this._renderId;
  16726. };
  16727. Scene.prototype.incrementRenderId = function () {
  16728. this._renderId++;
  16729. };
  16730. Scene.prototype._updatePointerPosition = function (evt) {
  16731. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16732. this._pointerX = evt.clientX - canvasRect.left;
  16733. this._pointerY = evt.clientY - canvasRect.top;
  16734. this._unTranslatedPointerX = this._pointerX;
  16735. this._unTranslatedPointerY = this._pointerY;
  16736. if (this.cameraToUseForPointers) {
  16737. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  16738. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  16739. }
  16740. };
  16741. // Pointers handling
  16742. /**
  16743. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  16744. * @param attachUp defines if you want to attach events to pointerup
  16745. * @param attachDown defines if you want to attach events to pointerdown
  16746. * @param attachMove defines if you want to attach events to pointermove
  16747. */
  16748. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  16749. var _this = this;
  16750. if (attachUp === void 0) { attachUp = true; }
  16751. if (attachDown === void 0) { attachDown = true; }
  16752. if (attachMove === void 0) { attachMove = true; }
  16753. var spritePredicate = function (sprite) {
  16754. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  16755. };
  16756. this._onPointerMove = function (evt) {
  16757. _this._updatePointerPosition(evt);
  16758. // PreObservable support
  16759. if (_this.onPrePointerObservable.hasObservers()) {
  16760. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16761. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16762. _this.onPrePointerObservable.notifyObservers(pi, type);
  16763. if (pi.skipOnPointerObservable) {
  16764. return;
  16765. }
  16766. }
  16767. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16768. return;
  16769. }
  16770. var canvas = _this._engine.getRenderingCanvas();
  16771. if (!_this.pointerMovePredicate) {
  16772. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  16773. }
  16774. // Meshes
  16775. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  16776. if (pickResult.hit && pickResult.pickedMesh) {
  16777. _this.setPointerOverSprite(null);
  16778. _this.setPointerOverMesh(pickResult.pickedMesh);
  16779. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  16780. canvas.style.cursor = _this.hoverCursor;
  16781. }
  16782. else {
  16783. canvas.style.cursor = "";
  16784. }
  16785. }
  16786. else {
  16787. _this.setPointerOverMesh(null);
  16788. // Sprites
  16789. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16790. if (pickResult.hit && pickResult.pickedSprite) {
  16791. canvas.style.cursor = _this.hoverCursor;
  16792. _this.setPointerOverSprite(pickResult.pickedSprite);
  16793. }
  16794. else {
  16795. _this.setPointerOverSprite(null);
  16796. // Restore pointer
  16797. canvas.style.cursor = "";
  16798. }
  16799. }
  16800. if (_this.onPointerMove) {
  16801. _this.onPointerMove(evt, pickResult);
  16802. }
  16803. if (_this.onPointerObservable.hasObservers()) {
  16804. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  16805. var pi = new PointerInfo(type, evt, pickResult);
  16806. _this.onPointerObservable.notifyObservers(pi, type);
  16807. }
  16808. };
  16809. this._onPointerDown = function (evt) {
  16810. _this._updatePointerPosition(evt);
  16811. // PreObservable support
  16812. if (_this.onPrePointerObservable.hasObservers()) {
  16813. var type = PointerEventTypes.POINTERDOWN;
  16814. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16815. _this.onPrePointerObservable.notifyObservers(pi, type);
  16816. if (pi.skipOnPointerObservable) {
  16817. return;
  16818. }
  16819. }
  16820. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16821. return;
  16822. }
  16823. _this._startingPointerPosition.x = _this._pointerX;
  16824. _this._startingPointerPosition.y = _this._pointerY;
  16825. _this._startingPointerTime = new Date().getTime();
  16826. if (!_this.pointerDownPredicate) {
  16827. _this.pointerDownPredicate = function (mesh) {
  16828. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || mesh.actionManager.hasPointerTriggers);
  16829. };
  16830. }
  16831. // Meshes
  16832. _this._pickedDownMesh = null;
  16833. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  16834. if (pickResult.hit && pickResult.pickedMesh) {
  16835. if (pickResult.pickedMesh.actionManager) {
  16836. _this._pickedDownMesh = pickResult.pickedMesh;
  16837. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  16838. switch (evt.button) {
  16839. case 0:
  16840. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16841. break;
  16842. case 1:
  16843. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16844. break;
  16845. case 2:
  16846. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16847. break;
  16848. }
  16849. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16850. }
  16851. if (pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  16852. var that = _this;
  16853. window.setTimeout(function () {
  16854. 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);
  16855. if (pickResult.hit && pickResult.pickedMesh) {
  16856. if (pickResult.pickedMesh.actionManager) {
  16857. 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)) {
  16858. that._startingPointerTime = 0;
  16859. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16860. }
  16861. }
  16862. }
  16863. }, BABYLON.ActionManager.LongPressDelay);
  16864. }
  16865. }
  16866. }
  16867. if (_this.onPointerDown) {
  16868. _this.onPointerDown(evt, pickResult);
  16869. }
  16870. if (_this.onPointerObservable.hasObservers()) {
  16871. var type = PointerEventTypes.POINTERDOWN;
  16872. var pi = new PointerInfo(type, evt, pickResult);
  16873. _this.onPointerObservable.notifyObservers(pi, type);
  16874. }
  16875. // Sprites
  16876. _this._pickedDownSprite = null;
  16877. if (_this.spriteManagers.length > 0) {
  16878. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16879. if (pickResult.hit && pickResult.pickedSprite) {
  16880. if (pickResult.pickedSprite.actionManager) {
  16881. _this._pickedDownSprite = pickResult.pickedSprite;
  16882. switch (evt.button) {
  16883. case 0:
  16884. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16885. break;
  16886. case 1:
  16887. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16888. break;
  16889. case 2:
  16890. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16891. break;
  16892. }
  16893. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16894. }
  16895. }
  16896. }
  16897. };
  16898. this._onPointerUp = function (evt) {
  16899. _this._updatePointerPosition(evt);
  16900. // PreObservable support
  16901. if (_this.onPrePointerObservable.hasObservers()) {
  16902. var type = PointerEventTypes.POINTERUP;
  16903. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  16904. _this.onPrePointerObservable.notifyObservers(pi, type);
  16905. if (pi.skipOnPointerObservable) {
  16906. return;
  16907. }
  16908. }
  16909. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  16910. return;
  16911. }
  16912. if (!_this.pointerUpPredicate) {
  16913. _this.pointerUpPredicate = function (mesh) {
  16914. return mesh.isPickable && mesh.isVisible && mesh.isReady() && (!mesh.actionManager || (mesh.actionManager.hasPickTriggers || mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)));
  16915. };
  16916. }
  16917. // Meshes
  16918. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  16919. if (pickResult.hit && pickResult.pickedMesh) {
  16920. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  16921. if (_this.onPointerPick) {
  16922. _this.onPointerPick(evt, pickResult);
  16923. }
  16924. if (_this.onPointerObservable.hasObservers()) {
  16925. var type = PointerEventTypes.POINTERPICK;
  16926. var pi = new PointerInfo(type, evt, pickResult);
  16927. _this.onPointerObservable.notifyObservers(pi, type);
  16928. }
  16929. }
  16930. if (pickResult.pickedMesh.actionManager) {
  16931. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16932. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16933. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  16934. }
  16935. }
  16936. }
  16937. if (_this._pickedDownMesh && _this._pickedDownMesh !== pickResult.pickedMesh) {
  16938. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  16939. }
  16940. if (_this.onPointerUp) {
  16941. _this.onPointerUp(evt, pickResult);
  16942. }
  16943. if (_this.onPointerObservable.hasObservers()) {
  16944. var type = PointerEventTypes.POINTERUP;
  16945. var pi = new PointerInfo(type, evt, pickResult);
  16946. _this.onPointerObservable.notifyObservers(pi, type);
  16947. }
  16948. _this._startingPointerTime = 0;
  16949. // Sprites
  16950. if (_this.spriteManagers.length > 0) {
  16951. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  16952. if (pickResult.hit && pickResult.pickedSprite) {
  16953. if (pickResult.pickedSprite.actionManager) {
  16954. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16955. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  16956. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  16957. }
  16958. }
  16959. }
  16960. if (_this._pickedDownSprite && _this._pickedDownSprite !== pickResult.pickedSprite) {
  16961. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  16962. }
  16963. }
  16964. };
  16965. this._onKeyDown = function (evt) {
  16966. if (_this.actionManager) {
  16967. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16968. }
  16969. };
  16970. this._onKeyUp = function (evt) {
  16971. if (_this.actionManager) {
  16972. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  16973. }
  16974. };
  16975. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16976. var canvas = this._engine.getRenderingCanvas();
  16977. if (attachMove) {
  16978. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  16979. // Wheel
  16980. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  16981. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  16982. }
  16983. if (attachDown) {
  16984. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  16985. }
  16986. if (attachUp) {
  16987. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  16988. }
  16989. canvas.tabIndex = 1;
  16990. canvas.addEventListener("keydown", this._onKeyDown, false);
  16991. canvas.addEventListener("keyup", this._onKeyUp, false);
  16992. };
  16993. Scene.prototype.detachControl = function () {
  16994. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  16995. var canvas = this._engine.getRenderingCanvas();
  16996. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  16997. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  16998. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  16999. // Wheel
  17000. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17001. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17002. canvas.removeEventListener("keydown", this._onKeyDown);
  17003. canvas.removeEventListener("keyup", this._onKeyUp);
  17004. };
  17005. // Ready
  17006. Scene.prototype.isReady = function () {
  17007. if (this._pendingData.length > 0) {
  17008. return false;
  17009. }
  17010. var index;
  17011. for (index = 0; index < this._geometries.length; index++) {
  17012. var geometry = this._geometries[index];
  17013. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17014. return false;
  17015. }
  17016. }
  17017. for (index = 0; index < this.meshes.length; index++) {
  17018. var mesh = this.meshes[index];
  17019. if (!mesh.isReady()) {
  17020. return false;
  17021. }
  17022. var mat = mesh.material;
  17023. if (mat) {
  17024. if (!mat.isReady(mesh)) {
  17025. return false;
  17026. }
  17027. }
  17028. }
  17029. return true;
  17030. };
  17031. Scene.prototype.resetCachedMaterial = function () {
  17032. this._cachedMaterial = null;
  17033. };
  17034. Scene.prototype.registerBeforeRender = function (func) {
  17035. this.onBeforeRenderObservable.add(func);
  17036. };
  17037. Scene.prototype.unregisterBeforeRender = function (func) {
  17038. this.onBeforeRenderObservable.removeCallback(func);
  17039. };
  17040. Scene.prototype.registerAfterRender = function (func) {
  17041. this.onAfterRenderObservable.add(func);
  17042. };
  17043. Scene.prototype.unregisterAfterRender = function (func) {
  17044. this.onAfterRenderObservable.removeCallback(func);
  17045. };
  17046. Scene.prototype._addPendingData = function (data) {
  17047. this._pendingData.push(data);
  17048. };
  17049. Scene.prototype._removePendingData = function (data) {
  17050. var index = this._pendingData.indexOf(data);
  17051. if (index !== -1) {
  17052. this._pendingData.splice(index, 1);
  17053. }
  17054. };
  17055. Scene.prototype.getWaitingItemsCount = function () {
  17056. return this._pendingData.length;
  17057. };
  17058. /**
  17059. * Registers a function to be executed when the scene is ready.
  17060. * @param {Function} func - the function to be executed.
  17061. */
  17062. Scene.prototype.executeWhenReady = function (func) {
  17063. var _this = this;
  17064. this.onReadyObservable.add(func);
  17065. if (this._executeWhenReadyTimeoutId !== -1) {
  17066. return;
  17067. }
  17068. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17069. _this._checkIsReady();
  17070. }, 150);
  17071. };
  17072. Scene.prototype._checkIsReady = function () {
  17073. var _this = this;
  17074. if (this.isReady()) {
  17075. this.onReadyObservable.notifyObservers(this);
  17076. this.onReadyObservable.clear();
  17077. this._executeWhenReadyTimeoutId = -1;
  17078. return;
  17079. }
  17080. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17081. _this._checkIsReady();
  17082. }, 150);
  17083. };
  17084. // Animations
  17085. /**
  17086. * Will start the animation sequence of a given target
  17087. * @param target - the target
  17088. * @param {number} from - from which frame should animation start
  17089. * @param {number} to - till which frame should animation run.
  17090. * @param {boolean} [loop] - should the animation loop
  17091. * @param {number} [speedRatio] - the speed in which to run the animation
  17092. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17093. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17094. * @return {BABYLON.Animatable} the animatable object created for this animation
  17095. * @see BABYLON.Animatable
  17096. * @see http://doc.babylonjs.com/page.php?p=22081
  17097. */
  17098. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17099. if (speedRatio === void 0) { speedRatio = 1.0; }
  17100. this.stopAnimation(target);
  17101. if (!animatable) {
  17102. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17103. }
  17104. // Local animations
  17105. if (target.animations) {
  17106. animatable.appendAnimations(target, target.animations);
  17107. }
  17108. // Children animations
  17109. if (target.getAnimatables) {
  17110. var animatables = target.getAnimatables();
  17111. for (var index = 0; index < animatables.length; index++) {
  17112. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17113. }
  17114. }
  17115. animatable.reset();
  17116. return animatable;
  17117. };
  17118. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17119. if (speedRatio === undefined) {
  17120. speedRatio = 1.0;
  17121. }
  17122. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17123. return animatable;
  17124. };
  17125. Scene.prototype.getAnimatableByTarget = function (target) {
  17126. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17127. if (this._activeAnimatables[index].target === target) {
  17128. return this._activeAnimatables[index];
  17129. }
  17130. }
  17131. return null;
  17132. };
  17133. Object.defineProperty(Scene.prototype, "Animatables", {
  17134. get: function () {
  17135. return this._activeAnimatables;
  17136. },
  17137. enumerable: true,
  17138. configurable: true
  17139. });
  17140. /**
  17141. * Will stop the animation of the given target
  17142. * @param target - the target
  17143. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17144. * @see beginAnimation
  17145. */
  17146. Scene.prototype.stopAnimation = function (target, animationName) {
  17147. var animatable = this.getAnimatableByTarget(target);
  17148. if (animatable) {
  17149. animatable.stop(animationName);
  17150. }
  17151. };
  17152. Scene.prototype._animate = function () {
  17153. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17154. return;
  17155. }
  17156. if (!this._animationStartDate) {
  17157. if (this._pendingData.length > 0) {
  17158. return;
  17159. }
  17160. this._animationStartDate = BABYLON.Tools.Now;
  17161. }
  17162. // Getting time
  17163. var now = BABYLON.Tools.Now;
  17164. var delay = now - this._animationStartDate;
  17165. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17166. this._activeAnimatables[index]._animate(delay);
  17167. }
  17168. };
  17169. // Matrix
  17170. Scene.prototype.getViewMatrix = function () {
  17171. return this._viewMatrix;
  17172. };
  17173. Scene.prototype.getProjectionMatrix = function () {
  17174. return this._projectionMatrix;
  17175. };
  17176. Scene.prototype.getTransformMatrix = function () {
  17177. return this._transformMatrix;
  17178. };
  17179. Scene.prototype.setTransformMatrix = function (view, projection) {
  17180. this._viewMatrix = view;
  17181. this._projectionMatrix = projection;
  17182. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17183. // Update frustum
  17184. if (!this._frustumPlanes) {
  17185. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17186. }
  17187. else {
  17188. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17189. }
  17190. };
  17191. // Methods
  17192. Scene.prototype.addMesh = function (newMesh) {
  17193. newMesh.uniqueId = this._uniqueIdCounter++;
  17194. var position = this.meshes.push(newMesh);
  17195. //notify the collision coordinator
  17196. this.collisionCoordinator.onMeshAdded(newMesh);
  17197. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17198. };
  17199. Scene.prototype.removeMesh = function (toRemove) {
  17200. var index = this.meshes.indexOf(toRemove);
  17201. if (index !== -1) {
  17202. // Remove from the scene if mesh found
  17203. this.meshes.splice(index, 1);
  17204. }
  17205. //notify the collision coordinator
  17206. this.collisionCoordinator.onMeshRemoved(toRemove);
  17207. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17208. return index;
  17209. };
  17210. Scene.prototype.removeSkeleton = function (toRemove) {
  17211. var index = this.skeletons.indexOf(toRemove);
  17212. if (index !== -1) {
  17213. // Remove from the scene if mesh found
  17214. this.skeletons.splice(index, 1);
  17215. }
  17216. return index;
  17217. };
  17218. Scene.prototype.removeLight = function (toRemove) {
  17219. var index = this.lights.indexOf(toRemove);
  17220. if (index !== -1) {
  17221. // Remove from the scene if mesh found
  17222. this.lights.splice(index, 1);
  17223. }
  17224. this.onLightRemovedObservable.notifyObservers(toRemove);
  17225. return index;
  17226. };
  17227. Scene.prototype.removeCamera = function (toRemove) {
  17228. var index = this.cameras.indexOf(toRemove);
  17229. if (index !== -1) {
  17230. // Remove from the scene if mesh found
  17231. this.cameras.splice(index, 1);
  17232. }
  17233. // Remove from activeCameras
  17234. var index2 = this.activeCameras.indexOf(toRemove);
  17235. if (index2 !== -1) {
  17236. // Remove from the scene if mesh found
  17237. this.activeCameras.splice(index2, 1);
  17238. }
  17239. // Reset the activeCamera
  17240. if (this.activeCamera === toRemove) {
  17241. if (this.cameras.length > 0) {
  17242. this.activeCamera = this.cameras[0];
  17243. }
  17244. else {
  17245. this.activeCamera = null;
  17246. }
  17247. }
  17248. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17249. return index;
  17250. };
  17251. Scene.prototype.addLight = function (newLight) {
  17252. newLight.uniqueId = this._uniqueIdCounter++;
  17253. var position = this.lights.push(newLight);
  17254. this.onNewLightAddedObservable.notifyObservers(newLight);
  17255. };
  17256. Scene.prototype.addCamera = function (newCamera) {
  17257. newCamera.uniqueId = this._uniqueIdCounter++;
  17258. var position = this.cameras.push(newCamera);
  17259. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17260. };
  17261. /**
  17262. * Switch active camera
  17263. * @param {Camera} newCamera - new active camera
  17264. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17265. */
  17266. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17267. if (attachControl === void 0) { attachControl = true; }
  17268. var canvas = this._engine.getRenderingCanvas();
  17269. this.activeCamera.detachControl(canvas);
  17270. this.activeCamera = newCamera;
  17271. if (attachControl) {
  17272. newCamera.attachControl(canvas);
  17273. }
  17274. };
  17275. /**
  17276. * sets the active camera of the scene using its ID
  17277. * @param {string} id - the camera's ID
  17278. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17279. * @see activeCamera
  17280. */
  17281. Scene.prototype.setActiveCameraByID = function (id) {
  17282. var camera = this.getCameraByID(id);
  17283. if (camera) {
  17284. this.activeCamera = camera;
  17285. return camera;
  17286. }
  17287. return null;
  17288. };
  17289. /**
  17290. * sets the active camera of the scene using its name
  17291. * @param {string} name - the camera's name
  17292. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17293. * @see activeCamera
  17294. */
  17295. Scene.prototype.setActiveCameraByName = function (name) {
  17296. var camera = this.getCameraByName(name);
  17297. if (camera) {
  17298. this.activeCamera = camera;
  17299. return camera;
  17300. }
  17301. return null;
  17302. };
  17303. /**
  17304. * get a material using its id
  17305. * @param {string} the material's ID
  17306. * @return {BABYLON.Material|null} the material or null if none found.
  17307. */
  17308. Scene.prototype.getMaterialByID = function (id) {
  17309. for (var index = 0; index < this.materials.length; index++) {
  17310. if (this.materials[index].id === id) {
  17311. return this.materials[index];
  17312. }
  17313. }
  17314. return null;
  17315. };
  17316. /**
  17317. * get a material using its name
  17318. * @param {string} the material's name
  17319. * @return {BABYLON.Material|null} the material or null if none found.
  17320. */
  17321. Scene.prototype.getMaterialByName = function (name) {
  17322. for (var index = 0; index < this.materials.length; index++) {
  17323. if (this.materials[index].name === name) {
  17324. return this.materials[index];
  17325. }
  17326. }
  17327. return null;
  17328. };
  17329. Scene.prototype.getLensFlareSystemByName = function (name) {
  17330. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17331. if (this.lensFlareSystems[index].name === name) {
  17332. return this.lensFlareSystems[index];
  17333. }
  17334. }
  17335. return null;
  17336. };
  17337. Scene.prototype.getLensFlareSystemByID = function (id) {
  17338. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17339. if (this.lensFlareSystems[index].id === id) {
  17340. return this.lensFlareSystems[index];
  17341. }
  17342. }
  17343. return null;
  17344. };
  17345. Scene.prototype.getCameraByID = function (id) {
  17346. for (var index = 0; index < this.cameras.length; index++) {
  17347. if (this.cameras[index].id === id) {
  17348. return this.cameras[index];
  17349. }
  17350. }
  17351. return null;
  17352. };
  17353. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17354. for (var index = 0; index < this.cameras.length; index++) {
  17355. if (this.cameras[index].uniqueId === uniqueId) {
  17356. return this.cameras[index];
  17357. }
  17358. }
  17359. return null;
  17360. };
  17361. /**
  17362. * get a camera using its name
  17363. * @param {string} the camera's name
  17364. * @return {BABYLON.Camera|null} the camera or null if none found.
  17365. */
  17366. Scene.prototype.getCameraByName = function (name) {
  17367. for (var index = 0; index < this.cameras.length; index++) {
  17368. if (this.cameras[index].name === name) {
  17369. return this.cameras[index];
  17370. }
  17371. }
  17372. return null;
  17373. };
  17374. /**
  17375. * get a bone using its id
  17376. * @param {string} the bone's id
  17377. * @return {BABYLON.Bone|null} the bone or null if not found
  17378. */
  17379. Scene.prototype.getBoneByID = function (id) {
  17380. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17381. var skeleton = this.skeletons[skeletonIndex];
  17382. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17383. if (skeleton.bones[boneIndex].id === id) {
  17384. return skeleton.bones[boneIndex];
  17385. }
  17386. }
  17387. }
  17388. return null;
  17389. };
  17390. /**
  17391. * get a bone using its id
  17392. * @param {string} the bone's name
  17393. * @return {BABYLON.Bone|null} the bone or null if not found
  17394. */
  17395. Scene.prototype.getBoneByName = function (name) {
  17396. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17397. var skeleton = this.skeletons[skeletonIndex];
  17398. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17399. if (skeleton.bones[boneIndex].name === name) {
  17400. return skeleton.bones[boneIndex];
  17401. }
  17402. }
  17403. }
  17404. return null;
  17405. };
  17406. /**
  17407. * get a light node using its name
  17408. * @param {string} the light's name
  17409. * @return {BABYLON.Light|null} the light or null if none found.
  17410. */
  17411. Scene.prototype.getLightByName = function (name) {
  17412. for (var index = 0; index < this.lights.length; index++) {
  17413. if (this.lights[index].name === name) {
  17414. return this.lights[index];
  17415. }
  17416. }
  17417. return null;
  17418. };
  17419. /**
  17420. * get a light node using its ID
  17421. * @param {string} the light's id
  17422. * @return {BABYLON.Light|null} the light or null if none found.
  17423. */
  17424. Scene.prototype.getLightByID = function (id) {
  17425. for (var index = 0; index < this.lights.length; index++) {
  17426. if (this.lights[index].id === id) {
  17427. return this.lights[index];
  17428. }
  17429. }
  17430. return null;
  17431. };
  17432. /**
  17433. * get a light node using its scene-generated unique ID
  17434. * @param {number} the light's unique id
  17435. * @return {BABYLON.Light|null} the light or null if none found.
  17436. */
  17437. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17438. for (var index = 0; index < this.lights.length; index++) {
  17439. if (this.lights[index].uniqueId === uniqueId) {
  17440. return this.lights[index];
  17441. }
  17442. }
  17443. return null;
  17444. };
  17445. /**
  17446. * get a particle system by id
  17447. * @param id {number} the particle system id
  17448. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17449. */
  17450. Scene.prototype.getParticleSystemByID = function (id) {
  17451. for (var index = 0; index < this.particleSystems.length; index++) {
  17452. if (this.particleSystems[index].id === id) {
  17453. return this.particleSystems[index];
  17454. }
  17455. }
  17456. return null;
  17457. };
  17458. /**
  17459. * get a geometry using its ID
  17460. * @param {string} the geometry's id
  17461. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17462. */
  17463. Scene.prototype.getGeometryByID = function (id) {
  17464. for (var index = 0; index < this._geometries.length; index++) {
  17465. if (this._geometries[index].id === id) {
  17466. return this._geometries[index];
  17467. }
  17468. }
  17469. return null;
  17470. };
  17471. /**
  17472. * add a new geometry to this scene.
  17473. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17474. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17475. * @return {boolean} was the geometry added or not
  17476. */
  17477. Scene.prototype.pushGeometry = function (geometry, force) {
  17478. if (!force && this.getGeometryByID(geometry.id)) {
  17479. return false;
  17480. }
  17481. this._geometries.push(geometry);
  17482. //notify the collision coordinator
  17483. this.collisionCoordinator.onGeometryAdded(geometry);
  17484. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17485. return true;
  17486. };
  17487. /**
  17488. * Removes an existing geometry
  17489. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17490. * @return {boolean} was the geometry removed or not
  17491. */
  17492. Scene.prototype.removeGeometry = function (geometry) {
  17493. var index = this._geometries.indexOf(geometry);
  17494. if (index > -1) {
  17495. this._geometries.splice(index, 1);
  17496. //notify the collision coordinator
  17497. this.collisionCoordinator.onGeometryDeleted(geometry);
  17498. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17499. return true;
  17500. }
  17501. return false;
  17502. };
  17503. Scene.prototype.getGeometries = function () {
  17504. return this._geometries;
  17505. };
  17506. /**
  17507. * Get the first added mesh found of a given ID
  17508. * @param {string} id - the id to search for
  17509. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17510. */
  17511. Scene.prototype.getMeshByID = function (id) {
  17512. for (var index = 0; index < this.meshes.length; index++) {
  17513. if (this.meshes[index].id === id) {
  17514. return this.meshes[index];
  17515. }
  17516. }
  17517. return null;
  17518. };
  17519. Scene.prototype.getMeshesByID = function (id) {
  17520. return this.meshes.filter(function (m) {
  17521. return m.id === id;
  17522. });
  17523. };
  17524. /**
  17525. * Get a mesh with its auto-generated unique id
  17526. * @param {number} uniqueId - the unique id to search for
  17527. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17528. */
  17529. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17530. for (var index = 0; index < this.meshes.length; index++) {
  17531. if (this.meshes[index].uniqueId === uniqueId) {
  17532. return this.meshes[index];
  17533. }
  17534. }
  17535. return null;
  17536. };
  17537. /**
  17538. * Get a the last added mesh found of a given ID
  17539. * @param {string} id - the id to search for
  17540. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17541. */
  17542. Scene.prototype.getLastMeshByID = function (id) {
  17543. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17544. if (this.meshes[index].id === id) {
  17545. return this.meshes[index];
  17546. }
  17547. }
  17548. return null;
  17549. };
  17550. /**
  17551. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17552. * @param {string} id - the id to search for
  17553. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17554. */
  17555. Scene.prototype.getLastEntryByID = function (id) {
  17556. var index;
  17557. for (index = this.meshes.length - 1; index >= 0; index--) {
  17558. if (this.meshes[index].id === id) {
  17559. return this.meshes[index];
  17560. }
  17561. }
  17562. for (index = this.cameras.length - 1; index >= 0; index--) {
  17563. if (this.cameras[index].id === id) {
  17564. return this.cameras[index];
  17565. }
  17566. }
  17567. for (index = this.lights.length - 1; index >= 0; index--) {
  17568. if (this.lights[index].id === id) {
  17569. return this.lights[index];
  17570. }
  17571. }
  17572. return null;
  17573. };
  17574. Scene.prototype.getNodeByID = function (id) {
  17575. var mesh = this.getMeshByID(id);
  17576. if (mesh) {
  17577. return mesh;
  17578. }
  17579. var light = this.getLightByID(id);
  17580. if (light) {
  17581. return light;
  17582. }
  17583. var camera = this.getCameraByID(id);
  17584. if (camera) {
  17585. return camera;
  17586. }
  17587. var bone = this.getBoneByID(id);
  17588. return bone;
  17589. };
  17590. Scene.prototype.getNodeByName = function (name) {
  17591. var mesh = this.getMeshByName(name);
  17592. if (mesh) {
  17593. return mesh;
  17594. }
  17595. var light = this.getLightByName(name);
  17596. if (light) {
  17597. return light;
  17598. }
  17599. var camera = this.getCameraByName(name);
  17600. if (camera) {
  17601. return camera;
  17602. }
  17603. var bone = this.getBoneByName(name);
  17604. return bone;
  17605. };
  17606. Scene.prototype.getMeshByName = function (name) {
  17607. for (var index = 0; index < this.meshes.length; index++) {
  17608. if (this.meshes[index].name === name) {
  17609. return this.meshes[index];
  17610. }
  17611. }
  17612. return null;
  17613. };
  17614. Scene.prototype.getSoundByName = function (name) {
  17615. var index;
  17616. if (BABYLON.AudioEngine) {
  17617. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  17618. if (this.mainSoundTrack.soundCollection[index].name === name) {
  17619. return this.mainSoundTrack.soundCollection[index];
  17620. }
  17621. }
  17622. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  17623. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  17624. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  17625. return this.soundTracks[sdIndex].soundCollection[index];
  17626. }
  17627. }
  17628. }
  17629. }
  17630. return null;
  17631. };
  17632. Scene.prototype.getLastSkeletonByID = function (id) {
  17633. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  17634. if (this.skeletons[index].id === id) {
  17635. return this.skeletons[index];
  17636. }
  17637. }
  17638. return null;
  17639. };
  17640. Scene.prototype.getSkeletonById = function (id) {
  17641. for (var index = 0; index < this.skeletons.length; index++) {
  17642. if (this.skeletons[index].id === id) {
  17643. return this.skeletons[index];
  17644. }
  17645. }
  17646. return null;
  17647. };
  17648. Scene.prototype.getSkeletonByName = function (name) {
  17649. for (var index = 0; index < this.skeletons.length; index++) {
  17650. if (this.skeletons[index].name === name) {
  17651. return this.skeletons[index];
  17652. }
  17653. }
  17654. return null;
  17655. };
  17656. Scene.prototype.isActiveMesh = function (mesh) {
  17657. return (this._activeMeshes.indexOf(mesh) !== -1);
  17658. };
  17659. Object.defineProperty(Scene.prototype, "uid", {
  17660. /**
  17661. * Return a unique id as a string which can serve as an identifier for the scene
  17662. */
  17663. get: function () {
  17664. if (!this._uid) {
  17665. this._uid = BABYLON.Tools.RandomId();
  17666. }
  17667. return this._uid;
  17668. },
  17669. enumerable: true,
  17670. configurable: true
  17671. });
  17672. /**
  17673. * Add an externaly attached data from its key.
  17674. * This method call will fail and return false, if such key already exists.
  17675. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17676. * @param key the unique key that identifies the data
  17677. * @param data the data object to associate to the key for this Engine instance
  17678. * @return true if no such key were already present and the data was added successfully, false otherwise
  17679. */
  17680. Scene.prototype.addExternalData = function (key, data) {
  17681. return this._externalData.add(key, data);
  17682. };
  17683. /**
  17684. * Get an externaly attached data from its key
  17685. * @param key the unique key that identifies the data
  17686. * @return the associated data, if present (can be null), or undefined if not present
  17687. */
  17688. Scene.prototype.getExternalData = function (key) {
  17689. return this._externalData.get(key);
  17690. };
  17691. /**
  17692. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17693. * @param key the unique key that identifies the data
  17694. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17695. * @return the associated data, can be null if the factory returned null.
  17696. */
  17697. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17698. return this._externalData.getOrAddWithFactory(key, factory);
  17699. };
  17700. /**
  17701. * Remove an externaly attached data from the Engine instance
  17702. * @param key the unique key that identifies the data
  17703. * @return true if the data was successfully removed, false if it doesn't exist
  17704. */
  17705. Scene.prototype.removeExternalData = function (key) {
  17706. return this._externalData.remove(key);
  17707. };
  17708. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  17709. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  17710. var material = subMesh.getMaterial();
  17711. if (mesh.showSubMeshesBoundingBox) {
  17712. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  17713. }
  17714. if (material) {
  17715. // Render targets
  17716. if (material.getRenderTargetTextures) {
  17717. if (this._processedMaterials.indexOf(material) === -1) {
  17718. this._processedMaterials.push(material);
  17719. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  17720. }
  17721. }
  17722. // Dispatch
  17723. this._activeIndices.addCount(subMesh.indexCount, false);
  17724. this._renderingManager.dispatch(subMesh);
  17725. }
  17726. }
  17727. };
  17728. Scene.prototype._isInIntermediateRendering = function () {
  17729. return this._intermediateRendering;
  17730. };
  17731. Scene.prototype._evaluateActiveMeshes = function () {
  17732. this.activeCamera._activeMeshes.reset();
  17733. this._activeMeshes.reset();
  17734. this._renderingManager.reset();
  17735. this._processedMaterials.reset();
  17736. this._activeParticleSystems.reset();
  17737. this._activeSkeletons.reset();
  17738. this._softwareSkinnedMeshes.reset();
  17739. this._boundingBoxRenderer.reset();
  17740. this._edgesRenderers.reset();
  17741. // Meshes
  17742. var meshes;
  17743. var len;
  17744. if (this._selectionOctree) {
  17745. var selection = this._selectionOctree.select(this._frustumPlanes);
  17746. meshes = selection.data;
  17747. len = selection.length;
  17748. }
  17749. else {
  17750. len = this.meshes.length;
  17751. meshes = this.meshes;
  17752. }
  17753. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  17754. var mesh = meshes[meshIndex];
  17755. if (mesh.isBlocked) {
  17756. continue;
  17757. }
  17758. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  17759. if (!mesh.isReady() || !mesh.isEnabled()) {
  17760. continue;
  17761. }
  17762. mesh.computeWorldMatrix();
  17763. // Intersections
  17764. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  17765. this._meshesForIntersections.pushNoDuplicate(mesh);
  17766. }
  17767. // Switch to current LOD
  17768. var meshLOD = mesh.getLOD(this.activeCamera);
  17769. if (!meshLOD) {
  17770. continue;
  17771. }
  17772. mesh._preActivate();
  17773. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  17774. this._activeMeshes.push(mesh);
  17775. this.activeCamera._activeMeshes.push(mesh);
  17776. mesh._activate(this._renderId);
  17777. this._activeMesh(mesh, meshLOD);
  17778. }
  17779. }
  17780. // Particle systems
  17781. this._particlesDuration.beginMonitoring();
  17782. var beforeParticlesDate = BABYLON.Tools.Now;
  17783. if (this.particlesEnabled) {
  17784. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  17785. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  17786. var particleSystem = this.particleSystems[particleIndex];
  17787. if (!particleSystem.isStarted()) {
  17788. continue;
  17789. }
  17790. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  17791. this._activeParticleSystems.push(particleSystem);
  17792. particleSystem.animate();
  17793. }
  17794. }
  17795. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  17796. }
  17797. this._particlesDuration.endMonitoring(false);
  17798. };
  17799. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  17800. if (mesh.skeleton && this.skeletonsEnabled) {
  17801. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  17802. mesh.skeleton.prepare();
  17803. }
  17804. if (!mesh.computeBonesUsingShaders) {
  17805. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  17806. }
  17807. }
  17808. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  17809. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  17810. }
  17811. if (sourceMesh._edgesRenderer) {
  17812. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  17813. }
  17814. if (mesh && mesh.subMeshes) {
  17815. // Submeshes Octrees
  17816. var len;
  17817. var subMeshes;
  17818. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  17819. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  17820. len = intersections.length;
  17821. subMeshes = intersections.data;
  17822. }
  17823. else {
  17824. subMeshes = mesh.subMeshes;
  17825. len = subMeshes.length;
  17826. }
  17827. for (var subIndex = 0; subIndex < len; subIndex++) {
  17828. var subMesh = subMeshes[subIndex];
  17829. this._evaluateSubMesh(subMesh, mesh);
  17830. }
  17831. }
  17832. };
  17833. Scene.prototype.updateTransformMatrix = function (force) {
  17834. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  17835. };
  17836. Scene.prototype._renderForCamera = function (camera) {
  17837. var engine = this._engine;
  17838. var startTime = BABYLON.Tools.Now;
  17839. this.activeCamera = camera;
  17840. if (!this.activeCamera)
  17841. throw new Error("Active camera not set");
  17842. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17843. // Viewport
  17844. engine.setViewport(this.activeCamera.viewport);
  17845. // Camera
  17846. this.resetCachedMaterial();
  17847. this._renderId++;
  17848. this.updateTransformMatrix();
  17849. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  17850. // Meshes
  17851. this._evaluateActiveMeshesDuration.beginMonitoring();
  17852. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  17853. this._evaluateActiveMeshes();
  17854. this._evaluateActiveMeshesDuration.endMonitoring(false);
  17855. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  17856. // Software skinning
  17857. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  17858. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  17859. mesh.applySkeleton(mesh.skeleton);
  17860. }
  17861. // Render targets
  17862. this._renderTargetsDuration.beginMonitoring();
  17863. var needsRestoreFrameBuffer = false;
  17864. var beforeRenderTargetDate = BABYLON.Tools.Now;
  17865. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  17866. this._intermediateRendering = true;
  17867. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17868. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  17869. var renderTarget = this._renderTargets.data[renderIndex];
  17870. if (renderTarget._shouldRender()) {
  17871. this._renderId++;
  17872. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  17873. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  17874. }
  17875. }
  17876. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  17877. this._intermediateRendering = false;
  17878. this._renderId++;
  17879. needsRestoreFrameBuffer = true; // Restore back buffer
  17880. }
  17881. // Render HighlightLayer Texture
  17882. var stencilState = this._engine.getStencilBuffer();
  17883. var renderhighlights = false;
  17884. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  17885. this._intermediateRendering = true;
  17886. for (var i = 0; i < this.highlightLayers.length; i++) {
  17887. var highlightLayer = this.highlightLayers[i];
  17888. if (highlightLayer.shouldRender() &&
  17889. (!highlightLayer.camera ||
  17890. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  17891. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  17892. renderhighlights = true;
  17893. var renderTarget = highlightLayer._mainTexture;
  17894. if (renderTarget._shouldRender()) {
  17895. this._renderId++;
  17896. renderTarget.render(false, false);
  17897. needsRestoreFrameBuffer = true;
  17898. }
  17899. }
  17900. }
  17901. this._intermediateRendering = false;
  17902. this._renderId++;
  17903. }
  17904. if (needsRestoreFrameBuffer) {
  17905. engine.restoreDefaultFramebuffer();
  17906. }
  17907. this._renderTargetsDuration.endMonitoring(false);
  17908. // Prepare Frame
  17909. this.postProcessManager._prepareFrame();
  17910. this._renderDuration.beginMonitoring();
  17911. // Backgrounds
  17912. var layerIndex;
  17913. var layer;
  17914. if (this.layers.length) {
  17915. engine.setDepthBuffer(false);
  17916. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17917. layer = this.layers[layerIndex];
  17918. if (layer.isBackground) {
  17919. layer.render();
  17920. }
  17921. }
  17922. engine.setDepthBuffer(true);
  17923. }
  17924. // Render
  17925. BABYLON.Tools.StartPerformanceCounter("Main render");
  17926. // Activate HighlightLayer stencil
  17927. if (renderhighlights) {
  17928. this._engine.setStencilBuffer(true);
  17929. }
  17930. this._renderingManager.render(null, null, true, true);
  17931. // Restore HighlightLayer stencil
  17932. if (renderhighlights) {
  17933. this._engine.setStencilBuffer(stencilState);
  17934. }
  17935. BABYLON.Tools.EndPerformanceCounter("Main render");
  17936. // Bounding boxes
  17937. this._boundingBoxRenderer.render();
  17938. // Edges
  17939. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  17940. this._edgesRenderers.data[edgesRendererIndex].render();
  17941. }
  17942. // Lens flares
  17943. if (this.lensFlaresEnabled) {
  17944. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17945. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  17946. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  17947. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  17948. lensFlareSystem.render();
  17949. }
  17950. }
  17951. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  17952. }
  17953. // Foregrounds
  17954. if (this.layers.length) {
  17955. engine.setDepthBuffer(false);
  17956. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  17957. layer = this.layers[layerIndex];
  17958. if (!layer.isBackground) {
  17959. layer.render();
  17960. }
  17961. }
  17962. engine.setDepthBuffer(true);
  17963. }
  17964. // Highlight Layer
  17965. if (renderhighlights) {
  17966. engine.setDepthBuffer(false);
  17967. for (var i = 0; i < this.highlightLayers.length; i++) {
  17968. if (this.highlightLayers[i].shouldRender()) {
  17969. this.highlightLayers[i].render();
  17970. }
  17971. }
  17972. engine.setDepthBuffer(true);
  17973. }
  17974. this._renderDuration.endMonitoring(false);
  17975. // Finalize frame
  17976. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  17977. // Update camera
  17978. this.activeCamera._updateFromScene();
  17979. // Reset some special arrays
  17980. this._renderTargets.reset();
  17981. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  17982. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  17983. };
  17984. Scene.prototype._processSubCameras = function (camera) {
  17985. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  17986. this._renderForCamera(camera);
  17987. return;
  17988. }
  17989. // rig cameras
  17990. for (var index = 0; index < camera._rigCameras.length; index++) {
  17991. this._renderForCamera(camera._rigCameras[index]);
  17992. }
  17993. this.activeCamera = camera;
  17994. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  17995. // Update camera
  17996. this.activeCamera._updateFromScene();
  17997. };
  17998. Scene.prototype._checkIntersections = function () {
  17999. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18000. var sourceMesh = this._meshesForIntersections.data[index];
  18001. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18002. var action = sourceMesh.actionManager.actions[actionIndex];
  18003. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18004. var parameters = action.getTriggerParameter();
  18005. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18006. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18007. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18008. if (areIntersecting && currentIntersectionInProgress === -1) {
  18009. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18010. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18011. sourceMesh._intersectionsInProgress.push(otherMesh);
  18012. }
  18013. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18014. sourceMesh._intersectionsInProgress.push(otherMesh);
  18015. }
  18016. }
  18017. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18018. //They intersected, and now they don't.
  18019. //is this trigger an exit trigger? execute an event.
  18020. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18021. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18022. }
  18023. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18024. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18025. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18026. }
  18027. }
  18028. }
  18029. }
  18030. }
  18031. };
  18032. Scene.prototype.render = function () {
  18033. this._lastFrameDuration.beginMonitoring();
  18034. this._particlesDuration.fetchNewFrame();
  18035. this._spritesDuration.fetchNewFrame();
  18036. this._activeParticles.fetchNewFrame();
  18037. this._renderDuration.fetchNewFrame();
  18038. this._renderTargetsDuration.fetchNewFrame();
  18039. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18040. this._totalVertices.fetchNewFrame();
  18041. this._activeIndices.fetchNewFrame();
  18042. this._activeBones.fetchNewFrame();
  18043. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18044. this._meshesForIntersections.reset();
  18045. this.resetCachedMaterial();
  18046. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18047. // Actions
  18048. if (this.actionManager) {
  18049. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18050. }
  18051. //Simplification Queue
  18052. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18053. this.simplificationQueue.executeNext();
  18054. }
  18055. // Animations
  18056. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18057. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18058. this._animate();
  18059. // Physics
  18060. if (this._physicsEngine) {
  18061. BABYLON.Tools.StartPerformanceCounter("Physics");
  18062. this._physicsEngine._step(deltaTime / 1000.0);
  18063. BABYLON.Tools.EndPerformanceCounter("Physics");
  18064. }
  18065. // Before render
  18066. this.onBeforeRenderObservable.notifyObservers(this);
  18067. // Customs render targets
  18068. this._renderTargetsDuration.beginMonitoring();
  18069. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18070. var engine = this.getEngine();
  18071. var currentActiveCamera = this.activeCamera;
  18072. if (this.renderTargetsEnabled) {
  18073. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18074. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18075. var renderTarget = this.customRenderTargets[customIndex];
  18076. if (renderTarget._shouldRender()) {
  18077. this._renderId++;
  18078. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18079. if (!this.activeCamera)
  18080. throw new Error("Active camera not set");
  18081. // Viewport
  18082. engine.setViewport(this.activeCamera.viewport);
  18083. // Camera
  18084. this.updateTransformMatrix();
  18085. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18086. }
  18087. }
  18088. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18089. this._renderId++;
  18090. }
  18091. if (this.customRenderTargets.length > 0) {
  18092. engine.restoreDefaultFramebuffer();
  18093. }
  18094. this._renderTargetsDuration.endMonitoring();
  18095. this.activeCamera = currentActiveCamera;
  18096. // Procedural textures
  18097. if (this.proceduralTexturesEnabled) {
  18098. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18099. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18100. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18101. if (proceduralTexture._shouldRender()) {
  18102. proceduralTexture.render();
  18103. }
  18104. }
  18105. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18106. }
  18107. // Clear
  18108. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  18109. // Shadows
  18110. if (this.shadowsEnabled) {
  18111. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18112. var light = this.lights[lightIndex];
  18113. var shadowGenerator = light.getShadowGenerator();
  18114. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  18115. this._renderTargets.push(shadowGenerator.getShadowMap());
  18116. }
  18117. }
  18118. }
  18119. // Depth renderer
  18120. if (this._depthRenderer) {
  18121. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18122. }
  18123. // RenderPipeline
  18124. this.postProcessRenderPipelineManager.update();
  18125. // Multi-cameras?
  18126. if (this.activeCameras.length > 0) {
  18127. var currentRenderId = this._renderId;
  18128. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18129. this._renderId = currentRenderId;
  18130. if (cameraIndex > 0) {
  18131. this._engine.clear(0, false, true, true);
  18132. }
  18133. this._processSubCameras(this.activeCameras[cameraIndex]);
  18134. }
  18135. }
  18136. else {
  18137. if (!this.activeCamera) {
  18138. throw new Error("No camera defined");
  18139. }
  18140. this._processSubCameras(this.activeCamera);
  18141. }
  18142. // Intersection checks
  18143. this._checkIntersections();
  18144. // Update the audio listener attached to the camera
  18145. if (BABYLON.AudioEngine) {
  18146. this._updateAudioParameters();
  18147. }
  18148. // After render
  18149. if (this.afterRender) {
  18150. this.afterRender();
  18151. }
  18152. this.onAfterRenderObservable.notifyObservers(this);
  18153. // Cleaning
  18154. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18155. this._toBeDisposed.data[index].dispose();
  18156. this._toBeDisposed[index] = null;
  18157. }
  18158. this._toBeDisposed.reset();
  18159. if (this.dumpNextRenderTargets) {
  18160. this.dumpNextRenderTargets = false;
  18161. }
  18162. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18163. this._lastFrameDuration.endMonitoring();
  18164. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18165. this._totalLightsCounter.addCount(this.lights.length, true);
  18166. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18167. this._totalTexturesCounter.addCount(this.textures.length, true);
  18168. this._activeBones.addCount(0, true);
  18169. this._activeIndices.addCount(0, true);
  18170. this._activeParticles.addCount(0, true);
  18171. };
  18172. Scene.prototype._updateAudioParameters = function () {
  18173. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18174. return;
  18175. }
  18176. var listeningCamera;
  18177. var audioEngine = BABYLON.Engine.audioEngine;
  18178. if (this.activeCameras.length > 0) {
  18179. listeningCamera = this.activeCameras[0];
  18180. }
  18181. else {
  18182. listeningCamera = this.activeCamera;
  18183. }
  18184. if (listeningCamera && audioEngine.canUseWebAudio) {
  18185. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18186. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18187. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18188. cameraDirection.normalize();
  18189. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18190. var i;
  18191. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18192. var sound = this.mainSoundTrack.soundCollection[i];
  18193. if (sound.useCustomAttenuation) {
  18194. sound.updateDistanceFromListener();
  18195. }
  18196. }
  18197. for (i = 0; i < this.soundTracks.length; i++) {
  18198. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18199. sound = this.soundTracks[i].soundCollection[j];
  18200. if (sound.useCustomAttenuation) {
  18201. sound.updateDistanceFromListener();
  18202. }
  18203. }
  18204. }
  18205. }
  18206. };
  18207. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18208. // Audio
  18209. get: function () {
  18210. return this._audioEnabled;
  18211. },
  18212. set: function (value) {
  18213. this._audioEnabled = value;
  18214. if (BABYLON.AudioEngine) {
  18215. if (this._audioEnabled) {
  18216. this._enableAudio();
  18217. }
  18218. else {
  18219. this._disableAudio();
  18220. }
  18221. }
  18222. },
  18223. enumerable: true,
  18224. configurable: true
  18225. });
  18226. Scene.prototype._disableAudio = function () {
  18227. var i;
  18228. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18229. this.mainSoundTrack.soundCollection[i].pause();
  18230. }
  18231. for (i = 0; i < this.soundTracks.length; i++) {
  18232. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18233. this.soundTracks[i].soundCollection[j].pause();
  18234. }
  18235. }
  18236. };
  18237. Scene.prototype._enableAudio = function () {
  18238. var i;
  18239. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18240. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18241. this.mainSoundTrack.soundCollection[i].play();
  18242. }
  18243. }
  18244. for (i = 0; i < this.soundTracks.length; i++) {
  18245. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18246. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18247. this.soundTracks[i].soundCollection[j].play();
  18248. }
  18249. }
  18250. }
  18251. };
  18252. Object.defineProperty(Scene.prototype, "headphone", {
  18253. get: function () {
  18254. return this._headphone;
  18255. },
  18256. set: function (value) {
  18257. this._headphone = value;
  18258. if (BABYLON.AudioEngine) {
  18259. if (this._headphone) {
  18260. this._switchAudioModeForHeadphones();
  18261. }
  18262. else {
  18263. this._switchAudioModeForNormalSpeakers();
  18264. }
  18265. }
  18266. },
  18267. enumerable: true,
  18268. configurable: true
  18269. });
  18270. Scene.prototype._switchAudioModeForHeadphones = function () {
  18271. this.mainSoundTrack.switchPanningModelToHRTF();
  18272. for (var i = 0; i < this.soundTracks.length; i++) {
  18273. this.soundTracks[i].switchPanningModelToHRTF();
  18274. }
  18275. };
  18276. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18277. this.mainSoundTrack.switchPanningModelToEqualPower();
  18278. for (var i = 0; i < this.soundTracks.length; i++) {
  18279. this.soundTracks[i].switchPanningModelToEqualPower();
  18280. }
  18281. };
  18282. Scene.prototype.enableDepthRenderer = function () {
  18283. if (this._depthRenderer) {
  18284. return this._depthRenderer;
  18285. }
  18286. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18287. return this._depthRenderer;
  18288. };
  18289. Scene.prototype.disableDepthRenderer = function () {
  18290. if (!this._depthRenderer) {
  18291. return;
  18292. }
  18293. this._depthRenderer.dispose();
  18294. this._depthRenderer = null;
  18295. };
  18296. Scene.prototype.freezeMaterials = function () {
  18297. for (var i = 0; i < this.materials.length; i++) {
  18298. this.materials[i].freeze();
  18299. }
  18300. };
  18301. Scene.prototype.unfreezeMaterials = function () {
  18302. for (var i = 0; i < this.materials.length; i++) {
  18303. this.materials[i].unfreeze();
  18304. }
  18305. };
  18306. Scene.prototype.dispose = function () {
  18307. this.beforeRender = null;
  18308. this.afterRender = null;
  18309. this.skeletons = [];
  18310. this._boundingBoxRenderer.dispose();
  18311. if (this._depthRenderer) {
  18312. this._depthRenderer.dispose();
  18313. }
  18314. // Debug layer
  18315. if (this._debugLayer) {
  18316. this._debugLayer.hide();
  18317. }
  18318. // Events
  18319. this.onDisposeObservable.notifyObservers(this);
  18320. this.onDisposeObservable.clear();
  18321. this.onBeforeRenderObservable.clear();
  18322. this.onAfterRenderObservable.clear();
  18323. this.detachControl();
  18324. // Release sounds & sounds tracks
  18325. if (BABYLON.AudioEngine) {
  18326. this.disposeSounds();
  18327. }
  18328. // Detach cameras
  18329. var canvas = this._engine.getRenderingCanvas();
  18330. var index;
  18331. for (index = 0; index < this.cameras.length; index++) {
  18332. this.cameras[index].detachControl(canvas);
  18333. }
  18334. // Release lights
  18335. while (this.lights.length) {
  18336. this.lights[0].dispose();
  18337. }
  18338. // Release meshes
  18339. while (this.meshes.length) {
  18340. this.meshes[0].dispose(true);
  18341. }
  18342. // Release cameras
  18343. while (this.cameras.length) {
  18344. this.cameras[0].dispose();
  18345. }
  18346. // Release materials
  18347. while (this.materials.length) {
  18348. this.materials[0].dispose();
  18349. }
  18350. // Release particles
  18351. while (this.particleSystems.length) {
  18352. this.particleSystems[0].dispose();
  18353. }
  18354. // Release sprites
  18355. while (this.spriteManagers.length) {
  18356. this.spriteManagers[0].dispose();
  18357. }
  18358. // Release layers
  18359. while (this.layers.length) {
  18360. this.layers[0].dispose();
  18361. }
  18362. while (this.highlightLayers.length) {
  18363. this.highlightLayers[0].dispose();
  18364. }
  18365. // Release textures
  18366. while (this.textures.length) {
  18367. this.textures[0].dispose();
  18368. }
  18369. // Post-processes
  18370. this.postProcessManager.dispose();
  18371. // Physics
  18372. if (this._physicsEngine) {
  18373. this.disablePhysicsEngine();
  18374. }
  18375. // Remove from engine
  18376. index = this._engine.scenes.indexOf(this);
  18377. if (index > -1) {
  18378. this._engine.scenes.splice(index, 1);
  18379. }
  18380. this._engine.wipeCaches();
  18381. };
  18382. // Release sounds & sounds tracks
  18383. Scene.prototype.disposeSounds = function () {
  18384. this.mainSoundTrack.dispose();
  18385. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18386. this.soundTracks[scIndex].dispose();
  18387. }
  18388. };
  18389. // Octrees
  18390. Scene.prototype.getWorldExtends = function () {
  18391. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18392. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18393. for (var index = 0; index < this.meshes.length; index++) {
  18394. var mesh = this.meshes[index];
  18395. mesh.computeWorldMatrix(true);
  18396. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18397. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18398. BABYLON.Tools.CheckExtends(minBox, min, max);
  18399. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18400. }
  18401. return {
  18402. min: min,
  18403. max: max
  18404. };
  18405. };
  18406. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18407. if (maxCapacity === void 0) { maxCapacity = 64; }
  18408. if (maxDepth === void 0) { maxDepth = 2; }
  18409. if (!this._selectionOctree) {
  18410. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18411. }
  18412. var worldExtends = this.getWorldExtends();
  18413. // Update octree
  18414. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18415. return this._selectionOctree;
  18416. };
  18417. // Picking
  18418. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18419. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18420. var engine = this._engine;
  18421. if (!camera) {
  18422. if (!this.activeCamera)
  18423. throw new Error("Active camera not set");
  18424. camera = this.activeCamera;
  18425. }
  18426. var cameraViewport = camera.viewport;
  18427. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18428. // Moving coordinates to local viewport world
  18429. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18430. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18431. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18432. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18433. };
  18434. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18435. var engine = this._engine;
  18436. if (!camera) {
  18437. if (!this.activeCamera)
  18438. throw new Error("Active camera not set");
  18439. camera = this.activeCamera;
  18440. }
  18441. var cameraViewport = camera.viewport;
  18442. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18443. var identity = BABYLON.Matrix.Identity();
  18444. // Moving coordinates to local viewport world
  18445. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18446. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18447. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18448. };
  18449. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18450. var pickingInfo = null;
  18451. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18452. var mesh = this.meshes[meshIndex];
  18453. if (predicate) {
  18454. if (!predicate(mesh)) {
  18455. continue;
  18456. }
  18457. }
  18458. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18459. continue;
  18460. }
  18461. var world = mesh.getWorldMatrix();
  18462. var ray = rayFunction(world);
  18463. var result = mesh.intersects(ray, fastCheck);
  18464. if (!result || !result.hit)
  18465. continue;
  18466. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18467. continue;
  18468. pickingInfo = result;
  18469. if (fastCheck) {
  18470. break;
  18471. }
  18472. }
  18473. return pickingInfo || new BABYLON.PickingInfo();
  18474. };
  18475. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18476. var pickingInfo = null;
  18477. camera = camera || this.activeCamera;
  18478. if (this.spriteManagers.length > 0) {
  18479. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18480. var spriteManager = this.spriteManagers[spriteIndex];
  18481. if (!spriteManager.isPickable) {
  18482. continue;
  18483. }
  18484. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18485. if (!result || !result.hit)
  18486. continue;
  18487. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18488. continue;
  18489. pickingInfo = result;
  18490. if (fastCheck) {
  18491. break;
  18492. }
  18493. }
  18494. }
  18495. return pickingInfo || new BABYLON.PickingInfo();
  18496. };
  18497. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18498. var _this = this;
  18499. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18500. /// <param name="x">X position on screen</param>
  18501. /// <param name="y">Y position on screen</param>
  18502. /// <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>
  18503. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18504. /// <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>
  18505. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18506. };
  18507. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18508. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18509. /// <param name="x">X position on screen</param>
  18510. /// <param name="y">Y position on screen</param>
  18511. /// <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>
  18512. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18513. /// <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>
  18514. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18515. };
  18516. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18517. var _this = this;
  18518. return this._internalPick(function (world) {
  18519. if (!_this._pickWithRayInverseMatrix) {
  18520. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18521. }
  18522. world.invertToRef(_this._pickWithRayInverseMatrix);
  18523. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18524. }, predicate, fastCheck);
  18525. };
  18526. Scene.prototype.setPointerOverMesh = function (mesh) {
  18527. if (this._pointerOverMesh === mesh) {
  18528. return;
  18529. }
  18530. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18531. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18532. }
  18533. this._pointerOverMesh = mesh;
  18534. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  18535. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  18536. }
  18537. };
  18538. Scene.prototype.getPointerOverMesh = function () {
  18539. return this._pointerOverMesh;
  18540. };
  18541. Scene.prototype.setPointerOverSprite = function (sprite) {
  18542. if (this._pointerOverSprite === sprite) {
  18543. return;
  18544. }
  18545. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18546. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18547. }
  18548. this._pointerOverSprite = sprite;
  18549. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  18550. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  18551. }
  18552. };
  18553. Scene.prototype.getPointerOverSprite = function () {
  18554. return this._pointerOverSprite;
  18555. };
  18556. // Physics
  18557. Scene.prototype.getPhysicsEngine = function () {
  18558. return this._physicsEngine;
  18559. };
  18560. /**
  18561. * Enables physics to the current scene
  18562. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  18563. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  18564. * @return {boolean} was the physics engine initialized
  18565. */
  18566. Scene.prototype.enablePhysics = function (gravity, plugin) {
  18567. if (this._physicsEngine) {
  18568. return true;
  18569. }
  18570. try {
  18571. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  18572. return true;
  18573. }
  18574. catch (e) {
  18575. BABYLON.Tools.Error(e.message);
  18576. return false;
  18577. }
  18578. };
  18579. Scene.prototype.disablePhysicsEngine = function () {
  18580. if (!this._physicsEngine) {
  18581. return;
  18582. }
  18583. this._physicsEngine.dispose();
  18584. this._physicsEngine = undefined;
  18585. };
  18586. Scene.prototype.isPhysicsEnabled = function () {
  18587. return this._physicsEngine !== undefined;
  18588. };
  18589. /**
  18590. *
  18591. * Sets the gravity of the physics engine (and NOT of the scene)
  18592. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  18593. */
  18594. Scene.prototype.setGravity = function (gravity) {
  18595. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  18596. if (!this._physicsEngine) {
  18597. return;
  18598. }
  18599. this._physicsEngine.setGravity(gravity);
  18600. };
  18601. /**
  18602. * Legacy support, using the new API
  18603. * @Deprecated
  18604. */
  18605. Scene.prototype.createCompoundImpostor = function (parts, options) {
  18606. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  18607. if (parts.parts) {
  18608. options = parts;
  18609. parts = parts.parts;
  18610. }
  18611. var mainMesh = parts[0].mesh;
  18612. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  18613. for (var index = 1; index < parts.length; index++) {
  18614. var mesh = parts[index].mesh;
  18615. if (mesh.parent !== mainMesh) {
  18616. mesh.position = mesh.position.subtract(mainMesh.position);
  18617. mesh.parent = mainMesh;
  18618. }
  18619. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  18620. }
  18621. mainMesh.physicsImpostor.forceUpdate();
  18622. };
  18623. Scene.prototype.deleteCompoundImpostor = function (compound) {
  18624. var mesh = compound.parts[0].mesh;
  18625. mesh.physicsImpostor.dispose();
  18626. mesh.physicsImpostor = null;
  18627. };
  18628. // Misc.
  18629. Scene.prototype.createDefaultCameraOrLight = function () {
  18630. // Light
  18631. if (this.lights.length === 0) {
  18632. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  18633. }
  18634. // Camera
  18635. if (!this.activeCamera) {
  18636. var camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  18637. // Compute position
  18638. var worldExtends = this.getWorldExtends();
  18639. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  18640. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  18641. camera.setTarget(worldCenter);
  18642. this.activeCamera = camera;
  18643. }
  18644. };
  18645. // Tags
  18646. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  18647. if (tagsQuery === undefined) {
  18648. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  18649. return list;
  18650. }
  18651. var listByTags = [];
  18652. forEach = forEach || (function (item) { return; });
  18653. for (var i in list) {
  18654. var item = list[i];
  18655. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  18656. listByTags.push(item);
  18657. forEach(item);
  18658. }
  18659. }
  18660. return listByTags;
  18661. };
  18662. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  18663. return this._getByTags(this.meshes, tagsQuery, forEach);
  18664. };
  18665. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  18666. return this._getByTags(this.cameras, tagsQuery, forEach);
  18667. };
  18668. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  18669. return this._getByTags(this.lights, tagsQuery, forEach);
  18670. };
  18671. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  18672. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  18673. };
  18674. /**
  18675. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  18676. * This allowed control for front to back rendering or reversly depending of the special needs.
  18677. *
  18678. * @param renderingGroupId The rendering group id corresponding to its index
  18679. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  18680. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  18681. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  18682. */
  18683. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  18684. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  18685. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  18686. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  18687. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  18688. };
  18689. /**
  18690. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  18691. *
  18692. * @param renderingGroupId The rendering group id corresponding to its index
  18693. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  18694. */
  18695. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  18696. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  18697. };
  18698. // Statics
  18699. Scene._FOGMODE_NONE = 0;
  18700. Scene._FOGMODE_EXP = 1;
  18701. Scene._FOGMODE_EXP2 = 2;
  18702. Scene._FOGMODE_LINEAR = 3;
  18703. Scene.MinDeltaTime = 1.0;
  18704. Scene.MaxDeltaTime = 1000.0;
  18705. return Scene;
  18706. }());
  18707. BABYLON.Scene = Scene;
  18708. })(BABYLON || (BABYLON = {}));
  18709. var BABYLON;
  18710. (function (BABYLON) {
  18711. var Buffer = (function () {
  18712. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  18713. if (engine instanceof BABYLON.Mesh) {
  18714. this._engine = engine.getScene().getEngine();
  18715. }
  18716. else {
  18717. this._engine = engine;
  18718. }
  18719. this._updatable = updatable;
  18720. this._data = data;
  18721. this._strideSize = stride;
  18722. if (!postponeInternalCreation) {
  18723. this.create();
  18724. }
  18725. this._instanced = instanced;
  18726. }
  18727. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  18728. // a lot of these parameters are ignored as they are overriden by the buffer
  18729. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  18730. };
  18731. // Properties
  18732. Buffer.prototype.isUpdatable = function () {
  18733. return this._updatable;
  18734. };
  18735. Buffer.prototype.getData = function () {
  18736. return this._data;
  18737. };
  18738. Buffer.prototype.getBuffer = function () {
  18739. return this._buffer;
  18740. };
  18741. Buffer.prototype.getStrideSize = function () {
  18742. return this._strideSize;
  18743. };
  18744. Buffer.prototype.getIsInstanced = function () {
  18745. return this._instanced;
  18746. };
  18747. // Methods
  18748. Buffer.prototype.create = function (data) {
  18749. if (!data && this._buffer) {
  18750. return; // nothing to do
  18751. }
  18752. data = data || this._data;
  18753. if (!this._buffer) {
  18754. if (this._updatable) {
  18755. this._buffer = this._engine.createDynamicVertexBuffer(data);
  18756. this._data = data;
  18757. }
  18758. else {
  18759. this._buffer = this._engine.createVertexBuffer(data);
  18760. }
  18761. }
  18762. else if (this._updatable) {
  18763. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  18764. this._data = data;
  18765. }
  18766. };
  18767. Buffer.prototype.update = function (data) {
  18768. this.create(data);
  18769. };
  18770. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  18771. if (!this._buffer) {
  18772. return;
  18773. }
  18774. if (this._updatable) {
  18775. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  18776. this._data = null;
  18777. }
  18778. };
  18779. Buffer.prototype.dispose = function () {
  18780. if (!this._buffer) {
  18781. return;
  18782. }
  18783. if (this._engine._releaseBuffer(this._buffer)) {
  18784. this._buffer = null;
  18785. }
  18786. };
  18787. return Buffer;
  18788. }());
  18789. BABYLON.Buffer = Buffer;
  18790. })(BABYLON || (BABYLON = {}));
  18791. var BABYLON;
  18792. (function (BABYLON) {
  18793. var VertexBuffer = (function () {
  18794. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  18795. if (!stride) {
  18796. // Deduce stride from kind
  18797. switch (kind) {
  18798. case VertexBuffer.PositionKind:
  18799. stride = 3;
  18800. break;
  18801. case VertexBuffer.NormalKind:
  18802. stride = 3;
  18803. break;
  18804. case VertexBuffer.UVKind:
  18805. case VertexBuffer.UV2Kind:
  18806. case VertexBuffer.UV3Kind:
  18807. case VertexBuffer.UV4Kind:
  18808. case VertexBuffer.UV5Kind:
  18809. case VertexBuffer.UV6Kind:
  18810. stride = 2;
  18811. break;
  18812. case VertexBuffer.ColorKind:
  18813. stride = 4;
  18814. break;
  18815. case VertexBuffer.MatricesIndicesKind:
  18816. case VertexBuffer.MatricesIndicesExtraKind:
  18817. stride = 4;
  18818. break;
  18819. case VertexBuffer.MatricesWeightsKind:
  18820. case VertexBuffer.MatricesWeightsExtraKind:
  18821. stride = 4;
  18822. break;
  18823. }
  18824. }
  18825. if (data instanceof BABYLON.Buffer) {
  18826. if (!stride) {
  18827. stride = data.getStrideSize();
  18828. }
  18829. this._buffer = data;
  18830. this._ownsBuffer = false;
  18831. }
  18832. else {
  18833. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  18834. this._ownsBuffer = true;
  18835. }
  18836. this._stride = stride;
  18837. this._offset = offset ? offset : 0;
  18838. this._size = size ? size : stride;
  18839. this._kind = kind;
  18840. }
  18841. VertexBuffer.prototype.getKind = function () {
  18842. return this._kind;
  18843. };
  18844. // Properties
  18845. VertexBuffer.prototype.isUpdatable = function () {
  18846. return this._buffer.isUpdatable();
  18847. };
  18848. VertexBuffer.prototype.getData = function () {
  18849. return this._buffer.getData();
  18850. };
  18851. VertexBuffer.prototype.getBuffer = function () {
  18852. return this._buffer.getBuffer();
  18853. };
  18854. VertexBuffer.prototype.getStrideSize = function () {
  18855. return this._stride;
  18856. };
  18857. VertexBuffer.prototype.getOffset = function () {
  18858. return this._offset;
  18859. };
  18860. VertexBuffer.prototype.getSize = function () {
  18861. return this._size;
  18862. };
  18863. VertexBuffer.prototype.getIsInstanced = function () {
  18864. return this._buffer.getIsInstanced();
  18865. };
  18866. // Methods
  18867. VertexBuffer.prototype.create = function (data) {
  18868. return this._buffer.create(data);
  18869. };
  18870. VertexBuffer.prototype.update = function (data) {
  18871. return this._buffer.update(data);
  18872. };
  18873. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  18874. return this._buffer.updateDirectly(data, offset);
  18875. };
  18876. VertexBuffer.prototype.dispose = function () {
  18877. if (this._ownsBuffer) {
  18878. this._buffer.dispose();
  18879. }
  18880. };
  18881. Object.defineProperty(VertexBuffer, "PositionKind", {
  18882. get: function () {
  18883. return VertexBuffer._PositionKind;
  18884. },
  18885. enumerable: true,
  18886. configurable: true
  18887. });
  18888. Object.defineProperty(VertexBuffer, "NormalKind", {
  18889. get: function () {
  18890. return VertexBuffer._NormalKind;
  18891. },
  18892. enumerable: true,
  18893. configurable: true
  18894. });
  18895. Object.defineProperty(VertexBuffer, "UVKind", {
  18896. get: function () {
  18897. return VertexBuffer._UVKind;
  18898. },
  18899. enumerable: true,
  18900. configurable: true
  18901. });
  18902. Object.defineProperty(VertexBuffer, "UV2Kind", {
  18903. get: function () {
  18904. return VertexBuffer._UV2Kind;
  18905. },
  18906. enumerable: true,
  18907. configurable: true
  18908. });
  18909. Object.defineProperty(VertexBuffer, "UV3Kind", {
  18910. get: function () {
  18911. return VertexBuffer._UV3Kind;
  18912. },
  18913. enumerable: true,
  18914. configurable: true
  18915. });
  18916. Object.defineProperty(VertexBuffer, "UV4Kind", {
  18917. get: function () {
  18918. return VertexBuffer._UV4Kind;
  18919. },
  18920. enumerable: true,
  18921. configurable: true
  18922. });
  18923. Object.defineProperty(VertexBuffer, "UV5Kind", {
  18924. get: function () {
  18925. return VertexBuffer._UV5Kind;
  18926. },
  18927. enumerable: true,
  18928. configurable: true
  18929. });
  18930. Object.defineProperty(VertexBuffer, "UV6Kind", {
  18931. get: function () {
  18932. return VertexBuffer._UV6Kind;
  18933. },
  18934. enumerable: true,
  18935. configurable: true
  18936. });
  18937. Object.defineProperty(VertexBuffer, "ColorKind", {
  18938. get: function () {
  18939. return VertexBuffer._ColorKind;
  18940. },
  18941. enumerable: true,
  18942. configurable: true
  18943. });
  18944. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  18945. get: function () {
  18946. return VertexBuffer._MatricesIndicesKind;
  18947. },
  18948. enumerable: true,
  18949. configurable: true
  18950. });
  18951. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  18952. get: function () {
  18953. return VertexBuffer._MatricesWeightsKind;
  18954. },
  18955. enumerable: true,
  18956. configurable: true
  18957. });
  18958. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  18959. get: function () {
  18960. return VertexBuffer._MatricesIndicesExtraKind;
  18961. },
  18962. enumerable: true,
  18963. configurable: true
  18964. });
  18965. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  18966. get: function () {
  18967. return VertexBuffer._MatricesWeightsExtraKind;
  18968. },
  18969. enumerable: true,
  18970. configurable: true
  18971. });
  18972. // Enums
  18973. VertexBuffer._PositionKind = "position";
  18974. VertexBuffer._NormalKind = "normal";
  18975. VertexBuffer._UVKind = "uv";
  18976. VertexBuffer._UV2Kind = "uv2";
  18977. VertexBuffer._UV3Kind = "uv3";
  18978. VertexBuffer._UV4Kind = "uv4";
  18979. VertexBuffer._UV5Kind = "uv5";
  18980. VertexBuffer._UV6Kind = "uv6";
  18981. VertexBuffer._ColorKind = "color";
  18982. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  18983. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  18984. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  18985. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  18986. return VertexBuffer;
  18987. }());
  18988. BABYLON.VertexBuffer = VertexBuffer;
  18989. })(BABYLON || (BABYLON = {}));
  18990. var BABYLON;
  18991. (function (BABYLON) {
  18992. /**
  18993. * Creates an instance based on a source mesh.
  18994. */
  18995. var InstancedMesh = (function (_super) {
  18996. __extends(InstancedMesh, _super);
  18997. function InstancedMesh(name, source) {
  18998. _super.call(this, name, source.getScene());
  18999. source.instances.push(this);
  19000. this._sourceMesh = source;
  19001. this.position.copyFrom(source.position);
  19002. this.rotation.copyFrom(source.rotation);
  19003. this.scaling.copyFrom(source.scaling);
  19004. if (source.rotationQuaternion) {
  19005. this.rotationQuaternion = source.rotationQuaternion.clone();
  19006. }
  19007. this.infiniteDistance = source.infiniteDistance;
  19008. this.setPivotMatrix(source.getPivotMatrix());
  19009. this.refreshBoundingInfo();
  19010. this._syncSubMeshes();
  19011. }
  19012. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  19013. // Methods
  19014. get: function () {
  19015. return this._sourceMesh.receiveShadows;
  19016. },
  19017. enumerable: true,
  19018. configurable: true
  19019. });
  19020. Object.defineProperty(InstancedMesh.prototype, "material", {
  19021. get: function () {
  19022. return this._sourceMesh.material;
  19023. },
  19024. enumerable: true,
  19025. configurable: true
  19026. });
  19027. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  19028. get: function () {
  19029. return this._sourceMesh.visibility;
  19030. },
  19031. enumerable: true,
  19032. configurable: true
  19033. });
  19034. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  19035. get: function () {
  19036. return this._sourceMesh.skeleton;
  19037. },
  19038. enumerable: true,
  19039. configurable: true
  19040. });
  19041. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  19042. get: function () {
  19043. return this._sourceMesh.renderingGroupId;
  19044. },
  19045. enumerable: true,
  19046. configurable: true
  19047. });
  19048. InstancedMesh.prototype.getTotalVertices = function () {
  19049. return this._sourceMesh.getTotalVertices();
  19050. };
  19051. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  19052. get: function () {
  19053. return this._sourceMesh;
  19054. },
  19055. enumerable: true,
  19056. configurable: true
  19057. });
  19058. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19059. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  19060. };
  19061. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  19062. return this._sourceMesh.isVerticesDataPresent(kind);
  19063. };
  19064. InstancedMesh.prototype.getIndices = function () {
  19065. return this._sourceMesh.getIndices();
  19066. };
  19067. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  19068. get: function () {
  19069. return this._sourceMesh._positions;
  19070. },
  19071. enumerable: true,
  19072. configurable: true
  19073. });
  19074. InstancedMesh.prototype.refreshBoundingInfo = function () {
  19075. var meshBB = this._sourceMesh.getBoundingInfo();
  19076. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  19077. this._updateBoundingInfo();
  19078. };
  19079. InstancedMesh.prototype._preActivate = function () {
  19080. if (this._currentLOD) {
  19081. this._currentLOD._preActivate();
  19082. }
  19083. };
  19084. InstancedMesh.prototype._activate = function (renderId) {
  19085. if (this._currentLOD) {
  19086. this._currentLOD._registerInstanceForRenderId(this, renderId);
  19087. }
  19088. };
  19089. InstancedMesh.prototype.getLOD = function (camera) {
  19090. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  19091. if (this._currentLOD === this.sourceMesh) {
  19092. return this;
  19093. }
  19094. return this._currentLOD;
  19095. };
  19096. InstancedMesh.prototype._syncSubMeshes = function () {
  19097. this.releaseSubMeshes();
  19098. if (this._sourceMesh.subMeshes) {
  19099. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  19100. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  19101. }
  19102. }
  19103. };
  19104. InstancedMesh.prototype._generatePointsArray = function () {
  19105. return this._sourceMesh._generatePointsArray();
  19106. };
  19107. // Clone
  19108. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19109. var result = this._sourceMesh.createInstance(name);
  19110. // Deep copy
  19111. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  19112. // Bounding info
  19113. this.refreshBoundingInfo();
  19114. // Parent
  19115. if (newParent) {
  19116. result.parent = newParent;
  19117. }
  19118. if (!doNotCloneChildren) {
  19119. // Children
  19120. for (var index = 0; index < this.getScene().meshes.length; index++) {
  19121. var mesh = this.getScene().meshes[index];
  19122. if (mesh.parent === this) {
  19123. mesh.clone(mesh.name, result);
  19124. }
  19125. }
  19126. }
  19127. result.computeWorldMatrix(true);
  19128. return result;
  19129. };
  19130. // Dispoe
  19131. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  19132. // Remove from mesh
  19133. var index = this._sourceMesh.instances.indexOf(this);
  19134. this._sourceMesh.instances.splice(index, 1);
  19135. _super.prototype.dispose.call(this, doNotRecurse);
  19136. };
  19137. return InstancedMesh;
  19138. }(BABYLON.AbstractMesh));
  19139. BABYLON.InstancedMesh = InstancedMesh;
  19140. })(BABYLON || (BABYLON = {}));
  19141. var BABYLON;
  19142. (function (BABYLON) {
  19143. var _InstancesBatch = (function () {
  19144. function _InstancesBatch() {
  19145. this.mustReturn = false;
  19146. this.visibleInstances = new Array();
  19147. this.renderSelf = new Array();
  19148. }
  19149. return _InstancesBatch;
  19150. }());
  19151. BABYLON._InstancesBatch = _InstancesBatch;
  19152. var Mesh = (function (_super) {
  19153. __extends(Mesh, _super);
  19154. /**
  19155. * @constructor
  19156. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19157. * @param {Scene} scene The scene to add this mesh to.
  19158. * @param {Node} parent The parent of this mesh, if it has one
  19159. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19160. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19161. * When false, achieved by calling a clone(), also passing False.
  19162. * This will make creation of children, recursive.
  19163. */
  19164. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19165. if (parent === void 0) { parent = null; }
  19166. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19167. _super.call(this, name, scene);
  19168. // Events
  19169. /**
  19170. * An event triggered before rendering the mesh
  19171. * @type {BABYLON.Observable}
  19172. */
  19173. this.onBeforeRenderObservable = new BABYLON.Observable();
  19174. /**
  19175. * An event triggered after rendering the mesh
  19176. * @type {BABYLON.Observable}
  19177. */
  19178. this.onAfterRenderObservable = new BABYLON.Observable();
  19179. /**
  19180. * An event triggered before drawing the mesh
  19181. * @type {BABYLON.Observable}
  19182. */
  19183. this.onBeforeDrawObservable = new BABYLON.Observable();
  19184. // Members
  19185. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19186. this.instances = new Array();
  19187. this._LODLevels = new Array();
  19188. this._visibleInstances = {};
  19189. this._renderIdForInstances = new Array();
  19190. this._batchCache = new _InstancesBatch();
  19191. this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19192. this._sideOrientation = Mesh._DEFAULTSIDE;
  19193. this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19194. if (source) {
  19195. // Geometry
  19196. if (source._geometry) {
  19197. source._geometry.applyToMesh(this);
  19198. }
  19199. // Deep copy
  19200. BABYLON.Tools.DeepCopy(source, this, ["name", "material", "skeleton", "instances"], ["_poseMatrix"]);
  19201. // Pivot
  19202. this.setPivotMatrix(source.getPivotMatrix());
  19203. this.id = name + "." + source.id;
  19204. // Material
  19205. this.material = source.material;
  19206. var index;
  19207. if (!doNotCloneChildren) {
  19208. // Children
  19209. for (index = 0; index < scene.meshes.length; index++) {
  19210. var mesh = scene.meshes[index];
  19211. if (mesh.parent === source) {
  19212. // doNotCloneChildren is always going to be False
  19213. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  19214. }
  19215. }
  19216. }
  19217. // Physics clone
  19218. var physicsEngine = this.getScene().getPhysicsEngine();
  19219. if (clonePhysicsImpostor && physicsEngine) {
  19220. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19221. if (impostor) {
  19222. this.physicsImpostor = impostor.clone(this);
  19223. }
  19224. }
  19225. // Particles
  19226. for (index = 0; index < scene.particleSystems.length; index++) {
  19227. var system = scene.particleSystems[index];
  19228. if (system.emitter === source) {
  19229. system.clone(system.name, this);
  19230. }
  19231. }
  19232. this.computeWorldMatrix(true);
  19233. }
  19234. // Parent
  19235. if (parent !== null) {
  19236. this.parent = parent;
  19237. }
  19238. }
  19239. Object.defineProperty(Mesh, "FRONTSIDE", {
  19240. /**
  19241. * Mesh side orientation : usually the external or front surface
  19242. */
  19243. get: function () {
  19244. return Mesh._FRONTSIDE;
  19245. },
  19246. enumerable: true,
  19247. configurable: true
  19248. });
  19249. Object.defineProperty(Mesh, "BACKSIDE", {
  19250. /**
  19251. * Mesh side orientation : usually the internal or back surface
  19252. */
  19253. get: function () {
  19254. return Mesh._BACKSIDE;
  19255. },
  19256. enumerable: true,
  19257. configurable: true
  19258. });
  19259. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19260. /**
  19261. * Mesh side orientation : both internal and external or front and back surfaces
  19262. */
  19263. get: function () {
  19264. return Mesh._DOUBLESIDE;
  19265. },
  19266. enumerable: true,
  19267. configurable: true
  19268. });
  19269. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19270. /**
  19271. * Mesh side orientation : by default, `FRONTSIDE`
  19272. */
  19273. get: function () {
  19274. return Mesh._DEFAULTSIDE;
  19275. },
  19276. enumerable: true,
  19277. configurable: true
  19278. });
  19279. Object.defineProperty(Mesh, "NO_CAP", {
  19280. /**
  19281. * Mesh cap setting : no cap
  19282. */
  19283. get: function () {
  19284. return Mesh._NO_CAP;
  19285. },
  19286. enumerable: true,
  19287. configurable: true
  19288. });
  19289. Object.defineProperty(Mesh, "CAP_START", {
  19290. /**
  19291. * Mesh cap setting : one cap at the beginning of the mesh
  19292. */
  19293. get: function () {
  19294. return Mesh._CAP_START;
  19295. },
  19296. enumerable: true,
  19297. configurable: true
  19298. });
  19299. Object.defineProperty(Mesh, "CAP_END", {
  19300. /**
  19301. * Mesh cap setting : one cap at the end of the mesh
  19302. */
  19303. get: function () {
  19304. return Mesh._CAP_END;
  19305. },
  19306. enumerable: true,
  19307. configurable: true
  19308. });
  19309. Object.defineProperty(Mesh, "CAP_ALL", {
  19310. /**
  19311. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19312. */
  19313. get: function () {
  19314. return Mesh._CAP_ALL;
  19315. },
  19316. enumerable: true,
  19317. configurable: true
  19318. });
  19319. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19320. set: function (callback) {
  19321. if (this._onBeforeDrawObserver) {
  19322. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19323. }
  19324. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19325. },
  19326. enumerable: true,
  19327. configurable: true
  19328. });
  19329. // Methods
  19330. /**
  19331. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19332. */
  19333. Mesh.prototype.toString = function (fullDetails) {
  19334. var ret = _super.prototype.toString.call(this, fullDetails);
  19335. ret += ", n vertices: " + this.getTotalVertices();
  19336. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19337. if (this.animations) {
  19338. for (var i = 0; i < this.animations.length; i++) {
  19339. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19340. }
  19341. }
  19342. if (fullDetails) {
  19343. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19344. }
  19345. return ret;
  19346. };
  19347. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19348. get: function () {
  19349. return this._LODLevels.length > 0;
  19350. },
  19351. enumerable: true,
  19352. configurable: true
  19353. });
  19354. Mesh.prototype._sortLODLevels = function () {
  19355. this._LODLevels.sort(function (a, b) {
  19356. if (a.distance < b.distance) {
  19357. return 1;
  19358. }
  19359. if (a.distance > b.distance) {
  19360. return -1;
  19361. }
  19362. return 0;
  19363. });
  19364. };
  19365. /**
  19366. * Add a mesh as LOD level triggered at the given distance.
  19367. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19368. * @param {number} distance The distance from the center of the object to show this level
  19369. * @param {Mesh} mesh The mesh to be added as LOD level
  19370. * @return {Mesh} This mesh (for chaining)
  19371. */
  19372. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19373. if (mesh && mesh._masterMesh) {
  19374. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19375. return this;
  19376. }
  19377. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19378. this._LODLevels.push(level);
  19379. if (mesh) {
  19380. mesh._masterMesh = this;
  19381. }
  19382. this._sortLODLevels();
  19383. return this;
  19384. };
  19385. /**
  19386. * Returns the LOD level mesh at the passed distance or null if not found.
  19387. * It is related to the method `addLODLevel(distance, mesh)`.
  19388. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19389. */
  19390. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19391. for (var index = 0; index < this._LODLevels.length; index++) {
  19392. var level = this._LODLevels[index];
  19393. if (level.distance === distance) {
  19394. return level.mesh;
  19395. }
  19396. }
  19397. return null;
  19398. };
  19399. /**
  19400. * Remove a mesh from the LOD array
  19401. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19402. * @param {Mesh} mesh The mesh to be removed.
  19403. * @return {Mesh} This mesh (for chaining)
  19404. */
  19405. Mesh.prototype.removeLODLevel = function (mesh) {
  19406. for (var index = 0; index < this._LODLevels.length; index++) {
  19407. if (this._LODLevels[index].mesh === mesh) {
  19408. this._LODLevels.splice(index, 1);
  19409. if (mesh) {
  19410. mesh._masterMesh = null;
  19411. }
  19412. }
  19413. }
  19414. this._sortLODLevels();
  19415. return this;
  19416. };
  19417. /**
  19418. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19419. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19420. */
  19421. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19422. if (!this._LODLevels || this._LODLevels.length === 0) {
  19423. return this;
  19424. }
  19425. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19426. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19427. if (this.onLODLevelSelection) {
  19428. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19429. }
  19430. return this;
  19431. }
  19432. for (var index = 0; index < this._LODLevels.length; index++) {
  19433. var level = this._LODLevels[index];
  19434. if (level.distance < distanceToCamera) {
  19435. if (level.mesh) {
  19436. level.mesh._preActivate();
  19437. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19438. }
  19439. if (this.onLODLevelSelection) {
  19440. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19441. }
  19442. return level.mesh;
  19443. }
  19444. }
  19445. if (this.onLODLevelSelection) {
  19446. this.onLODLevelSelection(distanceToCamera, this, this);
  19447. }
  19448. return this;
  19449. };
  19450. Object.defineProperty(Mesh.prototype, "geometry", {
  19451. /**
  19452. * Returns the mesh internal Geometry object.
  19453. */
  19454. get: function () {
  19455. return this._geometry;
  19456. },
  19457. enumerable: true,
  19458. configurable: true
  19459. });
  19460. /**
  19461. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19462. */
  19463. Mesh.prototype.getTotalVertices = function () {
  19464. if (!this._geometry) {
  19465. return 0;
  19466. }
  19467. return this._geometry.getTotalVertices();
  19468. };
  19469. /**
  19470. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19471. * 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.
  19472. * Returns null if the mesh has no geometry or no vertex buffer.
  19473. * Possible `kind` values :
  19474. * - BABYLON.VertexBuffer.PositionKind
  19475. * - BABYLON.VertexBuffer.UVKind
  19476. * - BABYLON.VertexBuffer.UV2Kind
  19477. * - BABYLON.VertexBuffer.UV3Kind
  19478. * - BABYLON.VertexBuffer.UV4Kind
  19479. * - BABYLON.VertexBuffer.UV5Kind
  19480. * - BABYLON.VertexBuffer.UV6Kind
  19481. * - BABYLON.VertexBuffer.ColorKind
  19482. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19483. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19484. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19485. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19486. */
  19487. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19488. if (!this._geometry) {
  19489. return null;
  19490. }
  19491. return this._geometry.getVerticesData(kind, copyWhenShared);
  19492. };
  19493. /**
  19494. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  19495. * Returns `undefined` if the mesh has no geometry.
  19496. * Possible `kind` values :
  19497. * - BABYLON.VertexBuffer.PositionKind
  19498. * - BABYLON.VertexBuffer.UVKind
  19499. * - BABYLON.VertexBuffer.UV2Kind
  19500. * - BABYLON.VertexBuffer.UV3Kind
  19501. * - BABYLON.VertexBuffer.UV4Kind
  19502. * - BABYLON.VertexBuffer.UV5Kind
  19503. * - BABYLON.VertexBuffer.UV6Kind
  19504. * - BABYLON.VertexBuffer.ColorKind
  19505. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19506. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19507. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19508. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19509. */
  19510. Mesh.prototype.getVertexBuffer = function (kind) {
  19511. if (!this._geometry) {
  19512. return undefined;
  19513. }
  19514. return this._geometry.getVertexBuffer(kind);
  19515. };
  19516. /**
  19517. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  19518. * Possible `kind` values :
  19519. * - BABYLON.VertexBuffer.PositionKind
  19520. * - BABYLON.VertexBuffer.UVKind
  19521. * - BABYLON.VertexBuffer.UV2Kind
  19522. * - BABYLON.VertexBuffer.UV3Kind
  19523. * - BABYLON.VertexBuffer.UV4Kind
  19524. * - BABYLON.VertexBuffer.UV5Kind
  19525. * - BABYLON.VertexBuffer.UV6Kind
  19526. * - BABYLON.VertexBuffer.ColorKind
  19527. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19528. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19529. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19530. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19531. */
  19532. Mesh.prototype.isVerticesDataPresent = function (kind) {
  19533. if (!this._geometry) {
  19534. if (this._delayInfo) {
  19535. return this._delayInfo.indexOf(kind) !== -1;
  19536. }
  19537. return false;
  19538. }
  19539. return this._geometry.isVerticesDataPresent(kind);
  19540. };
  19541. /**
  19542. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  19543. * Possible `kind` values :
  19544. * - BABYLON.VertexBuffer.PositionKind
  19545. * - BABYLON.VertexBuffer.UVKind
  19546. * - BABYLON.VertexBuffer.UV2Kind
  19547. * - BABYLON.VertexBuffer.UV3Kind
  19548. * - BABYLON.VertexBuffer.UV4Kind
  19549. * - BABYLON.VertexBuffer.UV5Kind
  19550. * - BABYLON.VertexBuffer.UV6Kind
  19551. * - BABYLON.VertexBuffer.ColorKind
  19552. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19553. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19554. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19555. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19556. */
  19557. Mesh.prototype.getVerticesDataKinds = function () {
  19558. if (!this._geometry) {
  19559. var result = [];
  19560. if (this._delayInfo) {
  19561. this._delayInfo.forEach(function (kind, index, array) {
  19562. result.push(kind);
  19563. });
  19564. }
  19565. return result;
  19566. }
  19567. return this._geometry.getVerticesDataKinds();
  19568. };
  19569. /**
  19570. * Returns a positive integer : the total number of indices in this mesh geometry.
  19571. * Returns zero if the mesh has no geometry.
  19572. */
  19573. Mesh.prototype.getTotalIndices = function () {
  19574. if (!this._geometry) {
  19575. return 0;
  19576. }
  19577. return this._geometry.getTotalIndices();
  19578. };
  19579. /**
  19580. * Returns an array of integers or a Int32Array populated with the mesh indices.
  19581. * 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.
  19582. * Returns an empty array if the mesh has no geometry.
  19583. */
  19584. Mesh.prototype.getIndices = function (copyWhenShared) {
  19585. if (!this._geometry) {
  19586. return [];
  19587. }
  19588. return this._geometry.getIndices(copyWhenShared);
  19589. };
  19590. Object.defineProperty(Mesh.prototype, "isBlocked", {
  19591. get: function () {
  19592. return this._masterMesh !== null && this._masterMesh !== undefined;
  19593. },
  19594. enumerable: true,
  19595. configurable: true
  19596. });
  19597. /**
  19598. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  19599. */
  19600. Mesh.prototype.isReady = function () {
  19601. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  19602. return false;
  19603. }
  19604. return _super.prototype.isReady.call(this);
  19605. };
  19606. /**
  19607. * Boolean : true if the mesh has been disposed.
  19608. */
  19609. Mesh.prototype.isDisposed = function () {
  19610. return this._isDisposed;
  19611. };
  19612. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  19613. get: function () {
  19614. return this._sideOrientation;
  19615. },
  19616. /**
  19617. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  19618. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  19619. */
  19620. set: function (sideO) {
  19621. this._sideOrientation = sideO;
  19622. },
  19623. enumerable: true,
  19624. configurable: true
  19625. });
  19626. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  19627. /**
  19628. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  19629. * This property is pertinent only for updatable parametric shapes.
  19630. */
  19631. get: function () {
  19632. return this._areNormalsFrozen;
  19633. },
  19634. enumerable: true,
  19635. configurable: true
  19636. });
  19637. /**
  19638. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19639. * It has no effect at all on other shapes.
  19640. * It prevents the mesh normals from being recomputed on next `positions` array update.
  19641. */
  19642. Mesh.prototype.freezeNormals = function () {
  19643. this._areNormalsFrozen = true;
  19644. };
  19645. /**
  19646. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  19647. * It has no effect at all on other shapes.
  19648. * It reactivates the mesh normals computation if it was previously frozen.
  19649. */
  19650. Mesh.prototype.unfreezeNormals = function () {
  19651. this._areNormalsFrozen = false;
  19652. };
  19653. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  19654. /**
  19655. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  19656. */
  19657. set: function (count) {
  19658. this._overridenInstanceCount = count;
  19659. },
  19660. enumerable: true,
  19661. configurable: true
  19662. });
  19663. // Methods
  19664. Mesh.prototype._preActivate = function () {
  19665. var sceneRenderId = this.getScene().getRenderId();
  19666. if (this._preActivateId === sceneRenderId) {
  19667. return;
  19668. }
  19669. this._preActivateId = sceneRenderId;
  19670. this._visibleInstances = null;
  19671. };
  19672. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  19673. if (this._visibleInstances) {
  19674. this._visibleInstances.intermediateDefaultRenderId = renderId;
  19675. }
  19676. };
  19677. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  19678. if (!this._visibleInstances) {
  19679. this._visibleInstances = {};
  19680. this._visibleInstances.defaultRenderId = renderId;
  19681. this._visibleInstances.selfDefaultRenderId = this._renderId;
  19682. }
  19683. if (!this._visibleInstances[renderId]) {
  19684. this._visibleInstances[renderId] = new Array();
  19685. }
  19686. this._visibleInstances[renderId].push(instance);
  19687. };
  19688. /**
  19689. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  19690. * This means the mesh underlying bounding box and sphere are recomputed.
  19691. */
  19692. Mesh.prototype.refreshBoundingInfo = function () {
  19693. if (this._boundingInfo.isLocked) {
  19694. return;
  19695. }
  19696. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19697. if (data) {
  19698. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  19699. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  19700. }
  19701. if (this.subMeshes) {
  19702. for (var index = 0; index < this.subMeshes.length; index++) {
  19703. this.subMeshes[index].refreshBoundingInfo();
  19704. }
  19705. }
  19706. this._updateBoundingInfo();
  19707. };
  19708. Mesh.prototype._createGlobalSubMesh = function () {
  19709. var totalVertices = this.getTotalVertices();
  19710. if (!totalVertices || !this.getIndices()) {
  19711. return null;
  19712. }
  19713. this.releaseSubMeshes();
  19714. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  19715. };
  19716. Mesh.prototype.subdivide = function (count) {
  19717. if (count < 1) {
  19718. return;
  19719. }
  19720. var totalIndices = this.getTotalIndices();
  19721. var subdivisionSize = (totalIndices / count) | 0;
  19722. var offset = 0;
  19723. // Ensure that subdivisionSize is a multiple of 3
  19724. while (subdivisionSize % 3 !== 0) {
  19725. subdivisionSize++;
  19726. }
  19727. this.releaseSubMeshes();
  19728. for (var index = 0; index < count; index++) {
  19729. if (offset >= totalIndices) {
  19730. break;
  19731. }
  19732. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  19733. offset += subdivisionSize;
  19734. }
  19735. this.synchronizeInstances();
  19736. };
  19737. /**
  19738. * Sets the vertex data of the mesh geometry for the requested `kind`.
  19739. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  19740. * The `data` are either a numeric array either a Float32Array.
  19741. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  19742. * 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).
  19743. * Note that a new underlying VertexBuffer object is created each call.
  19744. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  19745. *
  19746. * Possible `kind` values :
  19747. * - BABYLON.VertexBuffer.PositionKind
  19748. * - BABYLON.VertexBuffer.UVKind
  19749. * - BABYLON.VertexBuffer.UV2Kind
  19750. * - BABYLON.VertexBuffer.UV3Kind
  19751. * - BABYLON.VertexBuffer.UV4Kind
  19752. * - BABYLON.VertexBuffer.UV5Kind
  19753. * - BABYLON.VertexBuffer.UV6Kind
  19754. * - BABYLON.VertexBuffer.ColorKind
  19755. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19756. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19757. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19758. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19759. */
  19760. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  19761. if (!this._geometry) {
  19762. var vertexData = new BABYLON.VertexData();
  19763. vertexData.set(data, kind);
  19764. var scene = this.getScene();
  19765. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  19766. }
  19767. else {
  19768. this._geometry.setVerticesData(kind, data, updatable, stride);
  19769. }
  19770. };
  19771. Mesh.prototype.setVerticesBuffer = function (buffer) {
  19772. if (!this._geometry) {
  19773. var scene = this.getScene();
  19774. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  19775. }
  19776. this._geometry.setVerticesBuffer(buffer);
  19777. };
  19778. /**
  19779. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  19780. * If the mesh has no geometry, it is simply returned as it is.
  19781. * The `data` are either a numeric array either a Float32Array.
  19782. * No new underlying VertexBuffer object is created.
  19783. * 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.
  19784. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  19785. *
  19786. * Possible `kind` values :
  19787. * - BABYLON.VertexBuffer.PositionKind
  19788. * - BABYLON.VertexBuffer.UVKind
  19789. * - BABYLON.VertexBuffer.UV2Kind
  19790. * - BABYLON.VertexBuffer.UV3Kind
  19791. * - BABYLON.VertexBuffer.UV4Kind
  19792. * - BABYLON.VertexBuffer.UV5Kind
  19793. * - BABYLON.VertexBuffer.UV6Kind
  19794. * - BABYLON.VertexBuffer.ColorKind
  19795. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19796. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19797. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19798. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19799. */
  19800. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  19801. if (!this._geometry) {
  19802. return;
  19803. }
  19804. if (!makeItUnique) {
  19805. this._geometry.updateVerticesData(kind, data, updateExtends);
  19806. }
  19807. else {
  19808. this.makeGeometryUnique();
  19809. this.updateVerticesData(kind, data, updateExtends, false);
  19810. }
  19811. };
  19812. /**
  19813. * Deprecated since BabylonJS v2.3
  19814. */
  19815. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  19816. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  19817. if (!this._geometry) {
  19818. return;
  19819. }
  19820. if (!makeItUnique) {
  19821. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  19822. }
  19823. else {
  19824. this.makeGeometryUnique();
  19825. this.updateVerticesDataDirectly(kind, data, offset, false);
  19826. }
  19827. };
  19828. /**
  19829. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  19830. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  19831. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  19832. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  19833. */
  19834. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  19835. if (computeNormals === void 0) { computeNormals = true; }
  19836. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  19837. positionFunction(positions);
  19838. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  19839. if (computeNormals) {
  19840. var indices = this.getIndices();
  19841. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  19842. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  19843. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  19844. }
  19845. };
  19846. Mesh.prototype.makeGeometryUnique = function () {
  19847. if (!this._geometry) {
  19848. return;
  19849. }
  19850. var oldGeometry = this._geometry;
  19851. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  19852. oldGeometry.releaseForMesh(this, true);
  19853. geometry.applyToMesh(this);
  19854. };
  19855. /**
  19856. * Sets the mesh indices.
  19857. * Expects an array populated with integers or a Int32Array.
  19858. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  19859. * This method creates a new index buffer each call.
  19860. */
  19861. Mesh.prototype.setIndices = function (indices, totalVertices) {
  19862. if (!this._geometry) {
  19863. var vertexData = new BABYLON.VertexData();
  19864. vertexData.indices = indices;
  19865. var scene = this.getScene();
  19866. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  19867. }
  19868. else {
  19869. this._geometry.setIndices(indices, totalVertices);
  19870. }
  19871. };
  19872. /**
  19873. * Invert the geometry to move from a right handed system to a left handed one.
  19874. */
  19875. Mesh.prototype.toLeftHanded = function () {
  19876. if (!this._geometry) {
  19877. return;
  19878. }
  19879. this._geometry.toLeftHanded();
  19880. };
  19881. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  19882. var engine = this.getScene().getEngine();
  19883. // Wireframe
  19884. var indexToBind;
  19885. if (this._unIndexed) {
  19886. indexToBind = null;
  19887. }
  19888. else {
  19889. switch (fillMode) {
  19890. case BABYLON.Material.PointFillMode:
  19891. indexToBind = null;
  19892. break;
  19893. case BABYLON.Material.WireFrameFillMode:
  19894. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  19895. break;
  19896. default:
  19897. case BABYLON.Material.TriangleFillMode:
  19898. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  19899. break;
  19900. }
  19901. }
  19902. // VBOs
  19903. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  19904. };
  19905. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  19906. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  19907. return;
  19908. }
  19909. this.onBeforeDrawObservable.notifyObservers(this);
  19910. var engine = this.getScene().getEngine();
  19911. // Draw order
  19912. switch (fillMode) {
  19913. case BABYLON.Material.PointFillMode:
  19914. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19915. break;
  19916. case BABYLON.Material.WireFrameFillMode:
  19917. if (this._unIndexed) {
  19918. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19919. }
  19920. else {
  19921. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  19922. }
  19923. break;
  19924. default:
  19925. if (this._unIndexed) {
  19926. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  19927. }
  19928. else {
  19929. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  19930. }
  19931. }
  19932. };
  19933. /**
  19934. * Registers for this mesh a javascript function called just before the rendering process.
  19935. * This function is passed the current mesh and doesn't return anything.
  19936. */
  19937. Mesh.prototype.registerBeforeRender = function (func) {
  19938. this.onBeforeRenderObservable.add(func);
  19939. };
  19940. /**
  19941. * Disposes a previously registered javascript function called before the rendering.
  19942. * This function is passed the current mesh and doesn't return anything.
  19943. */
  19944. Mesh.prototype.unregisterBeforeRender = function (func) {
  19945. this.onBeforeRenderObservable.removeCallback(func);
  19946. };
  19947. /**
  19948. * Registers for this mesh a javascript function called just after the rendering is complete.
  19949. * This function is passed the current mesh and doesn't return anything.
  19950. */
  19951. Mesh.prototype.registerAfterRender = function (func) {
  19952. this.onAfterRenderObservable.add(func);
  19953. };
  19954. /**
  19955. * Disposes a previously registered javascript function called after the rendering.
  19956. * This function is passed the current mesh and doesn't return anything.
  19957. */
  19958. Mesh.prototype.unregisterAfterRender = function (func) {
  19959. this.onAfterRenderObservable.removeCallback(func);
  19960. };
  19961. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  19962. var scene = this.getScene();
  19963. this._batchCache.mustReturn = false;
  19964. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  19965. this._batchCache.visibleInstances[subMeshId] = null;
  19966. if (this._visibleInstances) {
  19967. var currentRenderId = scene.getRenderId();
  19968. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  19969. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  19970. var selfRenderId = this._renderId;
  19971. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  19972. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  19973. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  19974. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  19975. }
  19976. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  19977. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  19978. this._batchCache.mustReturn = true;
  19979. return this._batchCache;
  19980. }
  19981. if (currentRenderId !== selfRenderId) {
  19982. this._batchCache.renderSelf[subMeshId] = false;
  19983. }
  19984. }
  19985. this._renderIdForInstances[subMeshId] = currentRenderId;
  19986. }
  19987. return this._batchCache;
  19988. };
  19989. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  19990. var visibleInstances = batch.visibleInstances[subMesh._id];
  19991. var matricesCount = visibleInstances.length + 1;
  19992. var bufferSize = matricesCount * 16 * 4;
  19993. var currentInstancesBufferSize = this._instancesBufferSize;
  19994. var instancesBuffer = this._instancesBuffer;
  19995. while (this._instancesBufferSize < bufferSize) {
  19996. this._instancesBufferSize *= 2;
  19997. }
  19998. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  19999. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20000. }
  20001. var offset = 0;
  20002. var instancesCount = 0;
  20003. var world = this.getWorldMatrix();
  20004. if (batch.renderSelf[subMesh._id]) {
  20005. world.copyToArray(this._instancesData, offset);
  20006. offset += 16;
  20007. instancesCount++;
  20008. }
  20009. if (visibleInstances) {
  20010. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20011. var instance = visibleInstances[instanceIndex];
  20012. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20013. offset += 16;
  20014. instancesCount++;
  20015. }
  20016. }
  20017. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20018. if (instancesBuffer) {
  20019. instancesBuffer.dispose();
  20020. }
  20021. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20022. this._instancesBuffer = instancesBuffer;
  20023. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20024. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20025. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20026. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20027. }
  20028. else {
  20029. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20030. }
  20031. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  20032. this._draw(subMesh, fillMode, instancesCount);
  20033. engine.unbindInstanceAttributes();
  20034. };
  20035. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20036. var scene = this.getScene();
  20037. var engine = scene.getEngine();
  20038. if (hardwareInstancedRendering) {
  20039. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20040. }
  20041. else {
  20042. if (batch.renderSelf[subMesh._id]) {
  20043. // Draw
  20044. if (onBeforeDraw) {
  20045. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20046. }
  20047. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20048. }
  20049. if (batch.visibleInstances[subMesh._id]) {
  20050. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20051. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20052. // World
  20053. var world = instance.getWorldMatrix();
  20054. if (onBeforeDraw) {
  20055. onBeforeDraw(true, world, effectiveMaterial);
  20056. }
  20057. // Draw
  20058. this._draw(subMesh, fillMode);
  20059. }
  20060. }
  20061. }
  20062. };
  20063. /**
  20064. * Triggers the draw call for the mesh.
  20065. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20066. */
  20067. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20068. var scene = this.getScene();
  20069. // Managing instances
  20070. var batch = this._getInstancesRenderList(subMesh._id);
  20071. if (batch.mustReturn) {
  20072. return;
  20073. }
  20074. // Checking geometry state
  20075. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20076. return;
  20077. }
  20078. var callbackIndex;
  20079. this.onBeforeRenderObservable.notifyObservers(this);
  20080. var engine = scene.getEngine();
  20081. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20082. // Material
  20083. var effectiveMaterial = subMesh.getMaterial();
  20084. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20085. return;
  20086. }
  20087. // Outline - step 1
  20088. var savedDepthWrite = engine.getDepthWrite();
  20089. if (this.renderOutline) {
  20090. engine.setDepthWrite(false);
  20091. scene.getOutlineRenderer().render(subMesh, batch);
  20092. engine.setDepthWrite(savedDepthWrite);
  20093. }
  20094. effectiveMaterial._preBind();
  20095. var effect = effectiveMaterial.getEffect();
  20096. // Bind
  20097. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20098. this._bind(subMesh, effect, fillMode);
  20099. var world = this.getWorldMatrix();
  20100. effectiveMaterial.bind(world, this);
  20101. // Alpha mode
  20102. if (enableAlphaMode) {
  20103. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20104. }
  20105. // Draw
  20106. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20107. // Unbind
  20108. effectiveMaterial.unbind();
  20109. // Outline - step 2
  20110. if (this.renderOutline && savedDepthWrite) {
  20111. engine.setDepthWrite(true);
  20112. engine.setColorWrite(false);
  20113. scene.getOutlineRenderer().render(subMesh, batch);
  20114. engine.setColorWrite(true);
  20115. }
  20116. // Overlay
  20117. if (this.renderOverlay) {
  20118. var currentMode = engine.getAlphaMode();
  20119. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20120. scene.getOutlineRenderer().render(subMesh, batch, true);
  20121. engine.setAlphaMode(currentMode);
  20122. }
  20123. this.onAfterRenderObservable.notifyObservers(this);
  20124. };
  20125. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20126. if (isInstance) {
  20127. effectiveMaterial.bindOnlyWorldMatrix(world);
  20128. }
  20129. };
  20130. /**
  20131. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20132. */
  20133. Mesh.prototype.getEmittedParticleSystems = function () {
  20134. var results = new Array();
  20135. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20136. var particleSystem = this.getScene().particleSystems[index];
  20137. if (particleSystem.emitter === this) {
  20138. results.push(particleSystem);
  20139. }
  20140. }
  20141. return results;
  20142. };
  20143. /**
  20144. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20145. */
  20146. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20147. var results = new Array();
  20148. var descendants = this.getDescendants();
  20149. descendants.push(this);
  20150. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20151. var particleSystem = this.getScene().particleSystems[index];
  20152. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20153. results.push(particleSystem);
  20154. }
  20155. }
  20156. return results;
  20157. };
  20158. Mesh.prototype._checkDelayState = function () {
  20159. var scene = this.getScene();
  20160. if (this._geometry) {
  20161. this._geometry.load(scene);
  20162. }
  20163. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20164. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20165. this._queueLoad(this, scene);
  20166. }
  20167. };
  20168. Mesh.prototype._queueLoad = function (mesh, scene) {
  20169. var _this = this;
  20170. scene._addPendingData(mesh);
  20171. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20172. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20173. if (data instanceof ArrayBuffer) {
  20174. _this._delayLoadingFunction(data, _this);
  20175. }
  20176. else {
  20177. _this._delayLoadingFunction(JSON.parse(data), _this);
  20178. }
  20179. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20180. scene._removePendingData(_this);
  20181. }, function () { }, scene.database, getBinaryData);
  20182. };
  20183. /**
  20184. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20185. */
  20186. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20187. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20188. return false;
  20189. }
  20190. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20191. return false;
  20192. }
  20193. this._checkDelayState();
  20194. return true;
  20195. };
  20196. /**
  20197. * Sets the mesh material by the material or multiMaterial `id` property.
  20198. * The material `id` is a string identifying the material or the multiMaterial.
  20199. * This method returns nothing.
  20200. */
  20201. Mesh.prototype.setMaterialByID = function (id) {
  20202. var materials = this.getScene().materials;
  20203. var index;
  20204. for (index = 0; index < materials.length; index++) {
  20205. if (materials[index].id === id) {
  20206. this.material = materials[index];
  20207. return;
  20208. }
  20209. }
  20210. // Multi
  20211. var multiMaterials = this.getScene().multiMaterials;
  20212. for (index = 0; index < multiMaterials.length; index++) {
  20213. if (multiMaterials[index].id === id) {
  20214. this.material = multiMaterials[index];
  20215. return;
  20216. }
  20217. }
  20218. };
  20219. /**
  20220. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20221. */
  20222. Mesh.prototype.getAnimatables = function () {
  20223. var results = [];
  20224. if (this.material) {
  20225. results.push(this.material);
  20226. }
  20227. if (this.skeleton) {
  20228. results.push(this.skeleton);
  20229. }
  20230. return results;
  20231. };
  20232. /**
  20233. * Modifies the mesh geometry according to the passed transformation matrix.
  20234. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20235. * The mesh normals are modified accordingly the same transformation.
  20236. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20237. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20238. */
  20239. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20240. // Position
  20241. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20242. return;
  20243. }
  20244. var submeshes = this.subMeshes.splice(0);
  20245. this._resetPointsArrayCache();
  20246. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20247. var temp = [];
  20248. var index;
  20249. for (index = 0; index < data.length; index += 3) {
  20250. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20251. }
  20252. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20253. // Normals
  20254. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20255. return;
  20256. }
  20257. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20258. temp = [];
  20259. for (index = 0; index < data.length; index += 3) {
  20260. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20261. }
  20262. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20263. // flip faces?
  20264. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20265. this.flipFaces();
  20266. }
  20267. // Restore submeshes
  20268. this.releaseSubMeshes();
  20269. this.subMeshes = submeshes;
  20270. };
  20271. /**
  20272. * Modifies the mesh geometry according to its own current World Matrix.
  20273. * The mesh World Matrix is then reset.
  20274. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20275. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20276. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20277. */
  20278. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20279. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20280. this.scaling.copyFromFloats(1, 1, 1);
  20281. this.position.copyFromFloats(0, 0, 0);
  20282. this.rotation.copyFromFloats(0, 0, 0);
  20283. //only if quaternion is already set
  20284. if (this.rotationQuaternion) {
  20285. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20286. }
  20287. this._worldMatrix = BABYLON.Matrix.Identity();
  20288. };
  20289. // Cache
  20290. Mesh.prototype._resetPointsArrayCache = function () {
  20291. this._positions = null;
  20292. };
  20293. Mesh.prototype._generatePointsArray = function () {
  20294. if (this._positions)
  20295. return true;
  20296. this._positions = [];
  20297. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20298. if (!data) {
  20299. return false;
  20300. }
  20301. for (var index = 0; index < data.length; index += 3) {
  20302. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20303. }
  20304. return true;
  20305. };
  20306. /**
  20307. * Returns a new Mesh object generated from the current mesh properties.
  20308. * This method must not get confused with createInstance().
  20309. * The parameter `name` is a string, the name given to the new mesh.
  20310. * The optional parameter `newParent` can be any Node object (default `null`).
  20311. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20312. * 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.
  20313. */
  20314. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20315. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20316. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20317. };
  20318. /**
  20319. * Disposes the mesh.
  20320. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20321. */
  20322. Mesh.prototype.dispose = function (doNotRecurse) {
  20323. if (this._geometry) {
  20324. this._geometry.releaseForMesh(this, true);
  20325. }
  20326. // Instances
  20327. if (this._instancesBuffer) {
  20328. this._instancesBuffer.dispose();
  20329. this._instancesBuffer = null;
  20330. }
  20331. while (this.instances.length) {
  20332. this.instances[0].dispose();
  20333. }
  20334. // Highlight layers.
  20335. var highlightLayers = this.getScene().highlightLayers;
  20336. for (var i = 0; i < highlightLayers.length; i++) {
  20337. var highlightLayer = highlightLayers[i];
  20338. if (highlightLayer) {
  20339. highlightLayer.removeMesh(this);
  20340. highlightLayer.removeExcludedMesh(this);
  20341. }
  20342. }
  20343. _super.prototype.dispose.call(this, doNotRecurse);
  20344. };
  20345. /**
  20346. * Modifies the mesh geometry according to a displacement map.
  20347. * 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.
  20348. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20349. * This method returns nothing.
  20350. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20351. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20352. * 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.
  20353. */
  20354. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20355. var _this = this;
  20356. var scene = this.getScene();
  20357. var onload = function (img) {
  20358. // Getting height map data
  20359. var canvas = document.createElement("canvas");
  20360. var context = canvas.getContext("2d");
  20361. var heightMapWidth = img.width;
  20362. var heightMapHeight = img.height;
  20363. canvas.width = heightMapWidth;
  20364. canvas.height = heightMapHeight;
  20365. context.drawImage(img, 0, 0);
  20366. // Create VertexData from map data
  20367. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20368. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20369. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20370. //execute success callback, if set
  20371. if (onSuccess) {
  20372. onSuccess(_this);
  20373. }
  20374. };
  20375. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20376. };
  20377. /**
  20378. * Modifies the mesh geometry according to a displacementMap buffer.
  20379. * 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.
  20380. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20381. * This method returns nothing.
  20382. * 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.
  20383. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20384. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20385. */
  20386. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20387. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20388. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20389. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20390. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20391. return;
  20392. }
  20393. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20394. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20395. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20396. var position = BABYLON.Vector3.Zero();
  20397. var normal = BABYLON.Vector3.Zero();
  20398. var uv = BABYLON.Vector2.Zero();
  20399. for (var index = 0; index < positions.length; index += 3) {
  20400. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20401. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20402. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20403. // Compute height
  20404. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20405. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20406. var pos = (u + v * heightMapWidth) * 4;
  20407. var r = buffer[pos] / 255.0;
  20408. var g = buffer[pos + 1] / 255.0;
  20409. var b = buffer[pos + 2] / 255.0;
  20410. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20411. normal.normalize();
  20412. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20413. position = position.add(normal);
  20414. position.toArray(positions, index);
  20415. }
  20416. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20417. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20418. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20419. };
  20420. /**
  20421. * Modify the mesh to get a flat shading rendering.
  20422. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20423. * This method returns nothing.
  20424. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20425. */
  20426. Mesh.prototype.convertToFlatShadedMesh = function () {
  20427. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20428. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20429. var kinds = this.getVerticesDataKinds();
  20430. var vbs = [];
  20431. var data = [];
  20432. var newdata = [];
  20433. var updatableNormals = false;
  20434. var kindIndex;
  20435. var kind;
  20436. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20437. kind = kinds[kindIndex];
  20438. var vertexBuffer = this.getVertexBuffer(kind);
  20439. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20440. updatableNormals = vertexBuffer.isUpdatable();
  20441. kinds.splice(kindIndex, 1);
  20442. kindIndex--;
  20443. continue;
  20444. }
  20445. vbs[kind] = vertexBuffer;
  20446. data[kind] = vbs[kind].getData();
  20447. newdata[kind] = [];
  20448. }
  20449. // Save previous submeshes
  20450. var previousSubmeshes = this.subMeshes.slice(0);
  20451. var indices = this.getIndices();
  20452. var totalIndices = this.getTotalIndices();
  20453. // Generating unique vertices per face
  20454. var index;
  20455. for (index = 0; index < totalIndices; index++) {
  20456. var vertexIndex = indices[index];
  20457. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20458. kind = kinds[kindIndex];
  20459. var stride = vbs[kind].getStrideSize();
  20460. for (var offset = 0; offset < stride; offset++) {
  20461. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20462. }
  20463. }
  20464. }
  20465. // Updating faces & normal
  20466. var normals = [];
  20467. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20468. for (index = 0; index < totalIndices; index += 3) {
  20469. indices[index] = index;
  20470. indices[index + 1] = index + 1;
  20471. indices[index + 2] = index + 2;
  20472. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20473. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20474. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20475. var p1p2 = p1.subtract(p2);
  20476. var p3p2 = p3.subtract(p2);
  20477. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20478. // Store same normals for every vertex
  20479. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20480. normals.push(normal.x);
  20481. normals.push(normal.y);
  20482. normals.push(normal.z);
  20483. }
  20484. }
  20485. this.setIndices(indices);
  20486. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20487. // Updating vertex buffers
  20488. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20489. kind = kinds[kindIndex];
  20490. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20491. }
  20492. // Updating submeshes
  20493. this.releaseSubMeshes();
  20494. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20495. var previousOne = previousSubmeshes[submeshIndex];
  20496. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20497. }
  20498. this.synchronizeInstances();
  20499. };
  20500. /**
  20501. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  20502. * In other words, more vertices, no more indices and a single bigger VBO.
  20503. * This method returns nothing.
  20504. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  20505. *
  20506. */
  20507. Mesh.prototype.convertToUnIndexedMesh = function () {
  20508. /// <summary>Remove indices by unfolding faces into buffers</summary>
  20509. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20510. var kinds = this.getVerticesDataKinds();
  20511. var vbs = [];
  20512. var data = [];
  20513. var newdata = [];
  20514. var updatableNormals = false;
  20515. var kindIndex;
  20516. var kind;
  20517. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20518. kind = kinds[kindIndex];
  20519. var vertexBuffer = this.getVertexBuffer(kind);
  20520. vbs[kind] = vertexBuffer;
  20521. data[kind] = vbs[kind].getData();
  20522. newdata[kind] = [];
  20523. }
  20524. // Save previous submeshes
  20525. var previousSubmeshes = this.subMeshes.slice(0);
  20526. var indices = this.getIndices();
  20527. var totalIndices = this.getTotalIndices();
  20528. // Generating unique vertices per face
  20529. var index;
  20530. for (index = 0; index < totalIndices; index++) {
  20531. var vertexIndex = indices[index];
  20532. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20533. kind = kinds[kindIndex];
  20534. var stride = vbs[kind].getStrideSize();
  20535. for (var offset = 0; offset < stride; offset++) {
  20536. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20537. }
  20538. }
  20539. }
  20540. // Updating indices
  20541. for (index = 0; index < totalIndices; index += 3) {
  20542. indices[index] = index;
  20543. indices[index + 1] = index + 1;
  20544. indices[index + 2] = index + 2;
  20545. }
  20546. this.setIndices(indices);
  20547. // Updating vertex buffers
  20548. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20549. kind = kinds[kindIndex];
  20550. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20551. }
  20552. // Updating submeshes
  20553. this.releaseSubMeshes();
  20554. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  20555. var previousOne = previousSubmeshes[submeshIndex];
  20556. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  20557. }
  20558. this._unIndexed = true;
  20559. this.synchronizeInstances();
  20560. };
  20561. /**
  20562. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  20563. * This method returns nothing.
  20564. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  20565. */
  20566. Mesh.prototype.flipFaces = function (flipNormals) {
  20567. if (flipNormals === void 0) { flipNormals = false; }
  20568. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  20569. var i;
  20570. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20571. for (i = 0; i < vertex_data.normals.length; i++) {
  20572. vertex_data.normals[i] *= -1;
  20573. }
  20574. }
  20575. var temp;
  20576. for (i = 0; i < vertex_data.indices.length; i += 3) {
  20577. // reassign indices
  20578. temp = vertex_data.indices[i + 1];
  20579. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  20580. vertex_data.indices[i + 2] = temp;
  20581. }
  20582. vertex_data.applyToMesh(this);
  20583. };
  20584. // Instances
  20585. /**
  20586. * Creates a new InstancedMesh object from the mesh model.
  20587. * An instance shares the same properties and the same material than its model.
  20588. * Only these properties of each instance can then be set individually :
  20589. * - position
  20590. * - rotation
  20591. * - rotationQuaternion
  20592. * - setPivotMatrix
  20593. * - scaling
  20594. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  20595. * Warning : this method is not supported for Line mesh and LineSystem
  20596. */
  20597. Mesh.prototype.createInstance = function (name) {
  20598. return new BABYLON.InstancedMesh(name, this);
  20599. };
  20600. /**
  20601. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  20602. * After this call, all the mesh instances have the same submeshes than the current mesh.
  20603. * This method returns nothing.
  20604. */
  20605. Mesh.prototype.synchronizeInstances = function () {
  20606. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  20607. var instance = this.instances[instanceIndex];
  20608. instance._syncSubMeshes();
  20609. }
  20610. };
  20611. /**
  20612. * Simplify the mesh according to the given array of settings.
  20613. * Function will return immediately and will simplify async. It returns nothing.
  20614. * @param settings a collection of simplification settings.
  20615. * @param parallelProcessing should all levels calculate parallel or one after the other.
  20616. * @param type the type of simplification to run.
  20617. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  20618. */
  20619. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  20620. if (parallelProcessing === void 0) { parallelProcessing = true; }
  20621. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  20622. this.getScene().simplificationQueue.addTask({
  20623. settings: settings,
  20624. parallelProcessing: parallelProcessing,
  20625. mesh: this,
  20626. simplificationType: simplificationType,
  20627. successCallback: successCallback
  20628. });
  20629. };
  20630. /**
  20631. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  20632. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  20633. * This should be used together with the simplification to avoid disappearing triangles.
  20634. * @param successCallback an optional success callback to be called after the optimization finished.
  20635. */
  20636. Mesh.prototype.optimizeIndices = function (successCallback) {
  20637. var _this = this;
  20638. var indices = this.getIndices();
  20639. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20640. var vectorPositions = [];
  20641. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  20642. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  20643. }
  20644. var dupes = [];
  20645. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  20646. var realPos = vectorPositions.length - 1 - iteration;
  20647. var testedPosition = vectorPositions[realPos];
  20648. for (var j = 0; j < realPos; ++j) {
  20649. var againstPosition = vectorPositions[j];
  20650. if (testedPosition.equals(againstPosition)) {
  20651. dupes[realPos] = j;
  20652. break;
  20653. }
  20654. }
  20655. }, function () {
  20656. for (var i = 0; i < indices.length; ++i) {
  20657. indices[i] = dupes[indices[i]] || indices[i];
  20658. }
  20659. //indices are now reordered
  20660. var originalSubMeshes = _this.subMeshes.slice(0);
  20661. _this.setIndices(indices);
  20662. _this.subMeshes = originalSubMeshes;
  20663. if (successCallback) {
  20664. successCallback(_this);
  20665. }
  20666. });
  20667. };
  20668. // Statics
  20669. /**
  20670. * Returns a new Mesh object what is a deep copy of the passed mesh.
  20671. * The parameter `parsedMesh` is the mesh to be copied.
  20672. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20673. */
  20674. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  20675. var mesh = new Mesh(parsedMesh.name, scene);
  20676. mesh.id = parsedMesh.id;
  20677. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  20678. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  20679. if (parsedMesh.metadata !== undefined) {
  20680. mesh.metadata = parsedMesh.metadata;
  20681. }
  20682. if (parsedMesh.rotationQuaternion) {
  20683. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  20684. }
  20685. else if (parsedMesh.rotation) {
  20686. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  20687. }
  20688. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  20689. if (parsedMesh.localMatrix) {
  20690. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  20691. }
  20692. else if (parsedMesh.pivotMatrix) {
  20693. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  20694. }
  20695. mesh.setEnabled(parsedMesh.isEnabled);
  20696. mesh.isVisible = parsedMesh.isVisible;
  20697. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  20698. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  20699. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  20700. if (parsedMesh.applyFog !== undefined) {
  20701. mesh.applyFog = parsedMesh.applyFog;
  20702. }
  20703. if (parsedMesh.pickable !== undefined) {
  20704. mesh.isPickable = parsedMesh.pickable;
  20705. }
  20706. if (parsedMesh.alphaIndex !== undefined) {
  20707. mesh.alphaIndex = parsedMesh.alphaIndex;
  20708. }
  20709. mesh.receiveShadows = parsedMesh.receiveShadows;
  20710. mesh.billboardMode = parsedMesh.billboardMode;
  20711. if (parsedMesh.visibility !== undefined) {
  20712. mesh.visibility = parsedMesh.visibility;
  20713. }
  20714. mesh.checkCollisions = parsedMesh.checkCollisions;
  20715. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  20716. // freezeWorldMatrix
  20717. if (parsedMesh.freezeWorldMatrix) {
  20718. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  20719. }
  20720. // Parent
  20721. if (parsedMesh.parentId) {
  20722. mesh._waitingParentId = parsedMesh.parentId;
  20723. }
  20724. // Actions
  20725. if (parsedMesh.actions !== undefined) {
  20726. mesh._waitingActions = parsedMesh.actions;
  20727. }
  20728. // Geometry
  20729. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  20730. if (parsedMesh.delayLoadingFile) {
  20731. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20732. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  20733. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  20734. if (parsedMesh._binaryInfo) {
  20735. mesh._binaryInfo = parsedMesh._binaryInfo;
  20736. }
  20737. mesh._delayInfo = [];
  20738. if (parsedMesh.hasUVs) {
  20739. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  20740. }
  20741. if (parsedMesh.hasUVs2) {
  20742. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  20743. }
  20744. if (parsedMesh.hasUVs3) {
  20745. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  20746. }
  20747. if (parsedMesh.hasUVs4) {
  20748. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  20749. }
  20750. if (parsedMesh.hasUVs5) {
  20751. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  20752. }
  20753. if (parsedMesh.hasUVs6) {
  20754. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  20755. }
  20756. if (parsedMesh.hasColors) {
  20757. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  20758. }
  20759. if (parsedMesh.hasMatricesIndices) {
  20760. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  20761. }
  20762. if (parsedMesh.hasMatricesWeights) {
  20763. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  20764. }
  20765. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  20766. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  20767. mesh._checkDelayState();
  20768. }
  20769. }
  20770. else {
  20771. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  20772. }
  20773. // Material
  20774. if (parsedMesh.materialId) {
  20775. mesh.setMaterialByID(parsedMesh.materialId);
  20776. }
  20777. else {
  20778. mesh.material = null;
  20779. }
  20780. // Skeleton
  20781. if (parsedMesh.skeletonId > -1) {
  20782. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  20783. if (parsedMesh.numBoneInfluencers) {
  20784. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  20785. }
  20786. }
  20787. // Animations
  20788. if (parsedMesh.animations) {
  20789. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20790. var parsedAnimation = parsedMesh.animations[animationIndex];
  20791. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20792. }
  20793. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  20794. }
  20795. if (parsedMesh.autoAnimate) {
  20796. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  20797. }
  20798. // Layer Mask
  20799. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  20800. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  20801. }
  20802. else {
  20803. mesh.layerMask = 0x0FFFFFFF;
  20804. }
  20805. //(Deprecated) physics
  20806. if (parsedMesh.physicsImpostor) {
  20807. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  20808. mass: parsedMesh.physicsMass,
  20809. friction: parsedMesh.physicsFriction,
  20810. restitution: parsedMesh.physicsRestitution
  20811. }, scene);
  20812. }
  20813. // Instances
  20814. if (parsedMesh.instances) {
  20815. for (var index = 0; index < parsedMesh.instances.length; index++) {
  20816. var parsedInstance = parsedMesh.instances[index];
  20817. var instance = mesh.createInstance(parsedInstance.name);
  20818. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  20819. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  20820. if (parsedInstance.parentId) {
  20821. instance._waitingParentId = parsedInstance.parentId;
  20822. }
  20823. if (parsedInstance.rotationQuaternion) {
  20824. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  20825. }
  20826. else if (parsedInstance.rotation) {
  20827. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  20828. }
  20829. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  20830. instance.checkCollisions = mesh.checkCollisions;
  20831. if (parsedMesh.animations) {
  20832. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  20833. parsedAnimation = parsedMesh.animations[animationIndex];
  20834. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20835. }
  20836. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  20837. }
  20838. }
  20839. }
  20840. return mesh;
  20841. };
  20842. /**
  20843. * Creates a ribbon mesh.
  20844. * Please consider using the same method from the MeshBuilder class instead.
  20845. * 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.
  20846. *
  20847. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  20848. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  20849. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  20850. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  20851. * 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.
  20852. * 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.
  20853. * 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
  20854. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20855. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20856. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20857. */
  20858. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  20859. return BABYLON.MeshBuilder.CreateRibbon(name, {
  20860. pathArray: pathArray,
  20861. closeArray: closeArray,
  20862. closePath: closePath,
  20863. offset: offset,
  20864. updatable: updatable,
  20865. sideOrientation: sideOrientation,
  20866. instance: instance
  20867. }, scene);
  20868. };
  20869. /**
  20870. * Creates a plane polygonal mesh. By default, this is a disc.
  20871. * Please consider using the same method from the MeshBuilder class instead.
  20872. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  20873. * 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.
  20874. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20875. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20876. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20877. */
  20878. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  20879. var options = {
  20880. radius: radius,
  20881. tessellation: tessellation,
  20882. sideOrientation: sideOrientation,
  20883. updatable: updatable
  20884. };
  20885. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  20886. };
  20887. /**
  20888. * Creates a box mesh.
  20889. * Please consider using the same method from the MeshBuilder class instead.
  20890. * The parameter `size` sets the size (float) of each box side (default 1).
  20891. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20892. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20893. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20894. */
  20895. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  20896. var options = {
  20897. size: size,
  20898. sideOrientation: sideOrientation,
  20899. updatable: updatable
  20900. };
  20901. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  20902. };
  20903. /**
  20904. * Creates a sphere mesh.
  20905. * Please consider using the same method from the MeshBuilder class instead.
  20906. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  20907. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  20908. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20909. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20910. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20911. */
  20912. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  20913. var options = {
  20914. segments: segments,
  20915. diameterX: diameter,
  20916. diameterY: diameter,
  20917. diameterZ: diameter,
  20918. sideOrientation: sideOrientation,
  20919. updatable: updatable
  20920. };
  20921. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  20922. };
  20923. /**
  20924. * Creates a cylinder or a cone mesh.
  20925. * Please consider using the same method from the MeshBuilder class instead.
  20926. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  20927. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  20928. * 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.
  20929. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  20930. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  20931. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20932. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20933. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20934. */
  20935. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  20936. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  20937. if (scene !== undefined) {
  20938. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  20939. updatable = scene;
  20940. }
  20941. scene = subdivisions;
  20942. subdivisions = 1;
  20943. }
  20944. var options = {
  20945. height: height,
  20946. diameterTop: diameterTop,
  20947. diameterBottom: diameterBottom,
  20948. tessellation: tessellation,
  20949. subdivisions: subdivisions,
  20950. sideOrientation: sideOrientation,
  20951. updatable: updatable
  20952. };
  20953. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  20954. };
  20955. // Torus (Code from SharpDX.org)
  20956. /**
  20957. * Creates a torus mesh.
  20958. * Please consider using the same method from the MeshBuilder class instead.
  20959. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  20960. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  20961. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  20962. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20963. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20964. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20965. */
  20966. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  20967. var options = {
  20968. diameter: diameter,
  20969. thickness: thickness,
  20970. tessellation: tessellation,
  20971. sideOrientation: sideOrientation,
  20972. updatable: updatable
  20973. };
  20974. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  20975. };
  20976. /**
  20977. * Creates a torus knot mesh.
  20978. * Please consider using the same method from the MeshBuilder class instead.
  20979. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  20980. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  20981. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  20982. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  20983. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  20984. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  20985. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  20986. */
  20987. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  20988. var options = {
  20989. radius: radius,
  20990. tube: tube,
  20991. radialSegments: radialSegments,
  20992. tubularSegments: tubularSegments,
  20993. p: p,
  20994. q: q,
  20995. sideOrientation: sideOrientation,
  20996. updatable: updatable
  20997. };
  20998. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  20999. };
  21000. /**
  21001. * Creates a line mesh.
  21002. * Please consider using the same method from the MeshBuilder class instead.
  21003. * 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.
  21004. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21005. * The parameter `points` is an array successive Vector3.
  21006. * 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
  21007. * When updating an instance, remember that only point positions can change, not the number of points.
  21008. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21009. */
  21010. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21011. var options = {
  21012. points: points,
  21013. updatable: updatable,
  21014. instance: instance
  21015. };
  21016. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21017. };
  21018. /**
  21019. * Creates a dashed line mesh.
  21020. * Please consider using the same method from the MeshBuilder class instead.
  21021. * 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.
  21022. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21023. * The parameter `points` is an array successive Vector3.
  21024. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21025. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21026. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21027. * 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
  21028. * When updating an instance, remember that only point positions can change, not the number of points.
  21029. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21030. */
  21031. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21032. var options = {
  21033. points: points,
  21034. dashSize: dashSize,
  21035. gapSize: gapSize,
  21036. dashNb: dashNb,
  21037. updatable: updatable,
  21038. instance: instance
  21039. };
  21040. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21041. };
  21042. /**
  21043. * Creates an extruded shape mesh.
  21044. * 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.
  21045. * Please consider using the same method from the MeshBuilder class instead.
  21046. *
  21047. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21048. * 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
  21049. * extruded along the Z axis.
  21050. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21051. * 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.
  21052. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21053. * 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
  21054. * 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
  21055. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21056. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21057. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21058. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21059. */
  21060. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21061. var options = {
  21062. shape: shape,
  21063. path: path,
  21064. scale: scale,
  21065. rotation: rotation,
  21066. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21067. sideOrientation: sideOrientation,
  21068. instance: instance,
  21069. updatable: updatable
  21070. };
  21071. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21072. };
  21073. /**
  21074. * Creates an custom extruded shape mesh.
  21075. * 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.
  21076. * Please consider using the same method from the MeshBuilder class instead.
  21077. *
  21078. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21079. * 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
  21080. * extruded along the Z axis.
  21081. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21082. * 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
  21083. * and the distance of this point from the begining of the path :
  21084. * ```javascript
  21085. * var rotationFunction = function(i, distance) {
  21086. * // do things
  21087. * return rotationValue; }
  21088. * ```
  21089. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21090. * 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
  21091. * and the distance of this point from the begining of the path :
  21092. * ```javascript
  21093. * var scaleFunction = function(i, distance) {
  21094. * // do things
  21095. * return scaleValue;}
  21096. * ```
  21097. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21098. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21099. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21100. * 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
  21101. * 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
  21102. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21103. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21104. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21105. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21106. */
  21107. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21108. var options = {
  21109. shape: shape,
  21110. path: path,
  21111. scaleFunction: scaleFunction,
  21112. rotationFunction: rotationFunction,
  21113. ribbonCloseArray: ribbonCloseArray,
  21114. ribbonClosePath: ribbonClosePath,
  21115. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21116. sideOrientation: sideOrientation,
  21117. instance: instance,
  21118. updatable: updatable
  21119. };
  21120. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21121. };
  21122. /**
  21123. * Creates lathe mesh.
  21124. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21125. * Please consider using the same method from the MeshBuilder class instead.
  21126. * 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
  21127. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21128. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21129. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21130. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21131. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21132. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21133. */
  21134. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21135. var options = {
  21136. shape: shape,
  21137. radius: radius,
  21138. tessellation: tessellation,
  21139. sideOrientation: sideOrientation,
  21140. updatable: updatable
  21141. };
  21142. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21143. };
  21144. /**
  21145. * Creates a plane mesh.
  21146. * Please consider using the same method from the MeshBuilder class instead.
  21147. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21148. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21149. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21150. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21151. */
  21152. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21153. var options = {
  21154. size: size,
  21155. width: size,
  21156. height: size,
  21157. sideOrientation: sideOrientation,
  21158. updatable: updatable
  21159. };
  21160. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21161. };
  21162. /**
  21163. * Creates a ground mesh.
  21164. * Please consider using the same method from the MeshBuilder class instead.
  21165. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21166. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21167. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21168. */
  21169. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21170. var options = {
  21171. width: width,
  21172. height: height,
  21173. subdivisions: subdivisions,
  21174. updatable: updatable
  21175. };
  21176. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21177. };
  21178. /**
  21179. * Creates a tiled ground mesh.
  21180. * Please consider using the same method from the MeshBuilder class instead.
  21181. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21182. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21183. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21184. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21185. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21186. * numbers of subdivisions on the ground width and height of each tile.
  21187. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21188. */
  21189. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21190. var options = {
  21191. xmin: xmin,
  21192. zmin: zmin,
  21193. xmax: xmax,
  21194. zmax: zmax,
  21195. subdivisions: subdivisions,
  21196. precision: precision,
  21197. updatable: updatable
  21198. };
  21199. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21200. };
  21201. /**
  21202. * Creates a ground mesh from a height map.
  21203. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21204. * Please consider using the same method from the MeshBuilder class instead.
  21205. * The parameter `url` sets the URL of the height map image resource.
  21206. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21207. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21208. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21209. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21210. * 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).
  21211. * This function is passed the newly built mesh :
  21212. * ```javascript
  21213. * function(mesh) { // do things
  21214. * return; }
  21215. * ```
  21216. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21217. */
  21218. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21219. var options = {
  21220. width: width,
  21221. height: height,
  21222. subdivisions: subdivisions,
  21223. minHeight: minHeight,
  21224. maxHeight: maxHeight,
  21225. updatable: updatable,
  21226. onReady: onReady
  21227. };
  21228. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21229. };
  21230. /**
  21231. * Creates a tube mesh.
  21232. * 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.
  21233. * Please consider using the same method from the MeshBuilder class instead.
  21234. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21235. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21236. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21237. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21238. * 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.
  21239. * It must return a radius value (positive float) :
  21240. * ```javascript
  21241. * var radiusFunction = function(i, distance) {
  21242. * // do things
  21243. * return radius; }
  21244. * ```
  21245. * 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
  21246. * 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
  21247. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21248. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21249. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21250. */
  21251. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21252. var options = {
  21253. path: path,
  21254. radius: radius,
  21255. tessellation: tessellation,
  21256. radiusFunction: radiusFunction,
  21257. arc: 1,
  21258. cap: cap,
  21259. updatable: updatable,
  21260. sideOrientation: sideOrientation,
  21261. instance: instance
  21262. };
  21263. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21264. };
  21265. /**
  21266. * Creates a polyhedron mesh.
  21267. * Please consider using the same method from the MeshBuilder class instead.
  21268. * 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
  21269. * to choose the wanted type.
  21270. * The parameter `size` (positive float, default 1) sets the polygon size.
  21271. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21272. * 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`.
  21273. * 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
  21274. * 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)`).
  21275. * 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
  21276. * 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.
  21277. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21278. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21279. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21280. */
  21281. Mesh.CreatePolyhedron = function (name, options, scene) {
  21282. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21283. };
  21284. /**
  21285. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21286. * Please consider using the same method from the MeshBuilder class instead.
  21287. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21288. * 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`).
  21289. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21290. * 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.
  21291. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21292. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21293. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21294. */
  21295. Mesh.CreateIcoSphere = function (name, options, scene) {
  21296. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21297. };
  21298. /**
  21299. * Creates a decal mesh.
  21300. * Please consider using the same method from the MeshBuilder class instead.
  21301. * 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.
  21302. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21303. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21304. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21305. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21306. */
  21307. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21308. var options = {
  21309. position: position,
  21310. normal: normal,
  21311. size: size,
  21312. angle: angle
  21313. };
  21314. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21315. };
  21316. // Skeletons
  21317. /**
  21318. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21319. */
  21320. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21321. var source;
  21322. if (!this._sourcePositions) {
  21323. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21324. this._sourcePositions = new Float32Array(source);
  21325. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21326. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21327. }
  21328. }
  21329. return this._sourcePositions;
  21330. };
  21331. /**
  21332. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21333. */
  21334. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21335. var source;
  21336. if (!this._sourceNormals) {
  21337. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21338. this._sourceNormals = new Float32Array(source);
  21339. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21340. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21341. }
  21342. }
  21343. return this._sourceNormals;
  21344. };
  21345. /**
  21346. * Update the vertex buffers by applying transformation from the bones
  21347. * @param {skeleton} skeleton to apply
  21348. */
  21349. Mesh.prototype.applySkeleton = function (skeleton) {
  21350. if (!this.geometry) {
  21351. return;
  21352. }
  21353. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21354. return;
  21355. }
  21356. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21357. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21358. return this;
  21359. }
  21360. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21361. return this;
  21362. }
  21363. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21364. return this;
  21365. }
  21366. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21367. return this;
  21368. }
  21369. if (!this._sourcePositions) {
  21370. this.setPositionsForCPUSkinning();
  21371. }
  21372. if (!this._sourceNormals) {
  21373. this.setNormalsForCPUSkinning();
  21374. }
  21375. // positionsData checks for not being Float32Array will only pass at most once
  21376. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21377. if (!(positionsData instanceof Float32Array)) {
  21378. positionsData = new Float32Array(positionsData);
  21379. }
  21380. // normalsData checks for not being Float32Array will only pass at most once
  21381. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21382. if (!(normalsData instanceof Float32Array)) {
  21383. normalsData = new Float32Array(normalsData);
  21384. }
  21385. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21386. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21387. var needExtras = this.numBoneInfluencers > 4;
  21388. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21389. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21390. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21391. var tempVector3 = BABYLON.Vector3.Zero();
  21392. var finalMatrix = new BABYLON.Matrix();
  21393. var tempMatrix = new BABYLON.Matrix();
  21394. var matWeightIdx = 0;
  21395. var inf;
  21396. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21397. var weight;
  21398. for (inf = 0; inf < 4; inf++) {
  21399. weight = matricesWeightsData[matWeightIdx + inf];
  21400. if (weight > 0) {
  21401. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21402. finalMatrix.addToSelf(tempMatrix);
  21403. }
  21404. else
  21405. break;
  21406. }
  21407. if (needExtras) {
  21408. for (inf = 0; inf < 4; inf++) {
  21409. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21410. if (weight > 0) {
  21411. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21412. finalMatrix.addToSelf(tempMatrix);
  21413. }
  21414. else
  21415. break;
  21416. }
  21417. }
  21418. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21419. tempVector3.toArray(positionsData, index);
  21420. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21421. tempVector3.toArray(normalsData, index);
  21422. finalMatrix.reset();
  21423. }
  21424. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21425. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21426. return this;
  21427. };
  21428. // Tools
  21429. /**
  21430. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21431. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21432. */
  21433. Mesh.MinMax = function (meshes) {
  21434. var minVector = null;
  21435. var maxVector = null;
  21436. meshes.forEach(function (mesh, index, array) {
  21437. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21438. if (!minVector) {
  21439. minVector = boundingBox.minimumWorld;
  21440. maxVector = boundingBox.maximumWorld;
  21441. }
  21442. else {
  21443. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21444. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21445. }
  21446. });
  21447. return {
  21448. min: minVector,
  21449. max: maxVector
  21450. };
  21451. };
  21452. /**
  21453. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21454. */
  21455. Mesh.Center = function (meshesOrMinMaxVector) {
  21456. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21457. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21458. };
  21459. /**
  21460. * Merge the array of meshes into a single mesh for performance reasons.
  21461. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21462. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21463. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21464. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21465. */
  21466. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21467. if (disposeSource === void 0) { disposeSource = true; }
  21468. var index;
  21469. if (!allow32BitsIndices) {
  21470. var totalVertices = 0;
  21471. // Counting vertices
  21472. for (index = 0; index < meshes.length; index++) {
  21473. if (meshes[index]) {
  21474. totalVertices += meshes[index].getTotalVertices();
  21475. if (totalVertices > 65536) {
  21476. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21477. return null;
  21478. }
  21479. }
  21480. }
  21481. }
  21482. // Merge
  21483. var vertexData;
  21484. var otherVertexData;
  21485. var source;
  21486. for (index = 0; index < meshes.length; index++) {
  21487. if (meshes[index]) {
  21488. meshes[index].computeWorldMatrix(true);
  21489. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  21490. otherVertexData.transform(meshes[index].getWorldMatrix());
  21491. if (vertexData) {
  21492. vertexData.merge(otherVertexData);
  21493. }
  21494. else {
  21495. vertexData = otherVertexData;
  21496. source = meshes[index];
  21497. }
  21498. }
  21499. }
  21500. if (!meshSubclass) {
  21501. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  21502. }
  21503. vertexData.applyToMesh(meshSubclass);
  21504. // Setting properties
  21505. meshSubclass.material = source.material;
  21506. meshSubclass.checkCollisions = source.checkCollisions;
  21507. // Cleaning
  21508. if (disposeSource) {
  21509. for (index = 0; index < meshes.length; index++) {
  21510. if (meshes[index]) {
  21511. meshes[index].dispose();
  21512. }
  21513. }
  21514. }
  21515. return meshSubclass;
  21516. };
  21517. // Consts
  21518. Mesh._FRONTSIDE = 0;
  21519. Mesh._BACKSIDE = 1;
  21520. Mesh._DOUBLESIDE = 2;
  21521. Mesh._DEFAULTSIDE = 0;
  21522. Mesh._NO_CAP = 0;
  21523. Mesh._CAP_START = 1;
  21524. Mesh._CAP_END = 2;
  21525. Mesh._CAP_ALL = 3;
  21526. return Mesh;
  21527. }(BABYLON.AbstractMesh));
  21528. BABYLON.Mesh = Mesh;
  21529. })(BABYLON || (BABYLON = {}));
  21530. var BABYLON;
  21531. (function (BABYLON) {
  21532. var SubMesh = (function () {
  21533. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  21534. if (createBoundingBox === void 0) { createBoundingBox = true; }
  21535. this.materialIndex = materialIndex;
  21536. this.verticesStart = verticesStart;
  21537. this.verticesCount = verticesCount;
  21538. this.indexStart = indexStart;
  21539. this.indexCount = indexCount;
  21540. this._renderId = 0;
  21541. this._mesh = mesh;
  21542. this._renderingMesh = renderingMesh || mesh;
  21543. mesh.subMeshes.push(this);
  21544. this._trianglePlanes = [];
  21545. this._id = mesh.subMeshes.length - 1;
  21546. if (createBoundingBox) {
  21547. this.refreshBoundingInfo();
  21548. mesh.computeWorldMatrix(true);
  21549. }
  21550. }
  21551. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  21552. get: function () {
  21553. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  21554. },
  21555. enumerable: true,
  21556. configurable: true
  21557. });
  21558. SubMesh.prototype.getBoundingInfo = function () {
  21559. if (this.IsGlobal) {
  21560. return this._mesh.getBoundingInfo();
  21561. }
  21562. return this._boundingInfo;
  21563. };
  21564. SubMesh.prototype.getMesh = function () {
  21565. return this._mesh;
  21566. };
  21567. SubMesh.prototype.getRenderingMesh = function () {
  21568. return this._renderingMesh;
  21569. };
  21570. SubMesh.prototype.getMaterial = function () {
  21571. var rootMaterial = this._renderingMesh.material;
  21572. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  21573. var multiMaterial = rootMaterial;
  21574. return multiMaterial.getSubMaterial(this.materialIndex);
  21575. }
  21576. if (!rootMaterial) {
  21577. return this._mesh.getScene().defaultMaterial;
  21578. }
  21579. return rootMaterial;
  21580. };
  21581. // Methods
  21582. SubMesh.prototype.refreshBoundingInfo = function () {
  21583. this._lastColliderWorldVertices = null;
  21584. if (this.IsGlobal) {
  21585. return;
  21586. }
  21587. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21588. if (!data) {
  21589. this._boundingInfo = this._mesh._boundingInfo;
  21590. return;
  21591. }
  21592. var indices = this._renderingMesh.getIndices();
  21593. var extend;
  21594. //is this the only submesh?
  21595. if (this.indexStart === 0 && this.indexCount === indices.length) {
  21596. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  21597. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  21598. }
  21599. else {
  21600. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  21601. }
  21602. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21603. };
  21604. SubMesh.prototype._checkCollision = function (collider) {
  21605. return this.getBoundingInfo()._checkCollision(collider);
  21606. };
  21607. SubMesh.prototype.updateBoundingInfo = function (world) {
  21608. if (!this.getBoundingInfo()) {
  21609. this.refreshBoundingInfo();
  21610. }
  21611. this.getBoundingInfo().update(world);
  21612. };
  21613. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  21614. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  21615. };
  21616. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21617. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  21618. };
  21619. SubMesh.prototype.render = function (enableAlphaMode) {
  21620. this._renderingMesh.render(this, enableAlphaMode);
  21621. };
  21622. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  21623. if (!this._linesIndexBuffer) {
  21624. var linesIndices = [];
  21625. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21626. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  21627. }
  21628. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  21629. this.linesIndexCount = linesIndices.length;
  21630. }
  21631. return this._linesIndexBuffer;
  21632. };
  21633. SubMesh.prototype.canIntersects = function (ray) {
  21634. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  21635. };
  21636. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  21637. var intersectInfo = null;
  21638. // LineMesh first as it's also a Mesh...
  21639. if (this._mesh instanceof BABYLON.LinesMesh) {
  21640. var lineMesh = this._mesh;
  21641. // Line test
  21642. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  21643. var p0 = positions[indices[index]];
  21644. var p1 = positions[indices[index + 1]];
  21645. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  21646. if (length < 0) {
  21647. continue;
  21648. }
  21649. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  21650. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  21651. if (fastCheck) {
  21652. break;
  21653. }
  21654. }
  21655. }
  21656. }
  21657. else {
  21658. // Triangles test
  21659. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  21660. var p0 = positions[indices[index]];
  21661. var p1 = positions[indices[index + 1]];
  21662. var p2 = positions[indices[index + 2]];
  21663. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  21664. if (currentIntersectInfo) {
  21665. if (currentIntersectInfo.distance < 0) {
  21666. continue;
  21667. }
  21668. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21669. intersectInfo = currentIntersectInfo;
  21670. intersectInfo.faceId = index / 3;
  21671. if (fastCheck) {
  21672. break;
  21673. }
  21674. }
  21675. }
  21676. }
  21677. }
  21678. return intersectInfo;
  21679. };
  21680. // Clone
  21681. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  21682. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  21683. if (!this.IsGlobal) {
  21684. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  21685. }
  21686. return result;
  21687. };
  21688. // Dispose
  21689. SubMesh.prototype.dispose = function () {
  21690. if (this._linesIndexBuffer) {
  21691. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  21692. this._linesIndexBuffer = null;
  21693. }
  21694. // Remove from mesh
  21695. var index = this._mesh.subMeshes.indexOf(this);
  21696. this._mesh.subMeshes.splice(index, 1);
  21697. };
  21698. // Statics
  21699. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  21700. var minVertexIndex = Number.MAX_VALUE;
  21701. var maxVertexIndex = -Number.MAX_VALUE;
  21702. renderingMesh = renderingMesh || mesh;
  21703. var indices = renderingMesh.getIndices();
  21704. for (var index = startIndex; index < startIndex + indexCount; index++) {
  21705. var vertexIndex = indices[index];
  21706. if (vertexIndex < minVertexIndex)
  21707. minVertexIndex = vertexIndex;
  21708. if (vertexIndex > maxVertexIndex)
  21709. maxVertexIndex = vertexIndex;
  21710. }
  21711. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  21712. };
  21713. return SubMesh;
  21714. }());
  21715. BABYLON.SubMesh = SubMesh;
  21716. })(BABYLON || (BABYLON = {}));
  21717. var BABYLON;
  21718. (function (BABYLON) {
  21719. var MeshBuilder = (function () {
  21720. function MeshBuilder() {
  21721. }
  21722. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  21723. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  21724. return BABYLON.Mesh.DOUBLESIDE;
  21725. }
  21726. if (orientation === undefined || orientation === null) {
  21727. return BABYLON.Mesh.FRONTSIDE;
  21728. }
  21729. return orientation;
  21730. };
  21731. /**
  21732. * Creates a box mesh.
  21733. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  21734. * The parameter `size` sets the size (float) of each box side (default 1).
  21735. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  21736. * 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).
  21737. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21738. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21739. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21740. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21741. */
  21742. MeshBuilder.CreateBox = function (name, options, scene) {
  21743. var box = new BABYLON.Mesh(name, scene);
  21744. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21745. var vertexData = BABYLON.VertexData.CreateBox(options);
  21746. vertexData.applyToMesh(box, options.updatable);
  21747. return box;
  21748. };
  21749. /**
  21750. * Creates a sphere mesh.
  21751. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  21752. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21753. * 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`).
  21754. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21755. * 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
  21756. * 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).
  21757. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21758. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21759. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21760. */
  21761. MeshBuilder.CreateSphere = function (name, options, scene) {
  21762. var sphere = new BABYLON.Mesh(name, scene);
  21763. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21764. var vertexData = BABYLON.VertexData.CreateSphere(options);
  21765. vertexData.applyToMesh(sphere, options.updatable);
  21766. return sphere;
  21767. };
  21768. /**
  21769. * Creates a plane polygonal mesh. By default, this is a disc.
  21770. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  21771. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21772. * 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.
  21773. * 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
  21774. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21775. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21776. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21777. */
  21778. MeshBuilder.CreateDisc = function (name, options, scene) {
  21779. var disc = new BABYLON.Mesh(name, scene);
  21780. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21781. var vertexData = BABYLON.VertexData.CreateDisc(options);
  21782. vertexData.applyToMesh(disc, options.updatable);
  21783. return disc;
  21784. };
  21785. /**
  21786. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21787. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  21788. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21789. * 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`).
  21790. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21791. * 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.
  21792. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21793. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21794. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21795. */
  21796. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  21797. var sphere = new BABYLON.Mesh(name, scene);
  21798. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21799. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  21800. vertexData.applyToMesh(sphere, options.updatable);
  21801. return sphere;
  21802. };
  21803. ;
  21804. /**
  21805. * Creates a ribbon mesh.
  21806. * 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.
  21807. *
  21808. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21809. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21810. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21811. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21812. * 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.
  21813. * 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.
  21814. * 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
  21815. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21816. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21817. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  21818. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21819. */
  21820. MeshBuilder.CreateRibbon = function (name, options, scene) {
  21821. var pathArray = options.pathArray;
  21822. var closeArray = options.closeArray;
  21823. var closePath = options.closePath;
  21824. var offset = options.offset;
  21825. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21826. var instance = options.instance;
  21827. var updatable = options.updatable;
  21828. if (instance) {
  21829. // positionFunction : ribbon case
  21830. // only pathArray and sideOrientation parameters are taken into account for positions update
  21831. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  21832. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  21833. var positionFunction = function (positions) {
  21834. var minlg = pathArray[0].length;
  21835. var i = 0;
  21836. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  21837. for (var si = 1; si <= ns; si++) {
  21838. for (var p = 0; p < pathArray.length; p++) {
  21839. var path = pathArray[p];
  21840. var l = path.length;
  21841. minlg = (minlg < l) ? minlg : l;
  21842. var j = 0;
  21843. while (j < minlg) {
  21844. positions[i] = path[j].x;
  21845. positions[i + 1] = path[j].y;
  21846. positions[i + 2] = path[j].z;
  21847. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  21848. BABYLON.Tmp.Vector3[0].x = path[j].x;
  21849. }
  21850. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  21851. BABYLON.Tmp.Vector3[1].x = path[j].x;
  21852. }
  21853. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  21854. BABYLON.Tmp.Vector3[0].y = path[j].y;
  21855. }
  21856. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  21857. BABYLON.Tmp.Vector3[1].y = path[j].y;
  21858. }
  21859. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  21860. BABYLON.Tmp.Vector3[0].z = path[j].z;
  21861. }
  21862. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  21863. BABYLON.Tmp.Vector3[1].z = path[j].z;
  21864. }
  21865. j++;
  21866. i += 3;
  21867. }
  21868. if (instance._closePath) {
  21869. positions[i] = path[0].x;
  21870. positions[i + 1] = path[0].y;
  21871. positions[i + 2] = path[0].z;
  21872. i += 3;
  21873. }
  21874. }
  21875. }
  21876. };
  21877. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21878. positionFunction(positions);
  21879. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  21880. instance._boundingInfo.update(instance._worldMatrix);
  21881. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21882. if (!(instance.areNormalsFrozen)) {
  21883. var indices = instance.getIndices();
  21884. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21885. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21886. if (instance._closePath) {
  21887. var indexFirst = 0;
  21888. var indexLast = 0;
  21889. for (var p = 0; p < pathArray.length; p++) {
  21890. indexFirst = instance._idx[p] * 3;
  21891. if (p + 1 < pathArray.length) {
  21892. indexLast = (instance._idx[p + 1] - 1) * 3;
  21893. }
  21894. else {
  21895. indexLast = normals.length - 3;
  21896. }
  21897. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  21898. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  21899. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  21900. normals[indexLast] = normals[indexFirst];
  21901. normals[indexLast + 1] = normals[indexFirst + 1];
  21902. normals[indexLast + 2] = normals[indexFirst + 2];
  21903. }
  21904. }
  21905. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21906. }
  21907. return instance;
  21908. }
  21909. else {
  21910. var ribbon = new BABYLON.Mesh(name, scene);
  21911. ribbon.sideOrientation = sideOrientation;
  21912. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  21913. if (closePath) {
  21914. ribbon._idx = vertexData._idx;
  21915. }
  21916. ribbon._closePath = closePath;
  21917. ribbon._closeArray = closeArray;
  21918. vertexData.applyToMesh(ribbon, updatable);
  21919. return ribbon;
  21920. }
  21921. };
  21922. /**
  21923. * Creates a cylinder or a cone mesh.
  21924. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  21925. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21926. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21927. * 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.
  21928. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21929. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21930. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  21931. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  21932. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  21933. * 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).
  21934. * 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
  21935. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  21936. * 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
  21937. * 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.
  21938. * If `enclose` is false, a ring surface is one element.
  21939. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  21940. * 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
  21941. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21942. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21944. */
  21945. MeshBuilder.CreateCylinder = function (name, options, scene) {
  21946. var cylinder = new BABYLON.Mesh(name, scene);
  21947. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21948. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  21949. vertexData.applyToMesh(cylinder, options.updatable);
  21950. return cylinder;
  21951. };
  21952. /**
  21953. * Creates a torus mesh.
  21954. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  21955. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21956. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21957. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21958. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21959. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21960. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21961. */
  21962. MeshBuilder.CreateTorus = function (name, options, scene) {
  21963. var torus = new BABYLON.Mesh(name, scene);
  21964. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21965. var vertexData = BABYLON.VertexData.CreateTorus(options);
  21966. vertexData.applyToMesh(torus, options.updatable);
  21967. return torus;
  21968. };
  21969. /**
  21970. * Creates a torus knot mesh.
  21971. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  21972. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21973. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21974. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21975. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21976. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21977. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21978. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21979. */
  21980. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  21981. var torusKnot = new BABYLON.Mesh(name, scene);
  21982. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  21983. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  21984. vertexData.applyToMesh(torusKnot, options.updatable);
  21985. return torusKnot;
  21986. };
  21987. /**
  21988. * Creates a line system mesh.
  21989. * A line system is a pool of many lines gathered in a single mesh.
  21990. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  21991. * 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.
  21992. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  21993. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  21994. * 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
  21995. * 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
  21996. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  21997. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21998. */
  21999. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  22000. var instance = options.instance;
  22001. var lines = options.lines;
  22002. if (instance) {
  22003. var positionFunction = function (positions) {
  22004. var i = 0;
  22005. for (var l = 0; l < lines.length; l++) {
  22006. var points = lines[l];
  22007. for (var p = 0; p < points.length; p++) {
  22008. positions[i] = points[p].x;
  22009. positions[i + 1] = points[p].y;
  22010. positions[i + 2] = points[p].z;
  22011. i += 3;
  22012. }
  22013. }
  22014. };
  22015. instance.updateMeshPositions(positionFunction, false);
  22016. return instance;
  22017. }
  22018. // line system creation
  22019. var lineSystem = new BABYLON.LinesMesh(name, scene);
  22020. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  22021. vertexData.applyToMesh(lineSystem, options.updatable);
  22022. return lineSystem;
  22023. };
  22024. /**
  22025. * Creates a line mesh.
  22026. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  22027. * 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.
  22028. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22029. * The parameter `points` is an array successive Vector3.
  22030. * 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
  22031. * When updating an instance, remember that only point positions can change, not the number of points.
  22032. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22033. */
  22034. MeshBuilder.CreateLines = function (name, options, scene) {
  22035. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  22036. return lines;
  22037. };
  22038. /**
  22039. * Creates a dashed line mesh.
  22040. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  22041. * 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.
  22042. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22043. * The parameter `points` is an array successive Vector3.
  22044. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22045. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22046. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22047. * 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
  22048. * When updating an instance, remember that only point positions can change, not the number of points.
  22049. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22050. */
  22051. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  22052. var points = options.points;
  22053. var instance = options.instance;
  22054. var gapSize = options.gapSize;
  22055. var dashNb = options.dashNb;
  22056. var dashSize = options.dashSize;
  22057. if (instance) {
  22058. var positionFunction = function (positions) {
  22059. var curvect = BABYLON.Vector3.Zero();
  22060. var nbSeg = positions.length / 6;
  22061. var lg = 0;
  22062. var nb = 0;
  22063. var shft = 0;
  22064. var dashshft = 0;
  22065. var curshft = 0;
  22066. var p = 0;
  22067. var i = 0;
  22068. var j = 0;
  22069. for (i = 0; i < points.length - 1; i++) {
  22070. points[i + 1].subtractToRef(points[i], curvect);
  22071. lg += curvect.length();
  22072. }
  22073. shft = lg / nbSeg;
  22074. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  22075. for (i = 0; i < points.length - 1; i++) {
  22076. points[i + 1].subtractToRef(points[i], curvect);
  22077. nb = Math.floor(curvect.length() / shft);
  22078. curvect.normalize();
  22079. j = 0;
  22080. while (j < nb && p < positions.length) {
  22081. curshft = shft * j;
  22082. positions[p] = points[i].x + curshft * curvect.x;
  22083. positions[p + 1] = points[i].y + curshft * curvect.y;
  22084. positions[p + 2] = points[i].z + curshft * curvect.z;
  22085. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  22086. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  22087. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  22088. p += 6;
  22089. j++;
  22090. }
  22091. }
  22092. while (p < positions.length) {
  22093. positions[p] = points[i].x;
  22094. positions[p + 1] = points[i].y;
  22095. positions[p + 2] = points[i].z;
  22096. p += 3;
  22097. }
  22098. };
  22099. instance.updateMeshPositions(positionFunction, false);
  22100. return instance;
  22101. }
  22102. // dashed lines creation
  22103. var dashedLines = new BABYLON.LinesMesh(name, scene);
  22104. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  22105. vertexData.applyToMesh(dashedLines, options.updatable);
  22106. dashedLines.dashSize = dashSize;
  22107. dashedLines.gapSize = gapSize;
  22108. return dashedLines;
  22109. };
  22110. /**
  22111. * Creates an extruded shape mesh.
  22112. * 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.
  22113. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  22114. *
  22115. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22116. * 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
  22117. * extruded along the Z axis.
  22118. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22119. * 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.
  22120. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22121. * 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
  22122. * 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
  22123. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22124. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22125. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22126. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22127. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22128. */
  22129. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  22130. var path = options.path;
  22131. var shape = options.shape;
  22132. var scale = options.scale || 1;
  22133. var rotation = options.rotation || 0;
  22134. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22135. var updatable = options.updatable;
  22136. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22137. var instance = options.instance;
  22138. var invertUV = options.invertUV || false;
  22139. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  22140. };
  22141. /**
  22142. * Creates an custom extruded shape mesh.
  22143. * 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.
  22144. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  22145. *
  22146. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22147. * 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
  22148. * extruded along the Z axis.
  22149. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22150. * 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
  22151. * and the distance of this point from the begining of the path :
  22152. * ```javascript
  22153. * var rotationFunction = function(i, distance) {
  22154. * // do things
  22155. * return rotationValue; }
  22156. * ```
  22157. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22158. * 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
  22159. * and the distance of this point from the begining of the path :
  22160. * ```javascript
  22161. * var scaleFunction = function(i, distance) {
  22162. * // do things
  22163. * return scaleValue;}
  22164. * ```
  22165. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22166. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22167. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22168. * 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
  22169. * 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
  22170. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22171. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22172. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22173. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22174. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22175. */
  22176. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  22177. var path = options.path;
  22178. var shape = options.shape;
  22179. var scaleFunction = options.scaleFunction || (function () { return 1; });
  22180. var rotationFunction = options.rotationFunction || (function () { return 0; });
  22181. var ribbonCloseArray = options.ribbonCloseArray || false;
  22182. var ribbonClosePath = options.ribbonClosePath || false;
  22183. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22184. var updatable = options.updatable;
  22185. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22186. var instance = options.instance;
  22187. var invertUV = options.invertUV || false;
  22188. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  22189. };
  22190. /**
  22191. * Creates lathe mesh.
  22192. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22193. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  22194. *
  22195. * 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
  22196. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22197. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22198. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22199. * 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.
  22200. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  22201. * 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
  22202. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22203. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22204. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22205. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22206. */
  22207. MeshBuilder.CreateLathe = function (name, options, scene) {
  22208. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  22209. var closed = (options.closed === undefined) ? true : options.closed;
  22210. var shape = options.shape;
  22211. var radius = options.radius || 1;
  22212. var tessellation = options.tessellation || 64;
  22213. var updatable = options.updatable;
  22214. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22215. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22216. var pi2 = Math.PI * 2;
  22217. var paths = new Array();
  22218. var invertUV = options.invertUV || false;
  22219. var i = 0;
  22220. var p = 0;
  22221. var step = pi2 / tessellation * arc;
  22222. var rotated;
  22223. var path = new Array();
  22224. ;
  22225. for (i = 0; i <= tessellation; i++) {
  22226. var path = [];
  22227. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22228. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22229. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22230. }
  22231. for (p = 0; p < shape.length; p++) {
  22232. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22233. path.push(rotated);
  22234. }
  22235. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22236. 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));
  22237. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22238. }
  22239. paths.push(path);
  22240. }
  22241. // lathe ribbon
  22242. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22243. return lathe;
  22244. };
  22245. /**
  22246. * Creates a plane mesh.
  22247. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22248. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22249. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22250. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22251. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22252. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22254. */
  22255. MeshBuilder.CreatePlane = function (name, options, scene) {
  22256. var plane = new BABYLON.Mesh(name, scene);
  22257. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22258. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22259. vertexData.applyToMesh(plane, options.updatable);
  22260. if (options.sourcePlane) {
  22261. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22262. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22263. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22264. plane.rotate(vectorProduct, product);
  22265. }
  22266. return plane;
  22267. };
  22268. /**
  22269. * Creates a ground mesh.
  22270. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22271. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22272. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22273. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22274. */
  22275. MeshBuilder.CreateGround = function (name, options, scene) {
  22276. var ground = new BABYLON.GroundMesh(name, scene);
  22277. ground._setReady(false);
  22278. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22279. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22280. ground._width = options.width || 1;
  22281. ground._height = options.height || 1;
  22282. ground._maxX = ground._width / 2;
  22283. ground._maxZ = ground._height / 2;
  22284. ground._minX = -ground._maxX;
  22285. ground._minZ = -ground._maxZ;
  22286. var vertexData = BABYLON.VertexData.CreateGround(options);
  22287. vertexData.applyToMesh(ground, options.updatable);
  22288. ground._setReady(true);
  22289. return ground;
  22290. };
  22291. /**
  22292. * Creates a tiled ground mesh.
  22293. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22294. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22295. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22296. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22297. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22298. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22299. * numbers of subdivisions on the ground width and height of each tile.
  22300. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22301. */
  22302. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22303. var tiledGround = new BABYLON.Mesh(name, scene);
  22304. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22305. vertexData.applyToMesh(tiledGround, options.updatable);
  22306. return tiledGround;
  22307. };
  22308. /**
  22309. * Creates a ground mesh from a height map.
  22310. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22311. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22312. * The parameter `url` sets the URL of the height map image resource.
  22313. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22314. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22315. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22316. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22317. * 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).
  22318. * This function is passed the newly built mesh :
  22319. * ```javascript
  22320. * function(mesh) { // do things
  22321. * return; }
  22322. * ```
  22323. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22324. */
  22325. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22326. var width = options.width || 10.0;
  22327. var height = options.height || 10.0;
  22328. var subdivisions = options.subdivisions || 1 | 0;
  22329. var minHeight = options.minHeight || 0.0;
  22330. var maxHeight = options.maxHeight || 10.0;
  22331. var updatable = options.updatable;
  22332. var onReady = options.onReady;
  22333. var ground = new BABYLON.GroundMesh(name, scene);
  22334. ground._subdivisionsX = subdivisions;
  22335. ground._subdivisionsY = subdivisions;
  22336. ground._width = width;
  22337. ground._height = height;
  22338. ground._maxX = ground._width / 2.0;
  22339. ground._maxZ = ground._height / 2.0;
  22340. ground._minX = -ground._maxX;
  22341. ground._minZ = -ground._maxZ;
  22342. ground._setReady(false);
  22343. var onload = function (img) {
  22344. // Getting height map data
  22345. var canvas = document.createElement("canvas");
  22346. var context = canvas.getContext("2d");
  22347. var bufferWidth = img.width;
  22348. var bufferHeight = img.height;
  22349. canvas.width = bufferWidth;
  22350. canvas.height = bufferHeight;
  22351. context.drawImage(img, 0, 0);
  22352. // Create VertexData from map data
  22353. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22354. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22355. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22356. width: width, height: height,
  22357. subdivisions: subdivisions,
  22358. minHeight: minHeight, maxHeight: maxHeight,
  22359. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22360. });
  22361. vertexData.applyToMesh(ground, updatable);
  22362. ground._setReady(true);
  22363. //execute ready callback, if set
  22364. if (onReady) {
  22365. onReady(ground);
  22366. }
  22367. };
  22368. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22369. return ground;
  22370. };
  22371. /**
  22372. * Creates a tube mesh.
  22373. * 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.
  22374. *
  22375. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22376. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22377. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22378. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22379. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22380. * 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.
  22381. * It must return a radius value (positive float) :
  22382. * ```javascript
  22383. * var radiusFunction = function(i, distance) {
  22384. * // do things
  22385. * return radius; }
  22386. * ```
  22387. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22388. * 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
  22389. * 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
  22390. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22391. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22392. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22393. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22394. */
  22395. MeshBuilder.CreateTube = function (name, options, scene) {
  22396. var path = options.path;
  22397. var radius = options.radius || 1.0;
  22398. var tessellation = options.tessellation || 64 | 0;
  22399. var radiusFunction = options.radiusFunction;
  22400. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22401. var invertUV = options.invertUV || false;
  22402. var updatable = options.updatable;
  22403. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22404. var instance = options.instance;
  22405. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22406. // tube geometry
  22407. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22408. var tangents = path3D.getTangents();
  22409. var normals = path3D.getNormals();
  22410. var distances = path3D.getDistances();
  22411. var pi2 = Math.PI * 2;
  22412. var step = pi2 / tessellation * arc;
  22413. var returnRadius = function () { return radius; };
  22414. var radiusFunctionFinal = radiusFunction || returnRadius;
  22415. var circlePath;
  22416. var rad;
  22417. var normal;
  22418. var rotated;
  22419. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22420. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22421. for (var i = 0; i < path.length; i++) {
  22422. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22423. circlePath = Array(); // current circle array
  22424. normal = normals[i]; // current normal
  22425. for (var t = 0; t < tessellation; t++) {
  22426. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22427. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22428. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22429. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22430. circlePath[t] = rotated;
  22431. }
  22432. circlePaths[index] = circlePath;
  22433. index++;
  22434. }
  22435. // cap
  22436. var capPath = function (nbPoints, pathIndex) {
  22437. var pointCap = Array();
  22438. for (var i = 0; i < nbPoints; i++) {
  22439. pointCap.push(path[pathIndex]);
  22440. }
  22441. return pointCap;
  22442. };
  22443. switch (cap) {
  22444. case BABYLON.Mesh.NO_CAP:
  22445. break;
  22446. case BABYLON.Mesh.CAP_START:
  22447. circlePaths[0] = capPath(tessellation, 0);
  22448. circlePaths[1] = circlePaths[2].slice(0);
  22449. break;
  22450. case BABYLON.Mesh.CAP_END:
  22451. circlePaths[index] = circlePaths[index - 1].slice(0);
  22452. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22453. break;
  22454. case BABYLON.Mesh.CAP_ALL:
  22455. circlePaths[0] = capPath(tessellation, 0);
  22456. circlePaths[1] = circlePaths[2].slice(0);
  22457. circlePaths[index] = circlePaths[index - 1].slice(0);
  22458. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22459. break;
  22460. default:
  22461. break;
  22462. }
  22463. return circlePaths;
  22464. };
  22465. var path3D;
  22466. var pathArray;
  22467. if (instance) {
  22468. var arc = options.arc || instance.arc;
  22469. path3D = (instance.path3D).update(path);
  22470. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  22471. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  22472. instance.path3D = path3D;
  22473. instance.pathArray = pathArray;
  22474. instance.arc = arc;
  22475. return instance;
  22476. }
  22477. // tube creation
  22478. path3D = new BABYLON.Path3D(path);
  22479. var newPathArray = new Array();
  22480. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22481. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  22482. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  22483. tube.pathArray = pathArray;
  22484. tube.path3D = path3D;
  22485. tube.tessellation = tessellation;
  22486. tube.cap = cap;
  22487. tube.arc = options.arc;
  22488. return tube;
  22489. };
  22490. /**
  22491. * Creates a polyhedron mesh.
  22492. *
  22493. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  22494. * 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
  22495. * to choose the wanted type.
  22496. * The parameter `size` (positive float, default 1) sets the polygon size.
  22497. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22498. * 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`.
  22499. * 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
  22500. * 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)`).
  22501. * 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
  22502. * 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.
  22503. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22504. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22505. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22506. */
  22507. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  22508. var polyhedron = new BABYLON.Mesh(name, scene);
  22509. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22510. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  22511. vertexData.applyToMesh(polyhedron, options.updatable);
  22512. return polyhedron;
  22513. };
  22514. /**
  22515. * Creates a decal mesh.
  22516. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  22517. * 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.
  22518. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22519. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22520. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22521. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22522. */
  22523. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  22524. var indices = sourceMesh.getIndices();
  22525. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22526. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22527. var position = options.position || BABYLON.Vector3.Zero();
  22528. var normal = options.normal || BABYLON.Vector3.Up();
  22529. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  22530. var angle = options.angle || 0;
  22531. // Getting correct rotation
  22532. if (!normal) {
  22533. var target = new BABYLON.Vector3(0, 0, 1);
  22534. var camera = sourceMesh.getScene().activeCamera;
  22535. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  22536. normal = camera.globalPosition.subtract(cameraWorldTarget);
  22537. }
  22538. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  22539. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  22540. var pitch = Math.atan2(normal.y, len);
  22541. // Matrix
  22542. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  22543. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  22544. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  22545. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  22546. var vertexData = new BABYLON.VertexData();
  22547. vertexData.indices = [];
  22548. vertexData.positions = [];
  22549. vertexData.normals = [];
  22550. vertexData.uvs = [];
  22551. var currentVertexDataIndex = 0;
  22552. var extractDecalVector3 = function (indexId) {
  22553. var vertexId = indices[indexId];
  22554. var result = new BABYLON.PositionNormalVertex();
  22555. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  22556. // Send vector to decal local world
  22557. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  22558. // Get normal
  22559. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  22560. return result;
  22561. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  22562. var clip = function (vertices, axis) {
  22563. if (vertices.length === 0) {
  22564. return vertices;
  22565. }
  22566. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  22567. var clipVertices = function (v0, v1) {
  22568. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  22569. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  22570. };
  22571. var result = new Array();
  22572. for (var index = 0; index < vertices.length; index += 3) {
  22573. var v1Out;
  22574. var v2Out;
  22575. var v3Out;
  22576. var total = 0;
  22577. var nV1, nV2, nV3, nV4;
  22578. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  22579. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  22580. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  22581. v1Out = d1 > 0;
  22582. v2Out = d2 > 0;
  22583. v3Out = d3 > 0;
  22584. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  22585. switch (total) {
  22586. case 0:
  22587. result.push(vertices[index]);
  22588. result.push(vertices[index + 1]);
  22589. result.push(vertices[index + 2]);
  22590. break;
  22591. case 1:
  22592. if (v1Out) {
  22593. nV1 = vertices[index + 1];
  22594. nV2 = vertices[index + 2];
  22595. nV3 = clipVertices(vertices[index], nV1);
  22596. nV4 = clipVertices(vertices[index], nV2);
  22597. }
  22598. if (v2Out) {
  22599. nV1 = vertices[index];
  22600. nV2 = vertices[index + 2];
  22601. nV3 = clipVertices(vertices[index + 1], nV1);
  22602. nV4 = clipVertices(vertices[index + 1], nV2);
  22603. result.push(nV3);
  22604. result.push(nV2.clone());
  22605. result.push(nV1.clone());
  22606. result.push(nV2.clone());
  22607. result.push(nV3.clone());
  22608. result.push(nV4);
  22609. break;
  22610. }
  22611. if (v3Out) {
  22612. nV1 = vertices[index];
  22613. nV2 = vertices[index + 1];
  22614. nV3 = clipVertices(vertices[index + 2], nV1);
  22615. nV4 = clipVertices(vertices[index + 2], nV2);
  22616. }
  22617. result.push(nV1.clone());
  22618. result.push(nV2.clone());
  22619. result.push(nV3);
  22620. result.push(nV4);
  22621. result.push(nV3.clone());
  22622. result.push(nV2.clone());
  22623. break;
  22624. case 2:
  22625. if (!v1Out) {
  22626. nV1 = vertices[index].clone();
  22627. nV2 = clipVertices(nV1, vertices[index + 1]);
  22628. nV3 = clipVertices(nV1, vertices[index + 2]);
  22629. result.push(nV1);
  22630. result.push(nV2);
  22631. result.push(nV3);
  22632. }
  22633. if (!v2Out) {
  22634. nV1 = vertices[index + 1].clone();
  22635. nV2 = clipVertices(nV1, vertices[index + 2]);
  22636. nV3 = clipVertices(nV1, vertices[index]);
  22637. result.push(nV1);
  22638. result.push(nV2);
  22639. result.push(nV3);
  22640. }
  22641. if (!v3Out) {
  22642. nV1 = vertices[index + 2].clone();
  22643. nV2 = clipVertices(nV1, vertices[index]);
  22644. nV3 = clipVertices(nV1, vertices[index + 1]);
  22645. result.push(nV1);
  22646. result.push(nV2);
  22647. result.push(nV3);
  22648. }
  22649. break;
  22650. case 3:
  22651. break;
  22652. }
  22653. }
  22654. return result;
  22655. };
  22656. for (var index = 0; index < indices.length; index += 3) {
  22657. var faceVertices = new Array();
  22658. faceVertices.push(extractDecalVector3(index));
  22659. faceVertices.push(extractDecalVector3(index + 1));
  22660. faceVertices.push(extractDecalVector3(index + 2));
  22661. // Clip
  22662. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  22663. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  22664. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  22665. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  22666. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  22667. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  22668. if (faceVertices.length === 0) {
  22669. continue;
  22670. }
  22671. // Add UVs and get back to world
  22672. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  22673. var vertex = faceVertices[vIndex];
  22674. //TODO check for Int32Array
  22675. vertexData.indices.push(currentVertexDataIndex);
  22676. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  22677. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  22678. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  22679. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  22680. currentVertexDataIndex++;
  22681. }
  22682. }
  22683. // Return mesh
  22684. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  22685. vertexData.applyToMesh(decal);
  22686. decal.position = position.clone();
  22687. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  22688. return decal;
  22689. };
  22690. // Privates
  22691. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  22692. // extrusion geometry
  22693. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  22694. var tangents = path3D.getTangents();
  22695. var normals = path3D.getNormals();
  22696. var binormals = path3D.getBinormals();
  22697. var distances = path3D.getDistances();
  22698. var angle = 0;
  22699. var returnScale = function () { return scale; };
  22700. var returnRotation = function () { return rotation; };
  22701. var rotate = custom ? rotateFunction : returnRotation;
  22702. var scl = custom ? scaleFunction : returnScale;
  22703. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22704. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22705. for (var i = 0; i < curve.length; i++) {
  22706. var shapePath = new Array();
  22707. var angleStep = rotate(i, distances[i]);
  22708. var scaleRatio = scl(i, distances[i]);
  22709. for (var p = 0; p < shape.length; p++) {
  22710. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  22711. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  22712. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  22713. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  22714. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  22715. shapePath[p] = rotated;
  22716. }
  22717. shapePaths[index] = shapePath;
  22718. angle += angleStep;
  22719. index++;
  22720. }
  22721. // cap
  22722. var capPath = function (shapePath) {
  22723. var pointCap = Array();
  22724. var barycenter = BABYLON.Vector3.Zero();
  22725. var i;
  22726. for (i = 0; i < shapePath.length; i++) {
  22727. barycenter.addInPlace(shapePath[i]);
  22728. }
  22729. barycenter.scaleInPlace(1 / shapePath.length);
  22730. for (i = 0; i < shapePath.length; i++) {
  22731. pointCap.push(barycenter);
  22732. }
  22733. return pointCap;
  22734. };
  22735. switch (cap) {
  22736. case BABYLON.Mesh.NO_CAP:
  22737. break;
  22738. case BABYLON.Mesh.CAP_START:
  22739. shapePaths[0] = capPath(shapePaths[2]);
  22740. shapePaths[1] = shapePaths[2].slice(0);
  22741. break;
  22742. case BABYLON.Mesh.CAP_END:
  22743. shapePaths[index] = shapePaths[index - 1];
  22744. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22745. break;
  22746. case BABYLON.Mesh.CAP_ALL:
  22747. shapePaths[0] = capPath(shapePaths[2]);
  22748. shapePaths[1] = shapePaths[2].slice(0);
  22749. shapePaths[index] = shapePaths[index - 1];
  22750. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  22751. break;
  22752. default:
  22753. break;
  22754. }
  22755. return shapePaths;
  22756. };
  22757. var path3D;
  22758. var pathArray;
  22759. if (instance) {
  22760. path3D = (instance.path3D).update(curve);
  22761. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  22762. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  22763. return instance;
  22764. }
  22765. // extruded shape creation
  22766. path3D = new BABYLON.Path3D(curve);
  22767. var newShapePaths = new Array();
  22768. cap = (cap < 0 || cap > 3) ? 0 : cap;
  22769. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  22770. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  22771. extrudedGeneric.pathArray = pathArray;
  22772. extrudedGeneric.path3D = path3D;
  22773. extrudedGeneric.cap = cap;
  22774. return extrudedGeneric;
  22775. };
  22776. return MeshBuilder;
  22777. }());
  22778. BABYLON.MeshBuilder = MeshBuilder;
  22779. })(BABYLON || (BABYLON = {}));
  22780. var BABYLON;
  22781. (function (BABYLON) {
  22782. var BaseTexture = (function () {
  22783. function BaseTexture(scene) {
  22784. this.hasAlpha = false;
  22785. this.getAlphaFromRGB = false;
  22786. this.level = 1;
  22787. this.coordinatesIndex = 0;
  22788. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  22789. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  22790. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  22791. this.anisotropicFilteringLevel = 4;
  22792. this.isCube = false;
  22793. this.isRenderTarget = false;
  22794. this.animations = new Array();
  22795. /**
  22796. * An event triggered when the texture is disposed.
  22797. * @type {BABYLON.Observable}
  22798. */
  22799. this.onDisposeObservable = new BABYLON.Observable();
  22800. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  22801. this._scene = scene;
  22802. this._scene.textures.push(this);
  22803. this._uid = null;
  22804. }
  22805. Object.defineProperty(BaseTexture.prototype, "uid", {
  22806. get: function () {
  22807. if (!this._uid) {
  22808. this._uid = BABYLON.Tools.RandomId();
  22809. }
  22810. return this._uid;
  22811. },
  22812. enumerable: true,
  22813. configurable: true
  22814. });
  22815. BaseTexture.prototype.toString = function () {
  22816. return this.name;
  22817. };
  22818. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  22819. set: function (callback) {
  22820. if (this._onDisposeObserver) {
  22821. this.onDisposeObservable.remove(this._onDisposeObserver);
  22822. }
  22823. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  22824. },
  22825. enumerable: true,
  22826. configurable: true
  22827. });
  22828. BaseTexture.prototype.getScene = function () {
  22829. return this._scene;
  22830. };
  22831. BaseTexture.prototype.getTextureMatrix = function () {
  22832. return null;
  22833. };
  22834. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  22835. return null;
  22836. };
  22837. BaseTexture.prototype.getInternalTexture = function () {
  22838. return this._texture;
  22839. };
  22840. BaseTexture.prototype.isReady = function () {
  22841. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  22842. return true;
  22843. }
  22844. if (this._texture) {
  22845. return this._texture.isReady;
  22846. }
  22847. return false;
  22848. };
  22849. BaseTexture.prototype.getSize = function () {
  22850. if (this._texture._width) {
  22851. return new BABYLON.Size(this._texture._width, this._texture._height);
  22852. }
  22853. if (this._texture._size) {
  22854. return new BABYLON.Size(this._texture._size, this._texture._size);
  22855. }
  22856. return BABYLON.Size.Zero();
  22857. };
  22858. BaseTexture.prototype.getBaseSize = function () {
  22859. if (!this.isReady() || !this._texture)
  22860. return BABYLON.Size.Zero();
  22861. if (this._texture._size) {
  22862. return new BABYLON.Size(this._texture._size, this._texture._size);
  22863. }
  22864. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  22865. };
  22866. BaseTexture.prototype.scale = function (ratio) {
  22867. };
  22868. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  22869. get: function () {
  22870. return false;
  22871. },
  22872. enumerable: true,
  22873. configurable: true
  22874. });
  22875. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  22876. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22877. for (var index = 0; index < texturesCache.length; index++) {
  22878. var texturesCacheEntry = texturesCache[index];
  22879. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22880. texturesCache.splice(index, 1);
  22881. return;
  22882. }
  22883. }
  22884. };
  22885. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  22886. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  22887. for (var index = 0; index < texturesCache.length; index++) {
  22888. var texturesCacheEntry = texturesCache[index];
  22889. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  22890. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  22891. texturesCacheEntry.references++;
  22892. return texturesCacheEntry;
  22893. }
  22894. }
  22895. }
  22896. return null;
  22897. };
  22898. BaseTexture.prototype.delayLoad = function () {
  22899. };
  22900. BaseTexture.prototype.clone = function () {
  22901. return null;
  22902. };
  22903. BaseTexture.prototype.releaseInternalTexture = function () {
  22904. if (this._texture) {
  22905. this._scene.getEngine().releaseInternalTexture(this._texture);
  22906. delete this._texture;
  22907. }
  22908. };
  22909. BaseTexture.prototype.dispose = function () {
  22910. // Animations
  22911. this.getScene().stopAnimation(this);
  22912. // Remove from scene
  22913. var index = this._scene.textures.indexOf(this);
  22914. if (index >= 0) {
  22915. this._scene.textures.splice(index, 1);
  22916. }
  22917. if (this._texture === undefined) {
  22918. return;
  22919. }
  22920. // Release
  22921. this.releaseInternalTexture();
  22922. // Callback
  22923. this.onDisposeObservable.notifyObservers(this);
  22924. this.onDisposeObservable.clear();
  22925. };
  22926. BaseTexture.prototype.serialize = function () {
  22927. if (!this.name) {
  22928. return null;
  22929. }
  22930. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22931. // Animations
  22932. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22933. return serializationObject;
  22934. };
  22935. __decorate([
  22936. BABYLON.serialize()
  22937. ], BaseTexture.prototype, "name", void 0);
  22938. __decorate([
  22939. BABYLON.serialize()
  22940. ], BaseTexture.prototype, "hasAlpha", void 0);
  22941. __decorate([
  22942. BABYLON.serialize()
  22943. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  22944. __decorate([
  22945. BABYLON.serialize()
  22946. ], BaseTexture.prototype, "level", void 0);
  22947. __decorate([
  22948. BABYLON.serialize()
  22949. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  22950. __decorate([
  22951. BABYLON.serialize()
  22952. ], BaseTexture.prototype, "coordinatesMode", void 0);
  22953. __decorate([
  22954. BABYLON.serialize()
  22955. ], BaseTexture.prototype, "wrapU", void 0);
  22956. __decorate([
  22957. BABYLON.serialize()
  22958. ], BaseTexture.prototype, "wrapV", void 0);
  22959. __decorate([
  22960. BABYLON.serialize()
  22961. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  22962. __decorate([
  22963. BABYLON.serialize()
  22964. ], BaseTexture.prototype, "isCube", void 0);
  22965. __decorate([
  22966. BABYLON.serialize()
  22967. ], BaseTexture.prototype, "isRenderTarget", void 0);
  22968. return BaseTexture;
  22969. }());
  22970. BABYLON.BaseTexture = BaseTexture;
  22971. })(BABYLON || (BABYLON = {}));
  22972. var BABYLON;
  22973. (function (BABYLON) {
  22974. var Texture = (function (_super) {
  22975. __extends(Texture, _super);
  22976. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  22977. var _this = this;
  22978. if (noMipmap === void 0) { noMipmap = false; }
  22979. if (invertY === void 0) { invertY = true; }
  22980. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  22981. if (onLoad === void 0) { onLoad = null; }
  22982. if (onError === void 0) { onError = null; }
  22983. if (buffer === void 0) { buffer = null; }
  22984. if (deleteBuffer === void 0) { deleteBuffer = false; }
  22985. _super.call(this, scene);
  22986. this.uOffset = 0;
  22987. this.vOffset = 0;
  22988. this.uScale = 1.0;
  22989. this.vScale = 1.0;
  22990. this.uAng = 0;
  22991. this.vAng = 0;
  22992. this.wAng = 0;
  22993. this.name = url;
  22994. this.url = url;
  22995. this._noMipmap = noMipmap;
  22996. this._invertY = invertY;
  22997. this._samplingMode = samplingMode;
  22998. this._buffer = buffer;
  22999. this._deleteBuffer = deleteBuffer;
  23000. if (!url) {
  23001. return;
  23002. }
  23003. this._texture = this._getFromCache(url, noMipmap, samplingMode);
  23004. var load = function () {
  23005. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  23006. _this.onLoadObservable.notifyObservers(true);
  23007. }
  23008. if (onLoad) {
  23009. onLoad();
  23010. }
  23011. };
  23012. if (!this._texture) {
  23013. if (!scene.useDelayedTextureLoading) {
  23014. this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, this._samplingMode, load, onError, this._buffer);
  23015. if (deleteBuffer) {
  23016. delete this._buffer;
  23017. }
  23018. }
  23019. else {
  23020. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23021. this._delayedOnLoad = load;
  23022. this._delayedOnError = onError;
  23023. }
  23024. }
  23025. else {
  23026. if (this._texture.isReady) {
  23027. BABYLON.Tools.SetImmediate(function () { return load(); });
  23028. }
  23029. else {
  23030. this._texture.onLoadedCallbacks.push(load);
  23031. }
  23032. }
  23033. }
  23034. Object.defineProperty(Texture.prototype, "noMipmap", {
  23035. get: function () {
  23036. return this._noMipmap;
  23037. },
  23038. enumerable: true,
  23039. configurable: true
  23040. });
  23041. Texture.prototype.delayLoad = function () {
  23042. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23043. return;
  23044. }
  23045. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23046. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23047. if (!this._texture) {
  23048. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  23049. if (this._deleteBuffer) {
  23050. delete this._buffer;
  23051. }
  23052. }
  23053. };
  23054. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23055. if (!this._texture) {
  23056. return;
  23057. }
  23058. this._samplingMode = samplingMode;
  23059. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23060. };
  23061. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23062. x *= this.uScale;
  23063. y *= this.vScale;
  23064. x -= 0.5 * this.uScale;
  23065. y -= 0.5 * this.vScale;
  23066. z -= 0.5;
  23067. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23068. t.x += 0.5 * this.uScale + this.uOffset;
  23069. t.y += 0.5 * this.vScale + this.vOffset;
  23070. t.z += 0.5;
  23071. };
  23072. Texture.prototype.getTextureMatrix = function () {
  23073. if (this.uOffset === this._cachedUOffset &&
  23074. this.vOffset === this._cachedVOffset &&
  23075. this.uScale === this._cachedUScale &&
  23076. this.vScale === this._cachedVScale &&
  23077. this.uAng === this._cachedUAng &&
  23078. this.vAng === this._cachedVAng &&
  23079. this.wAng === this._cachedWAng) {
  23080. return this._cachedTextureMatrix;
  23081. }
  23082. this._cachedUOffset = this.uOffset;
  23083. this._cachedVOffset = this.vOffset;
  23084. this._cachedUScale = this.uScale;
  23085. this._cachedVScale = this.vScale;
  23086. this._cachedUAng = this.uAng;
  23087. this._cachedVAng = this.vAng;
  23088. this._cachedWAng = this.wAng;
  23089. if (!this._cachedTextureMatrix) {
  23090. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23091. this._rowGenerationMatrix = new BABYLON.Matrix();
  23092. this._t0 = BABYLON.Vector3.Zero();
  23093. this._t1 = BABYLON.Vector3.Zero();
  23094. this._t2 = BABYLON.Vector3.Zero();
  23095. }
  23096. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23097. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23098. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23099. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23100. this._t1.subtractInPlace(this._t0);
  23101. this._t2.subtractInPlace(this._t0);
  23102. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23103. this._cachedTextureMatrix.m[0] = this._t1.x;
  23104. this._cachedTextureMatrix.m[1] = this._t1.y;
  23105. this._cachedTextureMatrix.m[2] = this._t1.z;
  23106. this._cachedTextureMatrix.m[4] = this._t2.x;
  23107. this._cachedTextureMatrix.m[5] = this._t2.y;
  23108. this._cachedTextureMatrix.m[6] = this._t2.z;
  23109. this._cachedTextureMatrix.m[8] = this._t0.x;
  23110. this._cachedTextureMatrix.m[9] = this._t0.y;
  23111. this._cachedTextureMatrix.m[10] = this._t0.z;
  23112. return this._cachedTextureMatrix;
  23113. };
  23114. Texture.prototype.getReflectionTextureMatrix = function () {
  23115. if (this.uOffset === this._cachedUOffset &&
  23116. this.vOffset === this._cachedVOffset &&
  23117. this.uScale === this._cachedUScale &&
  23118. this.vScale === this._cachedVScale &&
  23119. this.coordinatesMode === this._cachedCoordinatesMode) {
  23120. return this._cachedTextureMatrix;
  23121. }
  23122. if (!this._cachedTextureMatrix) {
  23123. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23124. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23125. }
  23126. this._cachedCoordinatesMode = this.coordinatesMode;
  23127. switch (this.coordinatesMode) {
  23128. case Texture.PLANAR_MODE:
  23129. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23130. this._cachedTextureMatrix[0] = this.uScale;
  23131. this._cachedTextureMatrix[5] = this.vScale;
  23132. this._cachedTextureMatrix[12] = this.uOffset;
  23133. this._cachedTextureMatrix[13] = this.vOffset;
  23134. break;
  23135. case Texture.PROJECTION_MODE:
  23136. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23137. this._projectionModeMatrix.m[0] = 0.5;
  23138. this._projectionModeMatrix.m[5] = -0.5;
  23139. this._projectionModeMatrix.m[10] = 0.0;
  23140. this._projectionModeMatrix.m[12] = 0.5;
  23141. this._projectionModeMatrix.m[13] = 0.5;
  23142. this._projectionModeMatrix.m[14] = 1.0;
  23143. this._projectionModeMatrix.m[15] = 1.0;
  23144. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23145. break;
  23146. default:
  23147. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23148. break;
  23149. }
  23150. return this._cachedTextureMatrix;
  23151. };
  23152. Texture.prototype.clone = function () {
  23153. var _this = this;
  23154. return BABYLON.SerializationHelper.Clone(function () {
  23155. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23156. }, this);
  23157. };
  23158. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23159. get: function () {
  23160. if (!this._onLoadObservarble) {
  23161. this._onLoadObservarble = new BABYLON.Observable();
  23162. }
  23163. return this._onLoadObservarble;
  23164. },
  23165. enumerable: true,
  23166. configurable: true
  23167. });
  23168. // Statics
  23169. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  23170. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23171. if (onLoad === void 0) { onLoad = null; }
  23172. if (onError === void 0) { onError = null; }
  23173. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  23174. };
  23175. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23176. if (parsedTexture.customType) {
  23177. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23178. return customTexture.Parse(parsedTexture, scene, rootUrl);
  23179. }
  23180. if (parsedTexture.isCube) {
  23181. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23182. }
  23183. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23184. return null;
  23185. }
  23186. var texture = BABYLON.SerializationHelper.Parse(function () {
  23187. if (parsedTexture.mirrorPlane) {
  23188. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23189. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23190. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23191. return mirrorTexture;
  23192. }
  23193. else if (parsedTexture.isRenderTarget) {
  23194. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23195. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23196. return renderTargetTexture;
  23197. }
  23198. else {
  23199. var texture;
  23200. if (parsedTexture.base64String) {
  23201. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  23202. }
  23203. else {
  23204. texture = new Texture(rootUrl + parsedTexture.name, scene);
  23205. }
  23206. return texture;
  23207. }
  23208. }, parsedTexture, scene);
  23209. // Animations
  23210. if (parsedTexture.animations) {
  23211. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23212. var parsedAnimation = parsedTexture.animations[animationIndex];
  23213. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23214. }
  23215. }
  23216. return texture;
  23217. };
  23218. // Constants
  23219. Texture.NEAREST_SAMPLINGMODE = 1;
  23220. Texture.BILINEAR_SAMPLINGMODE = 2;
  23221. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23222. Texture.EXPLICIT_MODE = 0;
  23223. Texture.SPHERICAL_MODE = 1;
  23224. Texture.PLANAR_MODE = 2;
  23225. Texture.CUBIC_MODE = 3;
  23226. Texture.PROJECTION_MODE = 4;
  23227. Texture.SKYBOX_MODE = 5;
  23228. Texture.INVCUBIC_MODE = 6;
  23229. Texture.EQUIRECTANGULAR_MODE = 7;
  23230. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23231. Texture.CLAMP_ADDRESSMODE = 0;
  23232. Texture.WRAP_ADDRESSMODE = 1;
  23233. Texture.MIRROR_ADDRESSMODE = 2;
  23234. __decorate([
  23235. BABYLON.serialize()
  23236. ], Texture.prototype, "url", void 0);
  23237. __decorate([
  23238. BABYLON.serialize()
  23239. ], Texture.prototype, "uOffset", void 0);
  23240. __decorate([
  23241. BABYLON.serialize()
  23242. ], Texture.prototype, "vOffset", void 0);
  23243. __decorate([
  23244. BABYLON.serialize()
  23245. ], Texture.prototype, "uScale", void 0);
  23246. __decorate([
  23247. BABYLON.serialize()
  23248. ], Texture.prototype, "vScale", void 0);
  23249. __decorate([
  23250. BABYLON.serialize()
  23251. ], Texture.prototype, "uAng", void 0);
  23252. __decorate([
  23253. BABYLON.serialize()
  23254. ], Texture.prototype, "vAng", void 0);
  23255. __decorate([
  23256. BABYLON.serialize()
  23257. ], Texture.prototype, "wAng", void 0);
  23258. return Texture;
  23259. }(BABYLON.BaseTexture));
  23260. BABYLON.Texture = Texture;
  23261. })(BABYLON || (BABYLON = {}));
  23262. var BABYLON;
  23263. (function (BABYLON) {
  23264. var CubeTexture = (function (_super) {
  23265. __extends(CubeTexture, _super);
  23266. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23267. if (onLoad === void 0) { onLoad = null; }
  23268. if (onError === void 0) { onError = null; }
  23269. _super.call(this, scene);
  23270. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23271. this.name = rootUrl;
  23272. this.url = rootUrl;
  23273. this._noMipmap = noMipmap;
  23274. this.hasAlpha = false;
  23275. if (!rootUrl && !files) {
  23276. return;
  23277. }
  23278. this._texture = this._getFromCache(rootUrl, noMipmap);
  23279. if (!files) {
  23280. if (!extensions) {
  23281. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23282. }
  23283. files = [];
  23284. for (var index = 0; index < extensions.length; index++) {
  23285. files.push(rootUrl + extensions[index]);
  23286. }
  23287. this._extensions = extensions;
  23288. }
  23289. this._files = files;
  23290. if (!this._texture) {
  23291. if (!scene.useDelayedTextureLoading) {
  23292. this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23293. }
  23294. else {
  23295. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23296. }
  23297. }
  23298. else {
  23299. if (this._texture.isReady) {
  23300. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23301. }
  23302. else if (onLoad) {
  23303. this._texture.onLoadedCallbacks.push(onLoad);
  23304. }
  23305. }
  23306. this.isCube = true;
  23307. this._textureMatrix = BABYLON.Matrix.Identity();
  23308. }
  23309. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23310. return new CubeTexture("", scene, null, noMipmap, files);
  23311. };
  23312. // Methods
  23313. CubeTexture.prototype.delayLoad = function () {
  23314. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23315. return;
  23316. }
  23317. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23318. this._texture = this._getFromCache(this.url, this._noMipmap);
  23319. if (!this._texture) {
  23320. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23321. }
  23322. };
  23323. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23324. return this._textureMatrix;
  23325. };
  23326. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23327. var texture = BABYLON.SerializationHelper.Parse(function () {
  23328. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23329. }, parsedTexture, scene);
  23330. // Animations
  23331. if (parsedTexture.animations) {
  23332. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23333. var parsedAnimation = parsedTexture.animations[animationIndex];
  23334. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23335. }
  23336. }
  23337. return texture;
  23338. };
  23339. CubeTexture.prototype.clone = function () {
  23340. var _this = this;
  23341. return BABYLON.SerializationHelper.Clone(function () {
  23342. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23343. }, this);
  23344. };
  23345. return CubeTexture;
  23346. }(BABYLON.BaseTexture));
  23347. BABYLON.CubeTexture = CubeTexture;
  23348. })(BABYLON || (BABYLON = {}));
  23349. var BABYLON;
  23350. (function (BABYLON) {
  23351. var RenderTargetTexture = (function (_super) {
  23352. __extends(RenderTargetTexture, _super);
  23353. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23354. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23355. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23356. if (isCube === void 0) { isCube = false; }
  23357. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23358. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23359. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23360. _super.call(this, null, scene, !generateMipMaps);
  23361. this.isCube = isCube;
  23362. /**
  23363. * Use this list to define the list of mesh you want to render.
  23364. */
  23365. this.renderList = new Array();
  23366. this.renderParticles = true;
  23367. this.renderSprites = false;
  23368. this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23369. // Events
  23370. /**
  23371. * An event triggered when the texture is unbind.
  23372. * @type {BABYLON.Observable}
  23373. */
  23374. this.onAfterUnbindObservable = new BABYLON.Observable();
  23375. /**
  23376. * An event triggered before rendering the texture
  23377. * @type {BABYLON.Observable}
  23378. */
  23379. this.onBeforeRenderObservable = new BABYLON.Observable();
  23380. /**
  23381. * An event triggered after rendering the texture
  23382. * @type {BABYLON.Observable}
  23383. */
  23384. this.onAfterRenderObservable = new BABYLON.Observable();
  23385. /**
  23386. * An event triggered after the texture clear
  23387. * @type {BABYLON.Observable}
  23388. */
  23389. this.onClearObservable = new BABYLON.Observable();
  23390. this._currentRefreshId = -1;
  23391. this._refreshRate = 1;
  23392. this.name = name;
  23393. this.isRenderTarget = true;
  23394. this._size = size;
  23395. this._generateMipMaps = generateMipMaps;
  23396. this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23397. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23398. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23399. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23400. }
  23401. if (isCube) {
  23402. this._texture = scene.getEngine().createRenderTargetCubeTexture(size, {
  23403. generateMipMaps: generateMipMaps,
  23404. samplingMode: samplingMode,
  23405. generateDepthBuffer: generateDepthBuffer,
  23406. generateStencilBuffer: generateStencilBuffer
  23407. });
  23408. this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23409. this._textureMatrix = BABYLON.Matrix.Identity();
  23410. }
  23411. else {
  23412. this._texture = scene.getEngine().createRenderTargetTexture(size, {
  23413. generateMipMaps: generateMipMaps,
  23414. type: type,
  23415. samplingMode: samplingMode,
  23416. generateDepthBuffer: generateDepthBuffer,
  23417. generateStencilBuffer: generateStencilBuffer
  23418. });
  23419. }
  23420. // Rendering groups
  23421. this._renderingManager = new BABYLON.RenderingManager(scene);
  23422. }
  23423. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23424. get: function () {
  23425. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23426. },
  23427. enumerable: true,
  23428. configurable: true
  23429. });
  23430. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23431. get: function () {
  23432. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23433. },
  23434. enumerable: true,
  23435. configurable: true
  23436. });
  23437. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23438. get: function () {
  23439. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23440. },
  23441. enumerable: true,
  23442. configurable: true
  23443. });
  23444. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23445. set: function (callback) {
  23446. if (this._onAfterUnbindObserver) {
  23447. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23448. }
  23449. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23450. },
  23451. enumerable: true,
  23452. configurable: true
  23453. });
  23454. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  23455. set: function (callback) {
  23456. if (this._onBeforeRenderObserver) {
  23457. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  23458. }
  23459. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  23460. },
  23461. enumerable: true,
  23462. configurable: true
  23463. });
  23464. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  23465. set: function (callback) {
  23466. if (this._onAfterRenderObserver) {
  23467. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  23468. }
  23469. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  23470. },
  23471. enumerable: true,
  23472. configurable: true
  23473. });
  23474. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  23475. set: function (callback) {
  23476. if (this._onClearObserver) {
  23477. this.onClearObservable.remove(this._onClearObserver);
  23478. }
  23479. this._onClearObserver = this.onClearObservable.add(callback);
  23480. },
  23481. enumerable: true,
  23482. configurable: true
  23483. });
  23484. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  23485. this._currentRefreshId = -1;
  23486. };
  23487. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  23488. get: function () {
  23489. return this._refreshRate;
  23490. },
  23491. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23492. set: function (value) {
  23493. this._refreshRate = value;
  23494. this.resetRefreshCounter();
  23495. },
  23496. enumerable: true,
  23497. configurable: true
  23498. });
  23499. RenderTargetTexture.prototype._shouldRender = function () {
  23500. if (this._currentRefreshId === -1) {
  23501. this._currentRefreshId = 1;
  23502. return true;
  23503. }
  23504. if (this.refreshRate === this._currentRefreshId) {
  23505. this._currentRefreshId = 1;
  23506. return true;
  23507. }
  23508. this._currentRefreshId++;
  23509. return false;
  23510. };
  23511. RenderTargetTexture.prototype.isReady = function () {
  23512. if (!this.getScene().renderTargetsEnabled) {
  23513. return false;
  23514. }
  23515. return _super.prototype.isReady.call(this);
  23516. };
  23517. RenderTargetTexture.prototype.getRenderSize = function () {
  23518. return this._size;
  23519. };
  23520. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  23521. get: function () {
  23522. return true;
  23523. },
  23524. enumerable: true,
  23525. configurable: true
  23526. });
  23527. RenderTargetTexture.prototype.scale = function (ratio) {
  23528. var newSize = this._size * ratio;
  23529. this.resize(newSize, this._generateMipMaps);
  23530. };
  23531. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  23532. if (this.isCube) {
  23533. return this._textureMatrix;
  23534. }
  23535. return _super.prototype.getReflectionTextureMatrix.call(this);
  23536. };
  23537. RenderTargetTexture.prototype.resize = function (size, generateMipMaps) {
  23538. this.releaseInternalTexture();
  23539. if (this.isCube) {
  23540. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size);
  23541. }
  23542. else {
  23543. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23544. }
  23545. };
  23546. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  23547. var scene = this.getScene();
  23548. if (this.useCameraPostProcesses !== undefined) {
  23549. useCameraPostProcess = this.useCameraPostProcesses;
  23550. }
  23551. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23552. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  23553. }
  23554. if (this._waitingRenderList) {
  23555. this.renderList = [];
  23556. for (var index = 0; index < this._waitingRenderList.length; index++) {
  23557. var id = this._waitingRenderList[index];
  23558. this.renderList.push(scene.getMeshByID(id));
  23559. }
  23560. delete this._waitingRenderList;
  23561. }
  23562. // Is predicate defined?
  23563. if (this.renderListPredicate) {
  23564. this.renderList.splice(0); // Clear previous renderList
  23565. var sceneMeshes = this.getScene().meshes;
  23566. for (var index = 0; index < sceneMeshes.length; index++) {
  23567. var mesh = sceneMeshes[index];
  23568. if (this.renderListPredicate(mesh)) {
  23569. this.renderList.push(mesh);
  23570. }
  23571. }
  23572. }
  23573. if (this.renderList && this.renderList.length === 0) {
  23574. return;
  23575. }
  23576. // Prepare renderingManager
  23577. this._renderingManager.reset();
  23578. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  23579. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  23580. var sceneRenderId = scene.getRenderId();
  23581. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  23582. var mesh = currentRenderList[meshIndex];
  23583. if (mesh) {
  23584. if (!mesh.isReady()) {
  23585. // Reset _currentRefreshId
  23586. this.resetRefreshCounter();
  23587. continue;
  23588. }
  23589. mesh._preActivateForIntermediateRendering(sceneRenderId);
  23590. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  23591. mesh._activate(sceneRenderId);
  23592. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  23593. var subMesh = mesh.subMeshes[subIndex];
  23594. scene._activeIndices.addCount(subMesh.indexCount, false);
  23595. this._renderingManager.dispatch(subMesh);
  23596. }
  23597. }
  23598. }
  23599. }
  23600. if (this.isCube) {
  23601. for (var face = 0; face < 6; face++) {
  23602. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23603. scene.incrementRenderId();
  23604. scene.resetCachedMaterial();
  23605. }
  23606. }
  23607. else {
  23608. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  23609. }
  23610. this.onAfterUnbindObservable.notifyObservers(this);
  23611. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  23612. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  23613. }
  23614. scene.resetCachedMaterial();
  23615. };
  23616. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  23617. var scene = this.getScene();
  23618. var engine = scene.getEngine();
  23619. // Bind
  23620. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  23621. if (this.isCube) {
  23622. engine.bindFramebuffer(this._texture, faceIndex);
  23623. }
  23624. else {
  23625. engine.bindFramebuffer(this._texture);
  23626. }
  23627. }
  23628. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  23629. // Clear
  23630. if (this.onClearObservable.hasObservers()) {
  23631. this.onClearObservable.notifyObservers(engine);
  23632. }
  23633. else {
  23634. engine.clear(scene.clearColor, true, true, true);
  23635. }
  23636. if (!this._doNotChangeAspectRatio) {
  23637. scene.updateTransformMatrix(true);
  23638. }
  23639. // Render
  23640. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  23641. if (useCameraPostProcess) {
  23642. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  23643. }
  23644. if (!this._doNotChangeAspectRatio) {
  23645. scene.updateTransformMatrix(true);
  23646. }
  23647. this.onAfterRenderObservable.notifyObservers(faceIndex);
  23648. // Dump ?
  23649. if (dumpForDebug) {
  23650. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  23651. }
  23652. // Unbind
  23653. if (!this.isCube || faceIndex === 5) {
  23654. if (this.isCube) {
  23655. if (faceIndex === 5) {
  23656. engine.generateMipMapsForCubemap(this._texture);
  23657. }
  23658. }
  23659. engine.unBindFramebuffer(this._texture, this.isCube);
  23660. }
  23661. };
  23662. /**
  23663. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23664. * This allowed control for front to back rendering or reversly depending of the special needs.
  23665. *
  23666. * @param renderingGroupId The rendering group id corresponding to its index
  23667. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23668. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23669. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23670. */
  23671. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23672. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23673. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23674. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23675. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  23676. };
  23677. /**
  23678. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23679. *
  23680. * @param renderingGroupId The rendering group id corresponding to its index
  23681. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23682. */
  23683. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  23684. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  23685. };
  23686. RenderTargetTexture.prototype.clone = function () {
  23687. var textureSize = this.getSize();
  23688. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  23689. // Base texture
  23690. newTexture.hasAlpha = this.hasAlpha;
  23691. newTexture.level = this.level;
  23692. // RenderTarget Texture
  23693. newTexture.coordinatesMode = this.coordinatesMode;
  23694. newTexture.renderList = this.renderList.slice(0);
  23695. return newTexture;
  23696. };
  23697. RenderTargetTexture.prototype.serialize = function () {
  23698. if (!this.name) {
  23699. return null;
  23700. }
  23701. var serializationObject = _super.prototype.serialize.call(this);
  23702. serializationObject.renderTargetSize = this.getRenderSize();
  23703. serializationObject.renderList = [];
  23704. for (var index = 0; index < this.renderList.length; index++) {
  23705. serializationObject.renderList.push(this.renderList[index].id);
  23706. }
  23707. return serializationObject;
  23708. };
  23709. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  23710. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  23711. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  23712. return RenderTargetTexture;
  23713. }(BABYLON.Texture));
  23714. BABYLON.RenderTargetTexture = RenderTargetTexture;
  23715. })(BABYLON || (BABYLON = {}));
  23716. var BABYLON;
  23717. (function (BABYLON) {
  23718. var ProceduralTexture = (function (_super) {
  23719. __extends(ProceduralTexture, _super);
  23720. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  23721. if (generateMipMaps === void 0) { generateMipMaps = true; }
  23722. if (isCube === void 0) { isCube = false; }
  23723. _super.call(this, null, scene, !generateMipMaps);
  23724. this.isCube = isCube;
  23725. this.isEnabled = true;
  23726. this._currentRefreshId = -1;
  23727. this._refreshRate = 1;
  23728. this._vertexBuffers = {};
  23729. this._uniforms = new Array();
  23730. this._samplers = new Array();
  23731. this._textures = new Array();
  23732. this._floats = new Array();
  23733. this._floatsArrays = {};
  23734. this._colors3 = new Array();
  23735. this._colors4 = new Array();
  23736. this._vectors2 = new Array();
  23737. this._vectors3 = new Array();
  23738. this._matrices = new Array();
  23739. this._fallbackTextureUsed = false;
  23740. scene._proceduralTextures.push(this);
  23741. this.name = name;
  23742. this.isRenderTarget = true;
  23743. this._size = size;
  23744. this._generateMipMaps = generateMipMaps;
  23745. this.setFragment(fragment);
  23746. this._fallbackTexture = fallbackTexture;
  23747. var engine = scene.getEngine();
  23748. if (isCube) {
  23749. this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  23750. this.setFloat("face", 0);
  23751. }
  23752. else {
  23753. this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  23754. }
  23755. // VBO
  23756. var vertices = [];
  23757. vertices.push(1, 1);
  23758. vertices.push(-1, 1);
  23759. vertices.push(-1, -1);
  23760. vertices.push(1, -1);
  23761. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  23762. // Indices
  23763. var indices = [];
  23764. indices.push(0);
  23765. indices.push(1);
  23766. indices.push(2);
  23767. indices.push(0);
  23768. indices.push(2);
  23769. indices.push(3);
  23770. this._indexBuffer = engine.createIndexBuffer(indices);
  23771. }
  23772. ProceduralTexture.prototype.reset = function () {
  23773. if (this._effect === undefined) {
  23774. return;
  23775. }
  23776. var engine = this.getScene().getEngine();
  23777. engine._releaseEffect(this._effect);
  23778. };
  23779. ProceduralTexture.prototype.isReady = function () {
  23780. var _this = this;
  23781. var engine = this.getScene().getEngine();
  23782. var shaders;
  23783. if (!this._fragment) {
  23784. return false;
  23785. }
  23786. if (this._fallbackTextureUsed) {
  23787. return true;
  23788. }
  23789. if (this._fragment.fragmentElement !== undefined) {
  23790. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  23791. }
  23792. else {
  23793. shaders = { vertex: "procedural", fragment: this._fragment };
  23794. }
  23795. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  23796. _this.releaseInternalTexture();
  23797. if (_this._fallbackTexture) {
  23798. _this._texture = _this._fallbackTexture._texture;
  23799. _this._texture.references++;
  23800. }
  23801. _this._fallbackTextureUsed = true;
  23802. });
  23803. return this._effect.isReady();
  23804. };
  23805. ProceduralTexture.prototype.resetRefreshCounter = function () {
  23806. this._currentRefreshId = -1;
  23807. };
  23808. ProceduralTexture.prototype.setFragment = function (fragment) {
  23809. this._fragment = fragment;
  23810. };
  23811. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  23812. get: function () {
  23813. return this._refreshRate;
  23814. },
  23815. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  23816. set: function (value) {
  23817. this._refreshRate = value;
  23818. this.resetRefreshCounter();
  23819. },
  23820. enumerable: true,
  23821. configurable: true
  23822. });
  23823. ProceduralTexture.prototype._shouldRender = function () {
  23824. if (!this.isEnabled || !this.isReady() || !this._texture) {
  23825. return false;
  23826. }
  23827. if (this._fallbackTextureUsed) {
  23828. return false;
  23829. }
  23830. if (this._currentRefreshId === -1) {
  23831. this._currentRefreshId = 1;
  23832. return true;
  23833. }
  23834. if (this.refreshRate === this._currentRefreshId) {
  23835. this._currentRefreshId = 1;
  23836. return true;
  23837. }
  23838. this._currentRefreshId++;
  23839. return false;
  23840. };
  23841. ProceduralTexture.prototype.getRenderSize = function () {
  23842. return this._size;
  23843. };
  23844. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  23845. if (this._fallbackTextureUsed) {
  23846. return;
  23847. }
  23848. this.releaseInternalTexture();
  23849. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  23850. };
  23851. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  23852. if (this._uniforms.indexOf(uniformName) === -1) {
  23853. this._uniforms.push(uniformName);
  23854. }
  23855. };
  23856. ProceduralTexture.prototype.setTexture = function (name, texture) {
  23857. if (this._samplers.indexOf(name) === -1) {
  23858. this._samplers.push(name);
  23859. }
  23860. this._textures[name] = texture;
  23861. return this;
  23862. };
  23863. ProceduralTexture.prototype.setFloat = function (name, value) {
  23864. this._checkUniform(name);
  23865. this._floats[name] = value;
  23866. return this;
  23867. };
  23868. ProceduralTexture.prototype.setFloats = function (name, value) {
  23869. this._checkUniform(name);
  23870. this._floatsArrays[name] = value;
  23871. return this;
  23872. };
  23873. ProceduralTexture.prototype.setColor3 = function (name, value) {
  23874. this._checkUniform(name);
  23875. this._colors3[name] = value;
  23876. return this;
  23877. };
  23878. ProceduralTexture.prototype.setColor4 = function (name, value) {
  23879. this._checkUniform(name);
  23880. this._colors4[name] = value;
  23881. return this;
  23882. };
  23883. ProceduralTexture.prototype.setVector2 = function (name, value) {
  23884. this._checkUniform(name);
  23885. this._vectors2[name] = value;
  23886. return this;
  23887. };
  23888. ProceduralTexture.prototype.setVector3 = function (name, value) {
  23889. this._checkUniform(name);
  23890. this._vectors3[name] = value;
  23891. return this;
  23892. };
  23893. ProceduralTexture.prototype.setMatrix = function (name, value) {
  23894. this._checkUniform(name);
  23895. this._matrices[name] = value;
  23896. return this;
  23897. };
  23898. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  23899. var scene = this.getScene();
  23900. var engine = scene.getEngine();
  23901. // Render
  23902. engine.enableEffect(this._effect);
  23903. engine.setState(false);
  23904. // Texture
  23905. for (var name in this._textures) {
  23906. this._effect.setTexture(name, this._textures[name]);
  23907. }
  23908. // Float
  23909. for (name in this._floats) {
  23910. this._effect.setFloat(name, this._floats[name]);
  23911. }
  23912. // Floats
  23913. for (name in this._floatsArrays) {
  23914. this._effect.setArray(name, this._floatsArrays[name]);
  23915. }
  23916. // Color3
  23917. for (name in this._colors3) {
  23918. this._effect.setColor3(name, this._colors3[name]);
  23919. }
  23920. // Color4
  23921. for (name in this._colors4) {
  23922. var color = this._colors4[name];
  23923. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  23924. }
  23925. // Vector2
  23926. for (name in this._vectors2) {
  23927. this._effect.setVector2(name, this._vectors2[name]);
  23928. }
  23929. // Vector3
  23930. for (name in this._vectors3) {
  23931. this._effect.setVector3(name, this._vectors3[name]);
  23932. }
  23933. // Matrix
  23934. for (name in this._matrices) {
  23935. this._effect.setMatrix(name, this._matrices[name]);
  23936. }
  23937. // VBOs
  23938. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  23939. if (this.isCube) {
  23940. for (var face = 0; face < 6; face++) {
  23941. engine.bindFramebuffer(this._texture, face);
  23942. this._effect.setFloat("face", face);
  23943. // Clear
  23944. engine.clear(scene.clearColor, true, true, true);
  23945. // Draw order
  23946. engine.draw(true, 0, 6);
  23947. // Mipmaps
  23948. if (face === 5) {
  23949. engine.generateMipMapsForCubemap(this._texture);
  23950. }
  23951. }
  23952. }
  23953. else {
  23954. engine.bindFramebuffer(this._texture);
  23955. // Clear
  23956. engine.clear(scene.clearColor, true, true, true);
  23957. // Draw order
  23958. engine.draw(true, 0, 6);
  23959. }
  23960. // Unbind
  23961. engine.unBindFramebuffer(this._texture, this.isCube);
  23962. if (this.onGenerated) {
  23963. this.onGenerated();
  23964. }
  23965. };
  23966. ProceduralTexture.prototype.clone = function () {
  23967. var textureSize = this.getSize();
  23968. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  23969. // Base texture
  23970. newTexture.hasAlpha = this.hasAlpha;
  23971. newTexture.level = this.level;
  23972. // RenderTarget Texture
  23973. newTexture.coordinatesMode = this.coordinatesMode;
  23974. return newTexture;
  23975. };
  23976. ProceduralTexture.prototype.dispose = function () {
  23977. var index = this.getScene()._proceduralTextures.indexOf(this);
  23978. if (index >= 0) {
  23979. this.getScene()._proceduralTextures.splice(index, 1);
  23980. }
  23981. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  23982. if (vertexBuffer) {
  23983. vertexBuffer.dispose();
  23984. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  23985. }
  23986. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  23987. this._indexBuffer = null;
  23988. }
  23989. _super.prototype.dispose.call(this);
  23990. };
  23991. return ProceduralTexture;
  23992. }(BABYLON.Texture));
  23993. BABYLON.ProceduralTexture = ProceduralTexture;
  23994. })(BABYLON || (BABYLON = {}));
  23995. var BABYLON;
  23996. (function (BABYLON) {
  23997. var MirrorTexture = (function (_super) {
  23998. __extends(MirrorTexture, _super);
  23999. function MirrorTexture(name, size, scene, generateMipMaps) {
  24000. var _this = this;
  24001. _super.call(this, name, size, scene, generateMipMaps, true);
  24002. this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  24003. this._transformMatrix = BABYLON.Matrix.Zero();
  24004. this._mirrorMatrix = BABYLON.Matrix.Zero();
  24005. this.onBeforeRenderObservable.add(function () {
  24006. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  24007. _this._savedViewMatrix = scene.getViewMatrix();
  24008. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  24009. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  24010. scene.clipPlane = _this.mirrorPlane;
  24011. scene.getEngine().cullBackFaces = false;
  24012. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  24013. });
  24014. this.onAfterRenderObservable.add(function () {
  24015. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  24016. scene.getEngine().cullBackFaces = true;
  24017. scene._mirroredCameraPosition = null;
  24018. delete scene.clipPlane;
  24019. });
  24020. }
  24021. MirrorTexture.prototype.clone = function () {
  24022. var textureSize = this.getSize();
  24023. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24024. // Base texture
  24025. newTexture.hasAlpha = this.hasAlpha;
  24026. newTexture.level = this.level;
  24027. // Mirror Texture
  24028. newTexture.mirrorPlane = this.mirrorPlane.clone();
  24029. newTexture.renderList = this.renderList.slice(0);
  24030. return newTexture;
  24031. };
  24032. MirrorTexture.prototype.serialize = function () {
  24033. if (!this.name) {
  24034. return null;
  24035. }
  24036. var serializationObject = _super.prototype.serialize.call(this);
  24037. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  24038. return serializationObject;
  24039. };
  24040. return MirrorTexture;
  24041. }(BABYLON.RenderTargetTexture));
  24042. BABYLON.MirrorTexture = MirrorTexture;
  24043. })(BABYLON || (BABYLON = {}));
  24044. var BABYLON;
  24045. (function (BABYLON) {
  24046. /**
  24047. * Creates a refraction texture used by refraction channel of the standard material.
  24048. * @param name the texture name
  24049. * @param size size of the underlying texture
  24050. * @param scene root scene
  24051. */
  24052. var RefractionTexture = (function (_super) {
  24053. __extends(RefractionTexture, _super);
  24054. function RefractionTexture(name, size, scene, generateMipMaps) {
  24055. var _this = this;
  24056. _super.call(this, name, size, scene, generateMipMaps, true);
  24057. this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  24058. this.depth = 2.0;
  24059. this.onBeforeRenderObservable.add(function () {
  24060. scene.clipPlane = _this.refractionPlane;
  24061. });
  24062. this.onAfterRenderObservable.add(function () {
  24063. delete scene.clipPlane;
  24064. });
  24065. }
  24066. RefractionTexture.prototype.clone = function () {
  24067. var textureSize = this.getSize();
  24068. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24069. // Base texture
  24070. newTexture.hasAlpha = this.hasAlpha;
  24071. newTexture.level = this.level;
  24072. // Refraction Texture
  24073. newTexture.refractionPlane = this.refractionPlane.clone();
  24074. newTexture.renderList = this.renderList.slice(0);
  24075. newTexture.depth = this.depth;
  24076. return newTexture;
  24077. };
  24078. RefractionTexture.prototype.serialize = function () {
  24079. if (!this.name) {
  24080. return null;
  24081. }
  24082. var serializationObject = _super.prototype.serialize.call(this);
  24083. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  24084. serializationObject.depth = this.depth;
  24085. return serializationObject;
  24086. };
  24087. return RefractionTexture;
  24088. }(BABYLON.RenderTargetTexture));
  24089. BABYLON.RefractionTexture = RefractionTexture;
  24090. })(BABYLON || (BABYLON = {}));
  24091. var BABYLON;
  24092. (function (BABYLON) {
  24093. var DynamicTexture = (function (_super) {
  24094. __extends(DynamicTexture, _super);
  24095. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  24096. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24097. _super.call(this, null, scene, !generateMipMaps);
  24098. this.name = name;
  24099. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24100. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24101. this._generateMipMaps = generateMipMaps;
  24102. if (options.getContext) {
  24103. this._canvas = options;
  24104. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24105. }
  24106. else {
  24107. this._canvas = document.createElement("canvas");
  24108. if (options.width) {
  24109. this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24110. }
  24111. else {
  24112. this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  24113. }
  24114. }
  24115. var textureSize = this.getSize();
  24116. this._canvas.width = textureSize.width;
  24117. this._canvas.height = textureSize.height;
  24118. this._context = this._canvas.getContext("2d");
  24119. }
  24120. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  24121. get: function () {
  24122. return true;
  24123. },
  24124. enumerable: true,
  24125. configurable: true
  24126. });
  24127. DynamicTexture.prototype.scale = function (ratio) {
  24128. var textureSize = this.getSize();
  24129. textureSize.width *= ratio;
  24130. textureSize.height *= ratio;
  24131. this._canvas.width = textureSize.width;
  24132. this._canvas.height = textureSize.height;
  24133. this.releaseInternalTexture();
  24134. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  24135. };
  24136. DynamicTexture.prototype.getContext = function () {
  24137. return this._context;
  24138. };
  24139. DynamicTexture.prototype.clear = function () {
  24140. var size = this.getSize();
  24141. this._context.fillRect(0, 0, size.width, size.height);
  24142. };
  24143. DynamicTexture.prototype.update = function (invertY) {
  24144. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  24145. };
  24146. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  24147. if (update === void 0) { update = true; }
  24148. var size = this.getSize();
  24149. if (clearColor) {
  24150. this._context.fillStyle = clearColor;
  24151. this._context.fillRect(0, 0, size.width, size.height);
  24152. }
  24153. this._context.font = font;
  24154. if (x === null) {
  24155. var textSize = this._context.measureText(text);
  24156. x = (size.width - textSize.width) / 2;
  24157. }
  24158. this._context.fillStyle = color;
  24159. this._context.fillText(text, x, y);
  24160. if (update) {
  24161. this.update(invertY);
  24162. }
  24163. };
  24164. DynamicTexture.prototype.clone = function () {
  24165. var textureSize = this.getSize();
  24166. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  24167. // Base texture
  24168. newTexture.hasAlpha = this.hasAlpha;
  24169. newTexture.level = this.level;
  24170. // Dynamic Texture
  24171. newTexture.wrapU = this.wrapU;
  24172. newTexture.wrapV = this.wrapV;
  24173. return newTexture;
  24174. };
  24175. return DynamicTexture;
  24176. }(BABYLON.Texture));
  24177. BABYLON.DynamicTexture = DynamicTexture;
  24178. })(BABYLON || (BABYLON = {}));
  24179. var BABYLON;
  24180. (function (BABYLON) {
  24181. var VideoTexture = (function (_super) {
  24182. __extends(VideoTexture, _super);
  24183. /**
  24184. * Creates a video texture.
  24185. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  24186. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  24187. * @param {BABYLON.Scene} scene is obviously the current scene.
  24188. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  24189. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  24190. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  24191. */
  24192. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  24193. var _this = this;
  24194. if (generateMipMaps === void 0) { generateMipMaps = false; }
  24195. if (invertY === void 0) { invertY = false; }
  24196. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24197. _super.call(this, null, scene, !generateMipMaps, invertY);
  24198. this._autoLaunch = true;
  24199. var urls;
  24200. this.name = name;
  24201. if (urlsOrVideo instanceof HTMLVideoElement) {
  24202. this.video = urlsOrVideo;
  24203. }
  24204. else {
  24205. urls = urlsOrVideo;
  24206. this.video = document.createElement("video");
  24207. this.video.autoplay = false;
  24208. this.video.loop = true;
  24209. }
  24210. this._generateMipMaps = generateMipMaps;
  24211. this._samplingMode = samplingMode;
  24212. if (BABYLON.Tools.IsExponentOfTwo(this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(this.video.videoHeight)) {
  24213. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24214. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24215. }
  24216. else {
  24217. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24218. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24219. this._generateMipMaps = false;
  24220. }
  24221. if (urls) {
  24222. this.video.addEventListener("canplaythrough", function () {
  24223. _this._createTexture();
  24224. });
  24225. urls.forEach(function (url) {
  24226. var source = document.createElement("source");
  24227. source.src = url;
  24228. _this.video.appendChild(source);
  24229. });
  24230. }
  24231. else {
  24232. this._createTexture();
  24233. }
  24234. this._lastUpdate = BABYLON.Tools.Now;
  24235. }
  24236. VideoTexture.prototype._createTexture = function () {
  24237. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24238. this._texture.isReady = true;
  24239. };
  24240. VideoTexture.prototype.update = function () {
  24241. if (this._autoLaunch) {
  24242. this._autoLaunch = false;
  24243. this.video.play();
  24244. }
  24245. var now = BABYLON.Tools.Now;
  24246. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24247. return false;
  24248. }
  24249. this._lastUpdate = now;
  24250. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24251. return true;
  24252. };
  24253. return VideoTexture;
  24254. }(BABYLON.Texture));
  24255. BABYLON.VideoTexture = VideoTexture;
  24256. })(BABYLON || (BABYLON = {}));
  24257. var BABYLON;
  24258. (function (BABYLON) {
  24259. var CustomProceduralTexture = (function (_super) {
  24260. __extends(CustomProceduralTexture, _super);
  24261. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24262. _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps);
  24263. this._animate = true;
  24264. this._time = 0;
  24265. this._texturePath = texturePath;
  24266. //Try to load json
  24267. this.loadJson(texturePath);
  24268. this.refreshRate = 1;
  24269. }
  24270. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24271. var _this = this;
  24272. var that = this;
  24273. function noConfigFile() {
  24274. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24275. try {
  24276. that.setFragment(that._texturePath);
  24277. }
  24278. catch (ex) {
  24279. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24280. }
  24281. }
  24282. var configFileUrl = jsonUrl + "/config.json";
  24283. var xhr = new XMLHttpRequest();
  24284. xhr.open("GET", configFileUrl, true);
  24285. xhr.addEventListener("load", function () {
  24286. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24287. try {
  24288. _this._config = JSON.parse(xhr.response);
  24289. _this.updateShaderUniforms();
  24290. _this.updateTextures();
  24291. _this.setFragment(_this._texturePath + "/custom");
  24292. _this._animate = _this._config.animate;
  24293. _this.refreshRate = _this._config.refreshrate;
  24294. }
  24295. catch (ex) {
  24296. noConfigFile();
  24297. }
  24298. }
  24299. else {
  24300. noConfigFile();
  24301. }
  24302. }, false);
  24303. xhr.addEventListener("error", function () {
  24304. noConfigFile();
  24305. }, false);
  24306. try {
  24307. xhr.send();
  24308. }
  24309. catch (ex) {
  24310. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24311. }
  24312. };
  24313. CustomProceduralTexture.prototype.isReady = function () {
  24314. if (!_super.prototype.isReady.call(this)) {
  24315. return false;
  24316. }
  24317. for (var name in this._textures) {
  24318. var texture = this._textures[name];
  24319. if (!texture.isReady()) {
  24320. return false;
  24321. }
  24322. }
  24323. return true;
  24324. };
  24325. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24326. if (this._animate) {
  24327. this._time += this.getScene().getAnimationRatio() * 0.03;
  24328. this.updateShaderUniforms();
  24329. }
  24330. _super.prototype.render.call(this, useCameraPostProcess);
  24331. };
  24332. CustomProceduralTexture.prototype.updateTextures = function () {
  24333. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24334. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24335. }
  24336. };
  24337. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24338. if (this._config) {
  24339. for (var j = 0; j < this._config.uniforms.length; j++) {
  24340. var uniform = this._config.uniforms[j];
  24341. switch (uniform.type) {
  24342. case "float":
  24343. this.setFloat(uniform.name, uniform.value);
  24344. break;
  24345. case "color3":
  24346. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24347. break;
  24348. case "color4":
  24349. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24350. break;
  24351. case "vector2":
  24352. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24353. break;
  24354. case "vector3":
  24355. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24356. break;
  24357. }
  24358. }
  24359. }
  24360. this.setFloat("time", this._time);
  24361. };
  24362. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24363. get: function () {
  24364. return this._animate;
  24365. },
  24366. set: function (value) {
  24367. this._animate = value;
  24368. },
  24369. enumerable: true,
  24370. configurable: true
  24371. });
  24372. return CustomProceduralTexture;
  24373. }(BABYLON.ProceduralTexture));
  24374. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24375. })(BABYLON || (BABYLON = {}));
  24376. var BABYLON;
  24377. (function (BABYLON) {
  24378. var EffectFallbacks = (function () {
  24379. function EffectFallbacks() {
  24380. this._defines = {};
  24381. this._currentRank = 32;
  24382. this._maxRank = -1;
  24383. }
  24384. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24385. if (!this._defines[rank]) {
  24386. if (rank < this._currentRank) {
  24387. this._currentRank = rank;
  24388. }
  24389. if (rank > this._maxRank) {
  24390. this._maxRank = rank;
  24391. }
  24392. this._defines[rank] = new Array();
  24393. }
  24394. this._defines[rank].push(define);
  24395. };
  24396. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  24397. this._meshRank = rank;
  24398. this._mesh = mesh;
  24399. if (rank > this._maxRank) {
  24400. this._maxRank = rank;
  24401. }
  24402. };
  24403. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  24404. get: function () {
  24405. return this._currentRank <= this._maxRank;
  24406. },
  24407. enumerable: true,
  24408. configurable: true
  24409. });
  24410. EffectFallbacks.prototype.reduce = function (currentDefines) {
  24411. var currentFallbacks = this._defines[this._currentRank];
  24412. for (var index = 0; index < currentFallbacks.length; index++) {
  24413. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  24414. }
  24415. if (this._mesh && this._currentRank === this._meshRank) {
  24416. this._mesh.computeBonesUsingShaders = false;
  24417. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  24418. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  24419. }
  24420. this._currentRank++;
  24421. return currentDefines;
  24422. };
  24423. return EffectFallbacks;
  24424. }());
  24425. BABYLON.EffectFallbacks = EffectFallbacks;
  24426. var Effect = (function () {
  24427. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  24428. var _this = this;
  24429. this._isReady = false;
  24430. this._compilationError = "";
  24431. this._valueCache = {};
  24432. this._engine = engine;
  24433. this.name = baseName;
  24434. this.defines = defines;
  24435. this._uniformsNames = uniformsNames.concat(samplers);
  24436. this._samplers = samplers;
  24437. this._attributesNames = attributesNames;
  24438. this.onError = onError;
  24439. this.onCompiled = onCompiled;
  24440. this._indexParameters = indexParameters;
  24441. var vertexSource;
  24442. var fragmentSource;
  24443. if (baseName.vertexElement) {
  24444. vertexSource = document.getElementById(baseName.vertexElement);
  24445. if (!vertexSource) {
  24446. vertexSource = baseName.vertexElement;
  24447. }
  24448. }
  24449. else {
  24450. vertexSource = baseName.vertex || baseName;
  24451. }
  24452. if (baseName.fragmentElement) {
  24453. fragmentSource = document.getElementById(baseName.fragmentElement);
  24454. if (!fragmentSource) {
  24455. fragmentSource = baseName.fragmentElement;
  24456. }
  24457. }
  24458. else {
  24459. fragmentSource = baseName.fragment || baseName;
  24460. }
  24461. this._loadVertexShader(vertexSource, function (vertexCode) {
  24462. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24463. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24464. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24465. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  24466. });
  24467. });
  24468. });
  24469. });
  24470. }
  24471. // Properties
  24472. Effect.prototype.isReady = function () {
  24473. return this._isReady;
  24474. };
  24475. Effect.prototype.getProgram = function () {
  24476. return this._program;
  24477. };
  24478. Effect.prototype.getAttributesNames = function () {
  24479. return this._attributesNames;
  24480. };
  24481. Effect.prototype.getAttributeLocation = function (index) {
  24482. return this._attributes[index];
  24483. };
  24484. Effect.prototype.getAttributeLocationByName = function (name) {
  24485. var index = this._attributesNames.indexOf(name);
  24486. return this._attributes[index];
  24487. };
  24488. Effect.prototype.getAttributesCount = function () {
  24489. return this._attributes.length;
  24490. };
  24491. Effect.prototype.getUniformIndex = function (uniformName) {
  24492. return this._uniformsNames.indexOf(uniformName);
  24493. };
  24494. Effect.prototype.getUniform = function (uniformName) {
  24495. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24496. };
  24497. Effect.prototype.getSamplers = function () {
  24498. return this._samplers;
  24499. };
  24500. Effect.prototype.getCompilationError = function () {
  24501. return this._compilationError;
  24502. };
  24503. // Methods
  24504. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24505. // DOM element ?
  24506. if (vertex instanceof HTMLElement) {
  24507. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24508. callback(vertexCode);
  24509. return;
  24510. }
  24511. // Base64 encoded ?
  24512. if (vertex.substr(0, 7) === "base64:") {
  24513. var vertexBinary = window.atob(vertex.substr(7));
  24514. callback(vertexBinary);
  24515. return;
  24516. }
  24517. // Is in local store ?
  24518. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24519. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24520. return;
  24521. }
  24522. var vertexShaderUrl;
  24523. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24524. vertexShaderUrl = vertex;
  24525. }
  24526. else {
  24527. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24528. }
  24529. // Vertex shader
  24530. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24531. };
  24532. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24533. // DOM element ?
  24534. if (fragment instanceof HTMLElement) {
  24535. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24536. callback(fragmentCode);
  24537. return;
  24538. }
  24539. // Base64 encoded ?
  24540. if (fragment.substr(0, 7) === "base64:") {
  24541. var fragmentBinary = window.atob(fragment.substr(7));
  24542. callback(fragmentBinary);
  24543. return;
  24544. }
  24545. // Is in local store ?
  24546. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24547. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24548. return;
  24549. }
  24550. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24551. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24552. return;
  24553. }
  24554. var fragmentShaderUrl;
  24555. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24556. fragmentShaderUrl = fragment;
  24557. }
  24558. else {
  24559. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24560. }
  24561. // Fragment shader
  24562. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24563. };
  24564. Effect.prototype._dumpShadersName = function () {
  24565. if (this.name.vertexElement) {
  24566. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  24567. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  24568. }
  24569. else if (this.name.vertex) {
  24570. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  24571. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  24572. }
  24573. else {
  24574. BABYLON.Tools.Error("Vertex shader:" + this.name);
  24575. BABYLON.Tools.Error("Fragment shader:" + this.name);
  24576. }
  24577. };
  24578. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24579. var _this = this;
  24580. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24581. var match = regex.exec(sourceCode);
  24582. var returnValue = new String(sourceCode);
  24583. while (match != null) {
  24584. var includeFile = match[1];
  24585. if (Effect.IncludesShadersStore[includeFile]) {
  24586. // Substitution
  24587. var includeContent = Effect.IncludesShadersStore[includeFile];
  24588. if (match[2]) {
  24589. var splits = match[3].split(",");
  24590. for (var index = 0; index < splits.length; index += 2) {
  24591. var source = new RegExp(splits[index], "g");
  24592. var dest = splits[index + 1];
  24593. includeContent = includeContent.replace(source, dest);
  24594. }
  24595. }
  24596. if (match[4]) {
  24597. var indexString = match[5];
  24598. if (indexString.indexOf("..") !== -1) {
  24599. var indexSplits = indexString.split("..");
  24600. var minIndex = parseInt(indexSplits[0]);
  24601. var maxIndex = parseInt(indexSplits[1]);
  24602. var sourceIncludeContent = includeContent.slice(0);
  24603. includeContent = "";
  24604. if (isNaN(maxIndex)) {
  24605. maxIndex = this._indexParameters[indexSplits[1]];
  24606. }
  24607. for (var i = minIndex; i <= maxIndex; i++) {
  24608. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24609. }
  24610. }
  24611. else {
  24612. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24613. }
  24614. }
  24615. // Replace
  24616. returnValue = returnValue.replace(match[0], includeContent);
  24617. }
  24618. else {
  24619. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24620. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24621. Effect.IncludesShadersStore[includeFile] = fileContent;
  24622. _this._processIncludes(returnValue, callback);
  24623. });
  24624. return;
  24625. }
  24626. match = regex.exec(sourceCode);
  24627. }
  24628. callback(returnValue);
  24629. };
  24630. Effect.prototype._processPrecision = function (source) {
  24631. if (source.indexOf("precision highp float") === -1) {
  24632. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24633. source = "precision mediump float;\n" + source;
  24634. }
  24635. else {
  24636. source = "precision highp float;\n" + source;
  24637. }
  24638. }
  24639. else {
  24640. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24641. source = source.replace("precision highp float", "precision mediump float");
  24642. }
  24643. }
  24644. return source;
  24645. };
  24646. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  24647. try {
  24648. var engine = this._engine;
  24649. // Precision
  24650. vertexSourceCode = this._processPrecision(vertexSourceCode);
  24651. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  24652. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  24653. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24654. this._attributes = engine.getAttributes(this._program, attributesNames);
  24655. var index;
  24656. for (index = 0; index < this._samplers.length; index++) {
  24657. var sampler = this.getUniform(this._samplers[index]);
  24658. if (sampler == null) {
  24659. this._samplers.splice(index, 1);
  24660. index--;
  24661. }
  24662. }
  24663. engine.bindSamplers(this);
  24664. this._isReady = true;
  24665. if (this.onCompiled) {
  24666. this.onCompiled(this);
  24667. }
  24668. }
  24669. catch (e) {
  24670. // Let's go through fallbacks then
  24671. if (fallbacks && fallbacks.isMoreFallbacks) {
  24672. BABYLON.Tools.Error("Unable to compile effect with current defines. Trying next fallback.");
  24673. this._dumpShadersName();
  24674. defines = fallbacks.reduce(defines);
  24675. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  24676. }
  24677. else {
  24678. BABYLON.Tools.Error("Unable to compile effect: ");
  24679. this._dumpShadersName();
  24680. BABYLON.Tools.Error("Defines: " + defines);
  24681. BABYLON.Tools.Error("Error: " + e.message);
  24682. this._compilationError = e.message;
  24683. if (this.onError) {
  24684. this.onError(this, this._compilationError);
  24685. }
  24686. }
  24687. }
  24688. };
  24689. Object.defineProperty(Effect.prototype, "isSupported", {
  24690. get: function () {
  24691. return this._compilationError === "";
  24692. },
  24693. enumerable: true,
  24694. configurable: true
  24695. });
  24696. Effect.prototype._bindTexture = function (channel, texture) {
  24697. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24698. };
  24699. Effect.prototype.setTexture = function (channel, texture) {
  24700. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24701. };
  24702. Effect.prototype.setTextureArray = function (channel, textures) {
  24703. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24704. var initialPos = this._samplers.indexOf(channel);
  24705. for (var index = 1; index < textures.length; index++) {
  24706. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24707. }
  24708. }
  24709. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24710. };
  24711. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24712. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24713. };
  24714. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24715. var changed = false;
  24716. var cache = this._valueCache[uniformName];
  24717. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  24718. changed = true;
  24719. cache = new BABYLON.Matrix();
  24720. }
  24721. var tm = cache.m;
  24722. var om = matrix.m;
  24723. for (var index = 0; index < 16; index++) {
  24724. if (tm[index] !== om[index]) {
  24725. tm[index] = om[index];
  24726. changed = true;
  24727. }
  24728. }
  24729. this._valueCache[uniformName] = cache;
  24730. return changed;
  24731. };
  24732. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24733. var cache = this._valueCache[uniformName];
  24734. if (!cache) {
  24735. cache = [x, y];
  24736. this._valueCache[uniformName] = cache;
  24737. return true;
  24738. }
  24739. var changed = false;
  24740. if (cache[0] !== x) {
  24741. cache[0] = x;
  24742. changed = true;
  24743. }
  24744. if (cache[1] !== y) {
  24745. cache[1] = y;
  24746. changed = true;
  24747. }
  24748. return changed;
  24749. };
  24750. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24751. var cache = this._valueCache[uniformName];
  24752. if (!cache) {
  24753. cache = [x, y, z];
  24754. this._valueCache[uniformName] = cache;
  24755. return true;
  24756. }
  24757. var changed = false;
  24758. if (cache[0] !== x) {
  24759. cache[0] = x;
  24760. changed = true;
  24761. }
  24762. if (cache[1] !== y) {
  24763. cache[1] = y;
  24764. changed = true;
  24765. }
  24766. if (cache[2] !== z) {
  24767. cache[2] = z;
  24768. changed = true;
  24769. }
  24770. return changed;
  24771. };
  24772. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24773. var cache = this._valueCache[uniformName];
  24774. if (!cache) {
  24775. cache = [x, y, z, w];
  24776. this._valueCache[uniformName] = cache;
  24777. return true;
  24778. }
  24779. var changed = false;
  24780. if (cache[0] !== x) {
  24781. cache[0] = x;
  24782. changed = true;
  24783. }
  24784. if (cache[1] !== y) {
  24785. cache[1] = y;
  24786. changed = true;
  24787. }
  24788. if (cache[2] !== z) {
  24789. cache[2] = z;
  24790. changed = true;
  24791. }
  24792. if (cache[3] !== w) {
  24793. cache[3] = w;
  24794. changed = true;
  24795. }
  24796. return changed;
  24797. };
  24798. Effect.prototype.setIntArray = function (uniformName, array) {
  24799. this._valueCache[uniformName] = null;
  24800. this._engine.setIntArray(this.getUniform(uniformName), array);
  24801. return this;
  24802. };
  24803. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24804. this._valueCache[uniformName] = null;
  24805. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24806. return this;
  24807. };
  24808. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24809. this._valueCache[uniformName] = null;
  24810. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24811. return this;
  24812. };
  24813. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24814. this._valueCache[uniformName] = null;
  24815. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24816. return this;
  24817. };
  24818. Effect.prototype.setFloatArray = function (uniformName, array) {
  24819. this._valueCache[uniformName] = null;
  24820. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24821. return this;
  24822. };
  24823. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24824. this._valueCache[uniformName] = null;
  24825. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24826. return this;
  24827. };
  24828. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24829. this._valueCache[uniformName] = null;
  24830. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24831. return this;
  24832. };
  24833. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24834. this._valueCache[uniformName] = null;
  24835. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24836. return this;
  24837. };
  24838. Effect.prototype.setArray = function (uniformName, array) {
  24839. this._valueCache[uniformName] = null;
  24840. this._engine.setArray(this.getUniform(uniformName), array);
  24841. return this;
  24842. };
  24843. Effect.prototype.setArray2 = function (uniformName, array) {
  24844. this._valueCache[uniformName] = null;
  24845. this._engine.setArray2(this.getUniform(uniformName), array);
  24846. return this;
  24847. };
  24848. Effect.prototype.setArray3 = function (uniformName, array) {
  24849. this._valueCache[uniformName] = null;
  24850. this._engine.setArray3(this.getUniform(uniformName), array);
  24851. return this;
  24852. };
  24853. Effect.prototype.setArray4 = function (uniformName, array) {
  24854. this._valueCache[uniformName] = null;
  24855. this._engine.setArray4(this.getUniform(uniformName), array);
  24856. return this;
  24857. };
  24858. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24859. this._valueCache[uniformName] = null;
  24860. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24861. return this;
  24862. };
  24863. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24864. if (this._cacheMatrix(uniformName, matrix)) {
  24865. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24866. }
  24867. return this;
  24868. };
  24869. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24870. this._valueCache[uniformName] = null;
  24871. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24872. return this;
  24873. };
  24874. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24875. this._valueCache[uniformName] = null;
  24876. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24877. return this;
  24878. };
  24879. Effect.prototype.setFloat = function (uniformName, value) {
  24880. var cache = this._valueCache[uniformName];
  24881. if (cache !== undefined && cache === value)
  24882. return this;
  24883. this._valueCache[uniformName] = value;
  24884. this._engine.setFloat(this.getUniform(uniformName), value);
  24885. return this;
  24886. };
  24887. Effect.prototype.setBool = function (uniformName, bool) {
  24888. var cache = this._valueCache[uniformName];
  24889. if (cache !== undefined && cache === bool)
  24890. return this;
  24891. this._valueCache[uniformName] = bool;
  24892. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24893. return this;
  24894. };
  24895. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24896. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24897. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24898. }
  24899. return this;
  24900. };
  24901. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24902. if (this._cacheFloat2(uniformName, x, y)) {
  24903. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24904. }
  24905. return this;
  24906. };
  24907. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24908. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24909. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24910. }
  24911. return this;
  24912. };
  24913. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24914. if (this._cacheFloat3(uniformName, x, y, z)) {
  24915. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24916. }
  24917. return this;
  24918. };
  24919. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24920. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24921. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24922. }
  24923. return this;
  24924. };
  24925. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24926. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24927. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24928. }
  24929. return this;
  24930. };
  24931. Effect.prototype.setColor3 = function (uniformName, color3) {
  24932. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24933. this._engine.setColor3(this.getUniform(uniformName), color3);
  24934. }
  24935. return this;
  24936. };
  24937. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24938. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24939. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24940. }
  24941. return this;
  24942. };
  24943. // Statics
  24944. Effect.ShadersStore = {};
  24945. Effect.IncludesShadersStore = {};
  24946. return Effect;
  24947. }());
  24948. BABYLON.Effect = Effect;
  24949. })(BABYLON || (BABYLON = {}));
  24950. var BABYLON;
  24951. (function (BABYLON) {
  24952. var MaterialHelper = (function () {
  24953. function MaterialHelper() {
  24954. }
  24955. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  24956. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24957. var lightIndex = 0;
  24958. var needNormals = false;
  24959. var needRebuild = false;
  24960. var needShadows = false;
  24961. var lightmapMode = false;
  24962. for (var index = 0; index < scene.lights.length; index++) {
  24963. var light = scene.lights[index];
  24964. if (!light.isEnabled()) {
  24965. continue;
  24966. }
  24967. // Excluded check
  24968. if (light._excludedMeshesIds.length > 0) {
  24969. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  24970. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  24971. if (excludedMesh) {
  24972. light.excludedMeshes.push(excludedMesh);
  24973. }
  24974. }
  24975. light._excludedMeshesIds = [];
  24976. }
  24977. // Included check
  24978. if (light._includedOnlyMeshesIds.length > 0) {
  24979. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  24980. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  24981. if (includedOnlyMesh) {
  24982. light.includedOnlyMeshes.push(includedOnlyMesh);
  24983. }
  24984. }
  24985. light._includedOnlyMeshesIds = [];
  24986. }
  24987. if (!light.canAffectMesh(mesh)) {
  24988. continue;
  24989. }
  24990. needNormals = true;
  24991. if (defines["LIGHT" + lightIndex] === undefined) {
  24992. needRebuild = true;
  24993. }
  24994. defines["LIGHT" + lightIndex] = true;
  24995. var type;
  24996. if (light instanceof BABYLON.SpotLight) {
  24997. type = "SPOTLIGHT" + lightIndex;
  24998. }
  24999. else if (light instanceof BABYLON.HemisphericLight) {
  25000. type = "HEMILIGHT" + lightIndex;
  25001. }
  25002. else if (light instanceof BABYLON.PointLight) {
  25003. type = "POINTLIGHT" + lightIndex;
  25004. }
  25005. else {
  25006. type = "DIRLIGHT" + lightIndex;
  25007. }
  25008. if (defines[type] === undefined) {
  25009. needRebuild = true;
  25010. }
  25011. defines[type] = true;
  25012. // Specular
  25013. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  25014. defines["SPECULARTERM"] = true;
  25015. }
  25016. // Shadows
  25017. if (scene.shadowsEnabled) {
  25018. var shadowGenerator = light.getShadowGenerator();
  25019. if (mesh && mesh.receiveShadows && shadowGenerator) {
  25020. if (defines["SHADOW" + lightIndex] === undefined) {
  25021. needRebuild = true;
  25022. }
  25023. defines["SHADOW" + lightIndex] = true;
  25024. defines["SHADOWS"] = true;
  25025. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  25026. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  25027. needRebuild = true;
  25028. }
  25029. defines["SHADOWVSM" + lightIndex] = true;
  25030. }
  25031. if (shadowGenerator.usePoissonSampling) {
  25032. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  25033. needRebuild = true;
  25034. }
  25035. defines["SHADOWPCF" + lightIndex] = true;
  25036. }
  25037. needShadows = true;
  25038. }
  25039. }
  25040. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25041. lightmapMode = true;
  25042. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  25043. needRebuild = true;
  25044. }
  25045. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  25046. needRebuild = true;
  25047. }
  25048. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25049. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  25050. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  25051. }
  25052. }
  25053. lightIndex++;
  25054. if (lightIndex === maxSimultaneousLights)
  25055. break;
  25056. }
  25057. var caps = scene.getEngine().getCaps();
  25058. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  25059. if (defines["SHADOWFULLFLOAT"] === undefined) {
  25060. needRebuild = true;
  25061. }
  25062. defines["SHADOWFULLFLOAT"] = true;
  25063. }
  25064. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  25065. needRebuild = true;
  25066. }
  25067. if (lightmapMode) {
  25068. defines["LIGHTMAPEXCLUDED"] = true;
  25069. }
  25070. if (needRebuild) {
  25071. defines.rebuild();
  25072. }
  25073. return needNormals;
  25074. };
  25075. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  25076. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25077. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25078. if (!defines["LIGHT" + lightIndex]) {
  25079. break;
  25080. }
  25081. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  25082. samplersList.push("shadowSampler" + lightIndex);
  25083. }
  25084. };
  25085. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25086. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25087. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25088. if (!defines["LIGHT" + lightIndex]) {
  25089. break;
  25090. }
  25091. if (lightIndex > 0) {
  25092. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25093. }
  25094. if (defines["SHADOW" + lightIndex]) {
  25095. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25096. }
  25097. if (defines["SHADOWPCF" + lightIndex]) {
  25098. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25099. }
  25100. if (defines["SHADOWVSM" + lightIndex]) {
  25101. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  25102. }
  25103. }
  25104. };
  25105. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25106. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25107. fallbacks.addCPUSkinningFallback(0, mesh);
  25108. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25109. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25110. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25111. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25112. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25113. }
  25114. }
  25115. };
  25116. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25117. if (defines["INSTANCES"]) {
  25118. attribs.push("world0");
  25119. attribs.push("world1");
  25120. attribs.push("world2");
  25121. attribs.push("world3");
  25122. }
  25123. };
  25124. // Bindings
  25125. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  25126. var shadowGenerator = light.getShadowGenerator();
  25127. if (mesh.receiveShadows && shadowGenerator) {
  25128. if (!light.needCube()) {
  25129. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  25130. }
  25131. else {
  25132. if (!depthValuesAlreadySet) {
  25133. depthValuesAlreadySet = true;
  25134. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  25135. }
  25136. }
  25137. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  25138. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  25139. }
  25140. return depthValuesAlreadySet;
  25141. };
  25142. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25143. if (light instanceof BABYLON.PointLight) {
  25144. // Point Light
  25145. light.transferToEffect(effect, "vLightData" + lightIndex);
  25146. }
  25147. else if (light instanceof BABYLON.DirectionalLight) {
  25148. // Directional Light
  25149. light.transferToEffect(effect, "vLightData" + lightIndex);
  25150. }
  25151. else if (light instanceof BABYLON.SpotLight) {
  25152. // Spot Light
  25153. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  25154. }
  25155. else if (light instanceof BABYLON.HemisphericLight) {
  25156. // Hemispheric Light
  25157. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  25158. }
  25159. };
  25160. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  25161. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25162. var lightIndex = 0;
  25163. var depthValuesAlreadySet = false;
  25164. for (var index = 0; index < scene.lights.length; index++) {
  25165. var light = scene.lights[index];
  25166. if (!light.isEnabled()) {
  25167. continue;
  25168. }
  25169. if (!light.canAffectMesh(mesh)) {
  25170. continue;
  25171. }
  25172. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25173. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  25174. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  25175. if (defines["SPECULARTERM"]) {
  25176. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  25177. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  25178. }
  25179. // Shadows
  25180. if (scene.shadowsEnabled) {
  25181. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  25182. }
  25183. lightIndex++;
  25184. if (lightIndex === maxSimultaneousLights)
  25185. break;
  25186. }
  25187. };
  25188. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25189. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25190. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25191. effect.setColor3("vFogColor", scene.fogColor);
  25192. }
  25193. };
  25194. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25195. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25196. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25197. if (matrices) {
  25198. effect.setMatrices("mBones", matrices);
  25199. }
  25200. }
  25201. };
  25202. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25203. if (defines["LOGARITHMICDEPTH"]) {
  25204. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25205. }
  25206. };
  25207. MaterialHelper.BindClipPlane = function (effect, scene) {
  25208. if (scene.clipPlane) {
  25209. var clipPlane = scene.clipPlane;
  25210. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25211. }
  25212. };
  25213. return MaterialHelper;
  25214. }());
  25215. BABYLON.MaterialHelper = MaterialHelper;
  25216. })(BABYLON || (BABYLON = {}));
  25217. var BABYLON;
  25218. (function (BABYLON) {
  25219. var FresnelParameters = (function () {
  25220. function FresnelParameters() {
  25221. this.isEnabled = true;
  25222. this.leftColor = BABYLON.Color3.White();
  25223. this.rightColor = BABYLON.Color3.Black();
  25224. this.bias = 0;
  25225. this.power = 1;
  25226. }
  25227. FresnelParameters.prototype.clone = function () {
  25228. var newFresnelParameters = new FresnelParameters();
  25229. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25230. return newFresnelParameters;
  25231. };
  25232. FresnelParameters.prototype.serialize = function () {
  25233. var serializationObject = {};
  25234. serializationObject.isEnabled = this.isEnabled;
  25235. serializationObject.leftColor = this.leftColor;
  25236. serializationObject.rightColor = this.rightColor;
  25237. serializationObject.bias = this.bias;
  25238. serializationObject.power = this.power;
  25239. return serializationObject;
  25240. };
  25241. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25242. var fresnelParameters = new FresnelParameters();
  25243. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25244. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25245. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25246. fresnelParameters.bias = parsedFresnelParameters.bias;
  25247. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25248. return fresnelParameters;
  25249. };
  25250. return FresnelParameters;
  25251. }());
  25252. BABYLON.FresnelParameters = FresnelParameters;
  25253. })(BABYLON || (BABYLON = {}));
  25254. var BABYLON;
  25255. (function (BABYLON) {
  25256. var MaterialDefines = (function () {
  25257. function MaterialDefines() {
  25258. }
  25259. MaterialDefines.prototype.rebuild = function () {
  25260. if (this._keys) {
  25261. delete this._keys;
  25262. }
  25263. this._keys = Object.keys(this);
  25264. };
  25265. MaterialDefines.prototype.isEqual = function (other) {
  25266. if (this._keys.length !== other._keys.length) {
  25267. return false;
  25268. }
  25269. for (var index = 0; index < this._keys.length; index++) {
  25270. var prop = this._keys[index];
  25271. if (this[prop] !== other[prop]) {
  25272. return false;
  25273. }
  25274. }
  25275. return true;
  25276. };
  25277. MaterialDefines.prototype.cloneTo = function (other) {
  25278. if (this._keys.length !== other._keys.length) {
  25279. other._keys = this._keys.slice(0);
  25280. }
  25281. for (var index = 0; index < this._keys.length; index++) {
  25282. var prop = this._keys[index];
  25283. other[prop] = this[prop];
  25284. }
  25285. };
  25286. MaterialDefines.prototype.reset = function () {
  25287. for (var index = 0; index < this._keys.length; index++) {
  25288. var prop = this._keys[index];
  25289. if (typeof (this[prop]) === "number") {
  25290. this[prop] = 0;
  25291. }
  25292. else {
  25293. this[prop] = false;
  25294. }
  25295. }
  25296. };
  25297. MaterialDefines.prototype.toString = function () {
  25298. var result = "";
  25299. for (var index = 0; index < this._keys.length; index++) {
  25300. var prop = this._keys[index];
  25301. if (typeof (this[prop]) === "number") {
  25302. result += "#define " + prop + " " + this[prop] + "\n";
  25303. }
  25304. else if (this[prop]) {
  25305. result += "#define " + prop + "\n";
  25306. }
  25307. }
  25308. return result;
  25309. };
  25310. return MaterialDefines;
  25311. }());
  25312. BABYLON.MaterialDefines = MaterialDefines;
  25313. var Material = (function () {
  25314. function Material(name, scene, doNotAdd) {
  25315. this.name = name;
  25316. this.checkReadyOnEveryCall = false;
  25317. this.checkReadyOnlyOnce = false;
  25318. this.state = "";
  25319. this.alpha = 1.0;
  25320. this.backFaceCulling = true;
  25321. /**
  25322. * An event triggered when the material is disposed.
  25323. * @type {BABYLON.Observable}
  25324. */
  25325. this.onDisposeObservable = new BABYLON.Observable();
  25326. /**
  25327. * An event triggered when the material is bound.
  25328. * @type {BABYLON.Observable}
  25329. */
  25330. this.onBindObservable = new BABYLON.Observable();
  25331. /**
  25332. * An event triggered when the material is unbound.
  25333. * @type {BABYLON.Observable}
  25334. */
  25335. this.onUnBindObservable = new BABYLON.Observable();
  25336. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25337. this.disableDepthWrite = false;
  25338. this.fogEnabled = true;
  25339. this.pointSize = 1.0;
  25340. this.zOffset = 0;
  25341. this._wasPreviouslyReady = false;
  25342. this._fillMode = Material.TriangleFillMode;
  25343. this.id = name;
  25344. this._scene = scene;
  25345. if (scene.useRightHandedSystem) {
  25346. this.sideOrientation = Material.ClockWiseSideOrientation;
  25347. }
  25348. else {
  25349. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25350. }
  25351. if (!doNotAdd) {
  25352. scene.materials.push(this);
  25353. }
  25354. }
  25355. Object.defineProperty(Material, "TriangleFillMode", {
  25356. get: function () {
  25357. return Material._TriangleFillMode;
  25358. },
  25359. enumerable: true,
  25360. configurable: true
  25361. });
  25362. Object.defineProperty(Material, "WireFrameFillMode", {
  25363. get: function () {
  25364. return Material._WireFrameFillMode;
  25365. },
  25366. enumerable: true,
  25367. configurable: true
  25368. });
  25369. Object.defineProperty(Material, "PointFillMode", {
  25370. get: function () {
  25371. return Material._PointFillMode;
  25372. },
  25373. enumerable: true,
  25374. configurable: true
  25375. });
  25376. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25377. get: function () {
  25378. return Material._ClockWiseSideOrientation;
  25379. },
  25380. enumerable: true,
  25381. configurable: true
  25382. });
  25383. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25384. get: function () {
  25385. return Material._CounterClockWiseSideOrientation;
  25386. },
  25387. enumerable: true,
  25388. configurable: true
  25389. });
  25390. Object.defineProperty(Material.prototype, "onDispose", {
  25391. set: function (callback) {
  25392. if (this._onDisposeObserver) {
  25393. this.onDisposeObservable.remove(this._onDisposeObserver);
  25394. }
  25395. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25396. },
  25397. enumerable: true,
  25398. configurable: true
  25399. });
  25400. Object.defineProperty(Material.prototype, "onBind", {
  25401. set: function (callback) {
  25402. if (this._onBindObserver) {
  25403. this.onBindObservable.remove(this._onBindObserver);
  25404. }
  25405. this._onBindObserver = this.onBindObservable.add(callback);
  25406. },
  25407. enumerable: true,
  25408. configurable: true
  25409. });
  25410. Object.defineProperty(Material.prototype, "wireframe", {
  25411. get: function () {
  25412. return this._fillMode === Material.WireFrameFillMode;
  25413. },
  25414. set: function (value) {
  25415. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25416. },
  25417. enumerable: true,
  25418. configurable: true
  25419. });
  25420. Object.defineProperty(Material.prototype, "pointsCloud", {
  25421. get: function () {
  25422. return this._fillMode === Material.PointFillMode;
  25423. },
  25424. set: function (value) {
  25425. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25426. },
  25427. enumerable: true,
  25428. configurable: true
  25429. });
  25430. Object.defineProperty(Material.prototype, "fillMode", {
  25431. get: function () {
  25432. return this._fillMode;
  25433. },
  25434. set: function (value) {
  25435. this._fillMode = value;
  25436. },
  25437. enumerable: true,
  25438. configurable: true
  25439. });
  25440. /**
  25441. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25442. * subclasses should override adding information pertainent to themselves
  25443. */
  25444. Material.prototype.toString = function (fullDetails) {
  25445. var ret = "Name: " + this.name;
  25446. if (fullDetails) {
  25447. }
  25448. return ret;
  25449. };
  25450. Object.defineProperty(Material.prototype, "isFrozen", {
  25451. get: function () {
  25452. return this.checkReadyOnlyOnce;
  25453. },
  25454. enumerable: true,
  25455. configurable: true
  25456. });
  25457. Material.prototype.freeze = function () {
  25458. this.checkReadyOnlyOnce = true;
  25459. };
  25460. Material.prototype.unfreeze = function () {
  25461. this.checkReadyOnlyOnce = false;
  25462. };
  25463. Material.prototype.isReady = function (mesh, useInstances) {
  25464. return true;
  25465. };
  25466. Material.prototype.getEffect = function () {
  25467. return this._effect;
  25468. };
  25469. Material.prototype.getScene = function () {
  25470. return this._scene;
  25471. };
  25472. Material.prototype.needAlphaBlending = function () {
  25473. return (this.alpha < 1.0);
  25474. };
  25475. Material.prototype.needAlphaTesting = function () {
  25476. return false;
  25477. };
  25478. Material.prototype.getAlphaTestTexture = function () {
  25479. return null;
  25480. };
  25481. Material.prototype.markDirty = function () {
  25482. this._wasPreviouslyReady = false;
  25483. };
  25484. Material.prototype._preBind = function () {
  25485. var engine = this._scene.getEngine();
  25486. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25487. engine.enableEffect(this._effect);
  25488. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25489. };
  25490. Material.prototype.bind = function (world, mesh) {
  25491. this._scene._cachedMaterial = this;
  25492. this.onBindObservable.notifyObservers(mesh);
  25493. if (this.disableDepthWrite) {
  25494. var engine = this._scene.getEngine();
  25495. this._cachedDepthWriteState = engine.getDepthWrite();
  25496. engine.setDepthWrite(false);
  25497. }
  25498. };
  25499. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25500. };
  25501. Material.prototype.unbind = function () {
  25502. this.onUnBindObservable.notifyObservers(this);
  25503. if (this.disableDepthWrite) {
  25504. var engine = this._scene.getEngine();
  25505. engine.setDepthWrite(this._cachedDepthWriteState);
  25506. }
  25507. };
  25508. Material.prototype.clone = function (name) {
  25509. return null;
  25510. };
  25511. Material.prototype.getBindedMeshes = function () {
  25512. var result = new Array();
  25513. for (var index = 0; index < this._scene.meshes.length; index++) {
  25514. var mesh = this._scene.meshes[index];
  25515. if (mesh.material === this) {
  25516. result.push(mesh);
  25517. }
  25518. }
  25519. return result;
  25520. };
  25521. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25522. // Animations
  25523. this.getScene().stopAnimation(this);
  25524. // Remove from scene
  25525. var index = this._scene.materials.indexOf(this);
  25526. if (index >= 0) {
  25527. this._scene.materials.splice(index, 1);
  25528. }
  25529. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25530. if (forceDisposeEffect && this._effect) {
  25531. this._scene.getEngine()._releaseEffect(this._effect);
  25532. this._effect = null;
  25533. }
  25534. // Remove from meshes
  25535. for (index = 0; index < this._scene.meshes.length; index++) {
  25536. var mesh = this._scene.meshes[index];
  25537. if (mesh.material === this) {
  25538. mesh.material = null;
  25539. }
  25540. }
  25541. // Callback
  25542. this.onDisposeObservable.notifyObservers(this);
  25543. this.onDisposeObservable.clear();
  25544. this.onBindObservable.clear();
  25545. this.onUnBindObservable.clear();
  25546. };
  25547. Material.prototype.serialize = function () {
  25548. return BABYLON.SerializationHelper.Serialize(this);
  25549. };
  25550. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25551. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25552. multiMaterial.id = parsedMultiMaterial.id;
  25553. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25554. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25555. var subMatId = parsedMultiMaterial.materials[matIndex];
  25556. if (subMatId) {
  25557. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25558. }
  25559. else {
  25560. multiMaterial.subMaterials.push(null);
  25561. }
  25562. }
  25563. return multiMaterial;
  25564. };
  25565. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25566. if (!parsedMaterial.customType) {
  25567. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25568. }
  25569. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25570. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25571. ;
  25572. };
  25573. Material._TriangleFillMode = 0;
  25574. Material._WireFrameFillMode = 1;
  25575. Material._PointFillMode = 2;
  25576. Material._ClockWiseSideOrientation = 0;
  25577. Material._CounterClockWiseSideOrientation = 1;
  25578. __decorate([
  25579. BABYLON.serialize()
  25580. ], Material.prototype, "id", void 0);
  25581. __decorate([
  25582. BABYLON.serialize()
  25583. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25584. __decorate([
  25585. BABYLON.serialize()
  25586. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25587. __decorate([
  25588. BABYLON.serialize()
  25589. ], Material.prototype, "state", void 0);
  25590. __decorate([
  25591. BABYLON.serialize()
  25592. ], Material.prototype, "alpha", void 0);
  25593. __decorate([
  25594. BABYLON.serialize()
  25595. ], Material.prototype, "backFaceCulling", void 0);
  25596. __decorate([
  25597. BABYLON.serialize()
  25598. ], Material.prototype, "sideOrientation", void 0);
  25599. __decorate([
  25600. BABYLON.serialize()
  25601. ], Material.prototype, "alphaMode", void 0);
  25602. __decorate([
  25603. BABYLON.serialize()
  25604. ], Material.prototype, "disableDepthWrite", void 0);
  25605. __decorate([
  25606. BABYLON.serialize()
  25607. ], Material.prototype, "fogEnabled", void 0);
  25608. __decorate([
  25609. BABYLON.serialize()
  25610. ], Material.prototype, "pointSize", void 0);
  25611. __decorate([
  25612. BABYLON.serialize()
  25613. ], Material.prototype, "zOffset", void 0);
  25614. __decorate([
  25615. BABYLON.serialize()
  25616. ], Material.prototype, "wireframe", null);
  25617. __decorate([
  25618. BABYLON.serialize()
  25619. ], Material.prototype, "pointsCloud", null);
  25620. __decorate([
  25621. BABYLON.serialize()
  25622. ], Material.prototype, "fillMode", null);
  25623. return Material;
  25624. }());
  25625. BABYLON.Material = Material;
  25626. })(BABYLON || (BABYLON = {}));
  25627. var BABYLON;
  25628. (function (BABYLON) {
  25629. var StandardMaterialDefines = (function (_super) {
  25630. __extends(StandardMaterialDefines, _super);
  25631. function StandardMaterialDefines() {
  25632. _super.call(this);
  25633. this.DIFFUSE = false;
  25634. this.AMBIENT = false;
  25635. this.OPACITY = false;
  25636. this.OPACITYRGB = false;
  25637. this.REFLECTION = false;
  25638. this.EMISSIVE = false;
  25639. this.SPECULAR = false;
  25640. this.BUMP = false;
  25641. this.PARALLAX = false;
  25642. this.PARALLAXOCCLUSION = false;
  25643. this.SPECULAROVERALPHA = false;
  25644. this.CLIPPLANE = false;
  25645. this.ALPHATEST = false;
  25646. this.ALPHAFROMDIFFUSE = false;
  25647. this.POINTSIZE = false;
  25648. this.FOG = false;
  25649. this.SPECULARTERM = false;
  25650. this.DIFFUSEFRESNEL = false;
  25651. this.OPACITYFRESNEL = false;
  25652. this.REFLECTIONFRESNEL = false;
  25653. this.REFRACTIONFRESNEL = false;
  25654. this.EMISSIVEFRESNEL = false;
  25655. this.FRESNEL = false;
  25656. this.NORMAL = false;
  25657. this.UV1 = false;
  25658. this.UV2 = false;
  25659. this.VERTEXCOLOR = false;
  25660. this.VERTEXALPHA = false;
  25661. this.NUM_BONE_INFLUENCERS = 0;
  25662. this.BonesPerMesh = 0;
  25663. this.INSTANCES = false;
  25664. this.GLOSSINESS = false;
  25665. this.ROUGHNESS = false;
  25666. this.EMISSIVEASILLUMINATION = false;
  25667. this.LINKEMISSIVEWITHDIFFUSE = false;
  25668. this.REFLECTIONFRESNELFROMSPECULAR = false;
  25669. this.LIGHTMAP = false;
  25670. this.USELIGHTMAPASSHADOWMAP = false;
  25671. this.REFLECTIONMAP_3D = false;
  25672. this.REFLECTIONMAP_SPHERICAL = false;
  25673. this.REFLECTIONMAP_PLANAR = false;
  25674. this.REFLECTIONMAP_CUBIC = false;
  25675. this.REFLECTIONMAP_PROJECTION = false;
  25676. this.REFLECTIONMAP_SKYBOX = false;
  25677. this.REFLECTIONMAP_EXPLICIT = false;
  25678. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  25679. this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  25680. this.INVERTCUBICMAP = false;
  25681. this.LOGARITHMICDEPTH = false;
  25682. this.REFRACTION = false;
  25683. this.REFRACTIONMAP_3D = false;
  25684. this.REFLECTIONOVERALPHA = false;
  25685. this.INVERTNORMALMAPX = false;
  25686. this.INVERTNORMALMAPY = false;
  25687. this.SHADOWFULLFLOAT = false;
  25688. this.CAMERACOLORGRADING = false;
  25689. this.CAMERACOLORCURVES = false;
  25690. this.rebuild();
  25691. }
  25692. return StandardMaterialDefines;
  25693. }(BABYLON.MaterialDefines));
  25694. var StandardMaterial = (function (_super) {
  25695. __extends(StandardMaterial, _super);
  25696. function StandardMaterial(name, scene) {
  25697. var _this = this;
  25698. _super.call(this, name, scene);
  25699. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25700. this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  25701. this.specularColor = new BABYLON.Color3(1, 1, 1);
  25702. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  25703. this.specularPower = 64;
  25704. this.useAlphaFromDiffuseTexture = false;
  25705. this.useEmissiveAsIllumination = false;
  25706. this.linkEmissiveWithDiffuse = false;
  25707. this.useReflectionFresnelFromSpecular = false;
  25708. this.useSpecularOverAlpha = false;
  25709. this.useReflectionOverAlpha = false;
  25710. this.disableLighting = false;
  25711. this.useParallax = false;
  25712. this.useParallaxOcclusion = false;
  25713. this.parallaxScaleBias = 0.05;
  25714. this.roughness = 0;
  25715. this.indexOfRefraction = 0.98;
  25716. this.invertRefractionY = true;
  25717. this.useLightmapAsShadowmap = false;
  25718. this.useGlossinessFromSpecularMapAlpha = false;
  25719. this.maxSimultaneousLights = 4;
  25720. /**
  25721. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  25722. */
  25723. this.invertNormalMapX = false;
  25724. /**
  25725. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  25726. */
  25727. this.invertNormalMapY = false;
  25728. /**
  25729. * Color Grading 2D Lookup Texture.
  25730. * This allows special effects like sepia, black and white to sixties rendering style.
  25731. */
  25732. this.cameraColorGradingTexture = null;
  25733. /**
  25734. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  25735. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  25736. * 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;
  25737. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  25738. */
  25739. this.cameraColorCurves = null;
  25740. this._renderTargets = new BABYLON.SmartArray(16);
  25741. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  25742. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  25743. this._defines = new StandardMaterialDefines();
  25744. this._cachedDefines = new StandardMaterialDefines();
  25745. this._cachedDefines.BonesPerMesh = -1;
  25746. this.getRenderTargetTextures = function () {
  25747. _this._renderTargets.reset();
  25748. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  25749. _this._renderTargets.push(_this.reflectionTexture);
  25750. }
  25751. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  25752. _this._renderTargets.push(_this.refractionTexture);
  25753. }
  25754. return _this._renderTargets;
  25755. };
  25756. }
  25757. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  25758. get: function () {
  25759. return this._useLogarithmicDepth;
  25760. },
  25761. set: function (value) {
  25762. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  25763. },
  25764. enumerable: true,
  25765. configurable: true
  25766. });
  25767. StandardMaterial.prototype.needAlphaBlending = function () {
  25768. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  25769. };
  25770. StandardMaterial.prototype.needAlphaTesting = function () {
  25771. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  25772. };
  25773. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  25774. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  25775. };
  25776. StandardMaterial.prototype.getAlphaTestTexture = function () {
  25777. return this.diffuseTexture;
  25778. };
  25779. // Methods
  25780. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  25781. if (!mesh) {
  25782. return true;
  25783. }
  25784. if (this._defines.INSTANCES !== useInstances) {
  25785. return false;
  25786. }
  25787. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  25788. return true;
  25789. }
  25790. return false;
  25791. };
  25792. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  25793. if (this.isFrozen) {
  25794. if (this._wasPreviouslyReady) {
  25795. return true;
  25796. }
  25797. }
  25798. var scene = this.getScene();
  25799. if (!this.checkReadyOnEveryCall) {
  25800. if (this._renderId === scene.getRenderId()) {
  25801. if (this._checkCache(scene, mesh, useInstances)) {
  25802. return true;
  25803. }
  25804. }
  25805. }
  25806. var engine = scene.getEngine();
  25807. var needNormals = false;
  25808. var needUVs = false;
  25809. this._defines.reset();
  25810. // Textures
  25811. if (scene.texturesEnabled) {
  25812. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  25813. if (!this.diffuseTexture.isReady()) {
  25814. return false;
  25815. }
  25816. else {
  25817. needUVs = true;
  25818. this._defines.DIFFUSE = true;
  25819. }
  25820. }
  25821. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  25822. if (!this.ambientTexture.isReady()) {
  25823. return false;
  25824. }
  25825. else {
  25826. needUVs = true;
  25827. this._defines.AMBIENT = true;
  25828. }
  25829. }
  25830. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  25831. if (!this.opacityTexture.isReady()) {
  25832. return false;
  25833. }
  25834. else {
  25835. needUVs = true;
  25836. this._defines.OPACITY = true;
  25837. if (this.opacityTexture.getAlphaFromRGB) {
  25838. this._defines.OPACITYRGB = true;
  25839. }
  25840. }
  25841. }
  25842. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  25843. if (!this.reflectionTexture.isReady()) {
  25844. return false;
  25845. }
  25846. else {
  25847. needNormals = true;
  25848. this._defines.REFLECTION = true;
  25849. if (this.roughness > 0) {
  25850. this._defines.ROUGHNESS = true;
  25851. }
  25852. if (this.useReflectionOverAlpha) {
  25853. this._defines.REFLECTIONOVERALPHA = true;
  25854. }
  25855. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  25856. this._defines.INVERTCUBICMAP = true;
  25857. }
  25858. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  25859. switch (this.reflectionTexture.coordinatesMode) {
  25860. case BABYLON.Texture.CUBIC_MODE:
  25861. case BABYLON.Texture.INVCUBIC_MODE:
  25862. this._defines.REFLECTIONMAP_CUBIC = true;
  25863. break;
  25864. case BABYLON.Texture.EXPLICIT_MODE:
  25865. this._defines.REFLECTIONMAP_EXPLICIT = true;
  25866. break;
  25867. case BABYLON.Texture.PLANAR_MODE:
  25868. this._defines.REFLECTIONMAP_PLANAR = true;
  25869. break;
  25870. case BABYLON.Texture.PROJECTION_MODE:
  25871. this._defines.REFLECTIONMAP_PROJECTION = true;
  25872. break;
  25873. case BABYLON.Texture.SKYBOX_MODE:
  25874. this._defines.REFLECTIONMAP_SKYBOX = true;
  25875. break;
  25876. case BABYLON.Texture.SPHERICAL_MODE:
  25877. this._defines.REFLECTIONMAP_SPHERICAL = true;
  25878. break;
  25879. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  25880. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  25881. break;
  25882. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  25883. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  25884. break;
  25885. }
  25886. }
  25887. }
  25888. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  25889. if (!this.emissiveTexture.isReady()) {
  25890. return false;
  25891. }
  25892. else {
  25893. needUVs = true;
  25894. this._defines.EMISSIVE = true;
  25895. }
  25896. }
  25897. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  25898. if (!this.lightmapTexture.isReady()) {
  25899. return false;
  25900. }
  25901. else {
  25902. needUVs = true;
  25903. this._defines.LIGHTMAP = true;
  25904. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  25905. }
  25906. }
  25907. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  25908. if (!this.specularTexture.isReady()) {
  25909. return false;
  25910. }
  25911. else {
  25912. needUVs = true;
  25913. this._defines.SPECULAR = true;
  25914. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  25915. }
  25916. }
  25917. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  25918. if (!this.bumpTexture.isReady()) {
  25919. return false;
  25920. }
  25921. else {
  25922. needUVs = true;
  25923. this._defines.BUMP = true;
  25924. if (this.useParallax) {
  25925. this._defines.PARALLAX = true;
  25926. if (this.useParallaxOcclusion) {
  25927. this._defines.PARALLAXOCCLUSION = true;
  25928. }
  25929. }
  25930. if (this.invertNormalMapX) {
  25931. this._defines.INVERTNORMALMAPX = true;
  25932. }
  25933. if (this.invertNormalMapY) {
  25934. this._defines.INVERTNORMALMAPY = true;
  25935. }
  25936. }
  25937. }
  25938. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  25939. if (!this.refractionTexture.isReady()) {
  25940. return false;
  25941. }
  25942. else {
  25943. needUVs = true;
  25944. this._defines.REFRACTION = true;
  25945. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  25946. }
  25947. }
  25948. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  25949. if (!this.cameraColorGradingTexture.isReady()) {
  25950. return false;
  25951. }
  25952. else {
  25953. this._defines.CAMERACOLORGRADING = true;
  25954. }
  25955. }
  25956. }
  25957. // Effect
  25958. if (scene.clipPlane) {
  25959. this._defines.CLIPPLANE = true;
  25960. }
  25961. if (engine.getAlphaTesting()) {
  25962. this._defines.ALPHATEST = true;
  25963. }
  25964. if (this._shouldUseAlphaFromDiffuseTexture()) {
  25965. this._defines.ALPHAFROMDIFFUSE = true;
  25966. }
  25967. if (this.useEmissiveAsIllumination) {
  25968. this._defines.EMISSIVEASILLUMINATION = true;
  25969. }
  25970. if (this.linkEmissiveWithDiffuse) {
  25971. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  25972. }
  25973. if (this.useLogarithmicDepth) {
  25974. this._defines.LOGARITHMICDEPTH = true;
  25975. }
  25976. if (this.cameraColorCurves) {
  25977. this._defines.CAMERACOLORCURVES = true;
  25978. }
  25979. // Point size
  25980. if (this.pointsCloud || scene.forcePointsCloud) {
  25981. this._defines.POINTSIZE = true;
  25982. }
  25983. // Fog
  25984. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  25985. this._defines.FOG = true;
  25986. }
  25987. if (scene.lightsEnabled && !this.disableLighting) {
  25988. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  25989. }
  25990. if (StandardMaterial.FresnelEnabled) {
  25991. // Fresnel
  25992. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  25993. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  25994. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  25995. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  25996. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  25997. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  25998. this._defines.DIFFUSEFRESNEL = true;
  25999. }
  26000. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26001. this._defines.OPACITYFRESNEL = true;
  26002. }
  26003. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26004. this._defines.REFLECTIONFRESNEL = true;
  26005. if (this.useReflectionFresnelFromSpecular) {
  26006. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  26007. }
  26008. }
  26009. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26010. this._defines.REFRACTIONFRESNEL = true;
  26011. }
  26012. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26013. this._defines.EMISSIVEFRESNEL = true;
  26014. }
  26015. needNormals = true;
  26016. this._defines.FRESNEL = true;
  26017. }
  26018. }
  26019. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  26020. this._defines.SPECULAROVERALPHA = true;
  26021. }
  26022. // Attribs
  26023. if (mesh) {
  26024. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26025. this._defines.NORMAL = true;
  26026. }
  26027. if (needUVs) {
  26028. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26029. this._defines.UV1 = true;
  26030. }
  26031. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26032. this._defines.UV2 = true;
  26033. }
  26034. }
  26035. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26036. this._defines.VERTEXCOLOR = true;
  26037. if (mesh.hasVertexAlpha) {
  26038. this._defines.VERTEXALPHA = true;
  26039. }
  26040. }
  26041. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  26042. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  26043. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  26044. }
  26045. // Instances
  26046. if (useInstances) {
  26047. this._defines.INSTANCES = true;
  26048. }
  26049. }
  26050. // Get correct effect
  26051. if (!this._defines.isEqual(this._cachedDefines)) {
  26052. this._defines.cloneTo(this._cachedDefines);
  26053. scene.resetCachedMaterial();
  26054. // Fallbacks
  26055. var fallbacks = new BABYLON.EffectFallbacks();
  26056. if (this._defines.REFLECTION) {
  26057. fallbacks.addFallback(0, "REFLECTION");
  26058. }
  26059. if (this._defines.SPECULAR) {
  26060. fallbacks.addFallback(0, "SPECULAR");
  26061. }
  26062. if (this._defines.BUMP) {
  26063. fallbacks.addFallback(0, "BUMP");
  26064. }
  26065. if (this._defines.PARALLAX) {
  26066. fallbacks.addFallback(1, "PARALLAX");
  26067. }
  26068. if (this._defines.PARALLAXOCCLUSION) {
  26069. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26070. }
  26071. if (this._defines.SPECULAROVERALPHA) {
  26072. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26073. }
  26074. if (this._defines.FOG) {
  26075. fallbacks.addFallback(1, "FOG");
  26076. }
  26077. if (this._defines.POINTSIZE) {
  26078. fallbacks.addFallback(0, "POINTSIZE");
  26079. }
  26080. if (this._defines.LOGARITHMICDEPTH) {
  26081. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26082. }
  26083. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  26084. if (this._defines.SPECULARTERM) {
  26085. fallbacks.addFallback(0, "SPECULARTERM");
  26086. }
  26087. if (this._defines.DIFFUSEFRESNEL) {
  26088. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26089. }
  26090. if (this._defines.OPACITYFRESNEL) {
  26091. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26092. }
  26093. if (this._defines.REFLECTIONFRESNEL) {
  26094. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26095. }
  26096. if (this._defines.EMISSIVEFRESNEL) {
  26097. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26098. }
  26099. if (this._defines.FRESNEL) {
  26100. fallbacks.addFallback(4, "FRESNEL");
  26101. }
  26102. //Attributes
  26103. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26104. if (this._defines.NORMAL) {
  26105. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26106. }
  26107. if (this._defines.UV1) {
  26108. attribs.push(BABYLON.VertexBuffer.UVKind);
  26109. }
  26110. if (this._defines.UV2) {
  26111. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26112. }
  26113. if (this._defines.VERTEXCOLOR) {
  26114. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26115. }
  26116. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  26117. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  26118. var shaderName = "default";
  26119. var join = this._defines.toString();
  26120. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26121. "vFogInfos", "vFogColor", "pointSize",
  26122. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26123. "mBones",
  26124. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26125. "depthValues",
  26126. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26127. "logarithmicDepthConstant"
  26128. ];
  26129. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26130. if (this._defines.CAMERACOLORCURVES) {
  26131. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26132. }
  26133. if (this._defines.CAMERACOLORGRADING) {
  26134. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26135. }
  26136. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  26137. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  26138. }
  26139. if (!this._effect.isReady()) {
  26140. return false;
  26141. }
  26142. this._renderId = scene.getRenderId();
  26143. this._wasPreviouslyReady = true;
  26144. if (mesh) {
  26145. if (!mesh._materialDefines) {
  26146. mesh._materialDefines = new StandardMaterialDefines();
  26147. }
  26148. this._defines.cloneTo(mesh._materialDefines);
  26149. }
  26150. return true;
  26151. };
  26152. StandardMaterial.prototype.unbind = function () {
  26153. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  26154. this._effect.setTexture("reflection2DSampler", null);
  26155. }
  26156. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  26157. this._effect.setTexture("refraction2DSampler", null);
  26158. }
  26159. _super.prototype.unbind.call(this);
  26160. };
  26161. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26162. this._effect.setMatrix("world", world);
  26163. };
  26164. StandardMaterial.prototype.bind = function (world, mesh) {
  26165. var scene = this.getScene();
  26166. // Matrices
  26167. this.bindOnlyWorldMatrix(world);
  26168. // Bones
  26169. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  26170. if (scene.getCachedMaterial() !== this) {
  26171. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26172. if (StandardMaterial.FresnelEnabled) {
  26173. // Fresnel
  26174. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26175. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26176. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26177. }
  26178. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26179. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26180. }
  26181. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26182. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26183. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26184. }
  26185. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26186. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26187. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26188. }
  26189. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26190. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26191. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26192. }
  26193. }
  26194. // Textures
  26195. if (scene.texturesEnabled) {
  26196. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26197. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  26198. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  26199. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  26200. }
  26201. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26202. this._effect.setTexture("ambientSampler", this.ambientTexture);
  26203. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  26204. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  26205. }
  26206. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26207. this._effect.setTexture("opacitySampler", this.opacityTexture);
  26208. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  26209. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  26210. }
  26211. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26212. if (this.reflectionTexture.isCube) {
  26213. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  26214. }
  26215. else {
  26216. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  26217. }
  26218. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  26219. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  26220. }
  26221. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26222. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  26223. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  26224. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  26225. }
  26226. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26227. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26228. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26229. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26230. }
  26231. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26232. this._effect.setTexture("specularSampler", this.specularTexture);
  26233. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26234. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26235. }
  26236. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26237. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26238. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26239. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26240. }
  26241. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26242. var depth = 1.0;
  26243. if (this.refractionTexture.isCube) {
  26244. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26245. }
  26246. else {
  26247. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26248. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26249. if (this.refractionTexture.depth) {
  26250. depth = this.refractionTexture.depth;
  26251. }
  26252. }
  26253. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26254. }
  26255. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26256. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26257. }
  26258. }
  26259. // Clip plane
  26260. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26261. // Point size
  26262. if (this.pointsCloud) {
  26263. this._effect.setFloat("pointSize", this.pointSize);
  26264. }
  26265. // Colors
  26266. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  26267. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  26268. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  26269. if (this._defines.SPECULARTERM) {
  26270. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  26271. }
  26272. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  26273. }
  26274. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  26275. // Diffuse
  26276. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  26277. // Lights
  26278. if (scene.lightsEnabled && !this.disableLighting) {
  26279. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  26280. }
  26281. // View
  26282. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  26283. this._effect.setMatrix("view", scene.getViewMatrix());
  26284. }
  26285. // Fog
  26286. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  26287. // Log. depth
  26288. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  26289. // Color Curves
  26290. if (this.cameraColorCurves) {
  26291. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  26292. }
  26293. }
  26294. _super.prototype.bind.call(this, world, mesh);
  26295. };
  26296. StandardMaterial.prototype.getAnimatables = function () {
  26297. var results = [];
  26298. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  26299. results.push(this.diffuseTexture);
  26300. }
  26301. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  26302. results.push(this.ambientTexture);
  26303. }
  26304. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  26305. results.push(this.opacityTexture);
  26306. }
  26307. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  26308. results.push(this.reflectionTexture);
  26309. }
  26310. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  26311. results.push(this.emissiveTexture);
  26312. }
  26313. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  26314. results.push(this.specularTexture);
  26315. }
  26316. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  26317. results.push(this.bumpTexture);
  26318. }
  26319. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  26320. results.push(this.lightmapTexture);
  26321. }
  26322. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  26323. results.push(this.refractionTexture);
  26324. }
  26325. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  26326. results.push(this.cameraColorGradingTexture);
  26327. }
  26328. return results;
  26329. };
  26330. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26331. if (forceDisposeTextures) {
  26332. if (this.diffuseTexture) {
  26333. this.diffuseTexture.dispose();
  26334. }
  26335. if (this.ambientTexture) {
  26336. this.ambientTexture.dispose();
  26337. }
  26338. if (this.opacityTexture) {
  26339. this.opacityTexture.dispose();
  26340. }
  26341. if (this.reflectionTexture) {
  26342. this.reflectionTexture.dispose();
  26343. }
  26344. if (this.emissiveTexture) {
  26345. this.emissiveTexture.dispose();
  26346. }
  26347. if (this.specularTexture) {
  26348. this.specularTexture.dispose();
  26349. }
  26350. if (this.bumpTexture) {
  26351. this.bumpTexture.dispose();
  26352. }
  26353. if (this.lightmapTexture) {
  26354. this.lightmapTexture.dispose();
  26355. }
  26356. if (this.refractionTexture) {
  26357. this.refractionTexture.dispose();
  26358. }
  26359. if (this.cameraColorGradingTexture) {
  26360. this.cameraColorGradingTexture.dispose();
  26361. }
  26362. }
  26363. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  26364. };
  26365. StandardMaterial.prototype.clone = function (name) {
  26366. var _this = this;
  26367. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  26368. };
  26369. StandardMaterial.prototype.serialize = function () {
  26370. return BABYLON.SerializationHelper.Serialize(this);
  26371. };
  26372. // Statics
  26373. StandardMaterial.Parse = function (source, scene, rootUrl) {
  26374. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  26375. };
  26376. // Flags used to enable or disable a type of texture for all Standard Materials
  26377. StandardMaterial.DiffuseTextureEnabled = true;
  26378. StandardMaterial.AmbientTextureEnabled = true;
  26379. StandardMaterial.OpacityTextureEnabled = true;
  26380. StandardMaterial.ReflectionTextureEnabled = true;
  26381. StandardMaterial.EmissiveTextureEnabled = true;
  26382. StandardMaterial.SpecularTextureEnabled = true;
  26383. StandardMaterial.BumpTextureEnabled = true;
  26384. StandardMaterial.FresnelEnabled = true;
  26385. StandardMaterial.LightmapTextureEnabled = true;
  26386. StandardMaterial.RefractionTextureEnabled = true;
  26387. StandardMaterial.ColorGradingTextureEnabled = true;
  26388. __decorate([
  26389. BABYLON.serializeAsTexture()
  26390. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  26391. __decorate([
  26392. BABYLON.serializeAsTexture()
  26393. ], StandardMaterial.prototype, "ambientTexture", void 0);
  26394. __decorate([
  26395. BABYLON.serializeAsTexture()
  26396. ], StandardMaterial.prototype, "opacityTexture", void 0);
  26397. __decorate([
  26398. BABYLON.serializeAsTexture()
  26399. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  26400. __decorate([
  26401. BABYLON.serializeAsTexture()
  26402. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  26403. __decorate([
  26404. BABYLON.serializeAsTexture()
  26405. ], StandardMaterial.prototype, "specularTexture", void 0);
  26406. __decorate([
  26407. BABYLON.serializeAsTexture()
  26408. ], StandardMaterial.prototype, "bumpTexture", void 0);
  26409. __decorate([
  26410. BABYLON.serializeAsTexture()
  26411. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  26412. __decorate([
  26413. BABYLON.serializeAsTexture()
  26414. ], StandardMaterial.prototype, "refractionTexture", void 0);
  26415. __decorate([
  26416. BABYLON.serializeAsColor3("ambient")
  26417. ], StandardMaterial.prototype, "ambientColor", void 0);
  26418. __decorate([
  26419. BABYLON.serializeAsColor3("diffuse")
  26420. ], StandardMaterial.prototype, "diffuseColor", void 0);
  26421. __decorate([
  26422. BABYLON.serializeAsColor3("specular")
  26423. ], StandardMaterial.prototype, "specularColor", void 0);
  26424. __decorate([
  26425. BABYLON.serializeAsColor3("emissive")
  26426. ], StandardMaterial.prototype, "emissiveColor", void 0);
  26427. __decorate([
  26428. BABYLON.serialize()
  26429. ], StandardMaterial.prototype, "specularPower", void 0);
  26430. __decorate([
  26431. BABYLON.serialize()
  26432. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  26433. __decorate([
  26434. BABYLON.serialize()
  26435. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  26436. __decorate([
  26437. BABYLON.serialize()
  26438. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  26439. __decorate([
  26440. BABYLON.serialize()
  26441. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  26442. __decorate([
  26443. BABYLON.serialize()
  26444. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  26445. __decorate([
  26446. BABYLON.serialize()
  26447. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  26448. __decorate([
  26449. BABYLON.serialize()
  26450. ], StandardMaterial.prototype, "disableLighting", void 0);
  26451. __decorate([
  26452. BABYLON.serialize()
  26453. ], StandardMaterial.prototype, "useParallax", void 0);
  26454. __decorate([
  26455. BABYLON.serialize()
  26456. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  26457. __decorate([
  26458. BABYLON.serialize()
  26459. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  26460. __decorate([
  26461. BABYLON.serialize()
  26462. ], StandardMaterial.prototype, "roughness", void 0);
  26463. __decorate([
  26464. BABYLON.serialize()
  26465. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  26466. __decorate([
  26467. BABYLON.serialize()
  26468. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  26469. __decorate([
  26470. BABYLON.serialize()
  26471. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  26472. __decorate([
  26473. BABYLON.serializeAsFresnelParameters()
  26474. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  26475. __decorate([
  26476. BABYLON.serializeAsFresnelParameters()
  26477. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  26478. __decorate([
  26479. BABYLON.serializeAsFresnelParameters()
  26480. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  26481. __decorate([
  26482. BABYLON.serializeAsFresnelParameters()
  26483. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  26484. __decorate([
  26485. BABYLON.serializeAsFresnelParameters()
  26486. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  26487. __decorate([
  26488. BABYLON.serialize()
  26489. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  26490. __decorate([
  26491. BABYLON.serialize()
  26492. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  26493. __decorate([
  26494. BABYLON.serialize()
  26495. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  26496. __decorate([
  26497. BABYLON.serialize()
  26498. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  26499. __decorate([
  26500. BABYLON.serializeAsTexture()
  26501. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  26502. __decorate([
  26503. BABYLON.serializeAsColorCurves()
  26504. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  26505. __decorate([
  26506. BABYLON.serialize()
  26507. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  26508. return StandardMaterial;
  26509. }(BABYLON.Material));
  26510. BABYLON.StandardMaterial = StandardMaterial;
  26511. })(BABYLON || (BABYLON = {}));
  26512. var BABYLON;
  26513. (function (BABYLON) {
  26514. var MultiMaterial = (function (_super) {
  26515. __extends(MultiMaterial, _super);
  26516. function MultiMaterial(name, scene) {
  26517. _super.call(this, name, scene, true);
  26518. this.subMaterials = new Array();
  26519. scene.multiMaterials.push(this);
  26520. }
  26521. // Properties
  26522. MultiMaterial.prototype.getSubMaterial = function (index) {
  26523. if (index < 0 || index >= this.subMaterials.length) {
  26524. return this.getScene().defaultMaterial;
  26525. }
  26526. return this.subMaterials[index];
  26527. };
  26528. // Methods
  26529. MultiMaterial.prototype.isReady = function (mesh) {
  26530. for (var index = 0; index < this.subMaterials.length; index++) {
  26531. var subMaterial = this.subMaterials[index];
  26532. if (subMaterial) {
  26533. if (!this.subMaterials[index].isReady(mesh)) {
  26534. return false;
  26535. }
  26536. }
  26537. }
  26538. return true;
  26539. };
  26540. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  26541. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  26542. for (var index = 0; index < this.subMaterials.length; index++) {
  26543. var subMaterial = null;
  26544. if (cloneChildren) {
  26545. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  26546. }
  26547. else {
  26548. subMaterial = this.subMaterials[index];
  26549. }
  26550. newMultiMaterial.subMaterials.push(subMaterial);
  26551. }
  26552. return newMultiMaterial;
  26553. };
  26554. MultiMaterial.prototype.serialize = function () {
  26555. var serializationObject = {};
  26556. serializationObject.name = this.name;
  26557. serializationObject.id = this.id;
  26558. serializationObject.tags = BABYLON.Tags.GetTags(this);
  26559. serializationObject.materials = [];
  26560. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  26561. var subMat = this.subMaterials[matIndex];
  26562. if (subMat) {
  26563. serializationObject.materials.push(subMat.id);
  26564. }
  26565. else {
  26566. serializationObject.materials.push(null);
  26567. }
  26568. }
  26569. return serializationObject;
  26570. };
  26571. return MultiMaterial;
  26572. }(BABYLON.Material));
  26573. BABYLON.MultiMaterial = MultiMaterial;
  26574. })(BABYLON || (BABYLON = {}));
  26575. var BABYLON;
  26576. (function (BABYLON) {
  26577. var SceneLoader = (function () {
  26578. function SceneLoader() {
  26579. }
  26580. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  26581. get: function () {
  26582. return 0;
  26583. },
  26584. enumerable: true,
  26585. configurable: true
  26586. });
  26587. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  26588. get: function () {
  26589. return 1;
  26590. },
  26591. enumerable: true,
  26592. configurable: true
  26593. });
  26594. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  26595. get: function () {
  26596. return 2;
  26597. },
  26598. enumerable: true,
  26599. configurable: true
  26600. });
  26601. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  26602. get: function () {
  26603. return 3;
  26604. },
  26605. enumerable: true,
  26606. configurable: true
  26607. });
  26608. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  26609. get: function () {
  26610. return SceneLoader._ForceFullSceneLoadingForIncremental;
  26611. },
  26612. set: function (value) {
  26613. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  26614. },
  26615. enumerable: true,
  26616. configurable: true
  26617. });
  26618. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  26619. get: function () {
  26620. return SceneLoader._ShowLoadingScreen;
  26621. },
  26622. set: function (value) {
  26623. SceneLoader._ShowLoadingScreen = value;
  26624. },
  26625. enumerable: true,
  26626. configurable: true
  26627. });
  26628. Object.defineProperty(SceneLoader, "loggingLevel", {
  26629. get: function () {
  26630. return SceneLoader._loggingLevel;
  26631. },
  26632. set: function (value) {
  26633. SceneLoader._loggingLevel = value;
  26634. },
  26635. enumerable: true,
  26636. configurable: true
  26637. });
  26638. SceneLoader._getDefaultPlugin = function () {
  26639. return SceneLoader._registeredPlugins[".babylon"];
  26640. };
  26641. SceneLoader._getPluginForExtension = function (extension) {
  26642. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  26643. if (registeredPlugin) {
  26644. return registeredPlugin;
  26645. }
  26646. return SceneLoader._getDefaultPlugin();
  26647. };
  26648. SceneLoader._getPluginForFilename = function (sceneFilename) {
  26649. if (sceneFilename.name) {
  26650. sceneFilename = sceneFilename.name;
  26651. }
  26652. var dotPosition = sceneFilename.lastIndexOf(".");
  26653. var queryStringPosition = sceneFilename.indexOf("?");
  26654. if (queryStringPosition === -1) {
  26655. queryStringPosition = sceneFilename.length;
  26656. }
  26657. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  26658. return SceneLoader._getPluginForExtension(extension);
  26659. };
  26660. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  26661. SceneLoader._getDirectLoad = function (sceneFilename) {
  26662. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  26663. return sceneFilename.substr(5);
  26664. }
  26665. return null;
  26666. };
  26667. // Public functions
  26668. SceneLoader.GetPluginForExtension = function (extension) {
  26669. return SceneLoader._getPluginForExtension(extension).plugin;
  26670. };
  26671. SceneLoader.RegisterPlugin = function (plugin) {
  26672. if (typeof plugin.extensions === "string") {
  26673. var extension = plugin.extensions;
  26674. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26675. plugin: plugin,
  26676. isBinary: false
  26677. };
  26678. }
  26679. else {
  26680. var extensions = plugin.extensions;
  26681. Object.keys(extensions).forEach(function (extension) {
  26682. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  26683. plugin: plugin,
  26684. isBinary: extensions[extension].isBinary
  26685. };
  26686. });
  26687. }
  26688. };
  26689. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26690. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26691. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26692. return;
  26693. }
  26694. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26695. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26696. return;
  26697. }
  26698. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26699. var loadingToken = {};
  26700. scene._addPendingData(loadingToken);
  26701. var manifestChecked = function (success) {
  26702. scene.database = database;
  26703. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26704. var plugin = registeredPlugin.plugin;
  26705. var useArrayBuffer = registeredPlugin.isBinary;
  26706. var importMeshFromData = function (data) {
  26707. var meshes = [];
  26708. var particleSystems = [];
  26709. var skeletons = [];
  26710. try {
  26711. if (plugin.importMesh) {
  26712. var syncedPlugin = plugin;
  26713. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  26714. if (onerror) {
  26715. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26716. }
  26717. scene._removePendingData(loadingToken);
  26718. return;
  26719. }
  26720. if (onsuccess) {
  26721. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26722. onsuccess(meshes, particleSystems, skeletons);
  26723. scene._removePendingData(loadingToken);
  26724. }
  26725. }
  26726. else {
  26727. var asyncedPlugin = plugin;
  26728. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  26729. if (onsuccess) {
  26730. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  26731. onsuccess(meshes, particleSystems, skeletons);
  26732. scene._removePendingData(loadingToken);
  26733. }
  26734. }, function () {
  26735. if (onerror) {
  26736. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  26737. }
  26738. scene._removePendingData(loadingToken);
  26739. });
  26740. }
  26741. }
  26742. catch (e) {
  26743. if (onerror) {
  26744. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  26745. }
  26746. scene._removePendingData(loadingToken);
  26747. }
  26748. };
  26749. if (directLoad) {
  26750. importMeshFromData(directLoad);
  26751. return;
  26752. }
  26753. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  26754. importMeshFromData(data);
  26755. }, progressCallBack, database, useArrayBuffer);
  26756. };
  26757. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  26758. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26759. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26760. }
  26761. else {
  26762. // If the scene is a data stream or offline support is not enabled, it's a direct load
  26763. manifestChecked(true);
  26764. }
  26765. };
  26766. /**
  26767. * Load a scene
  26768. * @param rootUrl a string that defines the root url for scene and resources
  26769. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26770. * @param engine is the instance of BABYLON.Engine to use to create the scene
  26771. */
  26772. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  26773. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  26774. };
  26775. /**
  26776. * Append a scene
  26777. * @param rootUrl a string that defines the root url for scene and resources
  26778. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  26779. * @param scene is the instance of BABYLON.Scene to append to
  26780. */
  26781. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  26782. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  26783. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  26784. return;
  26785. }
  26786. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  26787. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  26788. var plugin = registeredPlugin.plugin;
  26789. var useArrayBuffer = registeredPlugin.isBinary;
  26790. var database;
  26791. var loadingToken = {};
  26792. scene._addPendingData(loadingToken);
  26793. if (SceneLoader.ShowLoadingScreen) {
  26794. scene.getEngine().displayLoadingUI();
  26795. }
  26796. var loadSceneFromData = function (data) {
  26797. scene.database = database;
  26798. if (plugin.load) {
  26799. var syncedPlugin = plugin;
  26800. if (!syncedPlugin.load(scene, data, rootUrl)) {
  26801. if (onerror) {
  26802. onerror(scene);
  26803. }
  26804. scene._removePendingData(loadingToken);
  26805. scene.getEngine().hideLoadingUI();
  26806. return;
  26807. }
  26808. if (onsuccess) {
  26809. onsuccess(scene);
  26810. }
  26811. scene._removePendingData(loadingToken);
  26812. }
  26813. else {
  26814. var asyncedPlugin = plugin;
  26815. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  26816. if (onsuccess) {
  26817. onsuccess(scene);
  26818. }
  26819. scene._removePendingData(loadingToken);
  26820. }, function () {
  26821. if (onerror) {
  26822. onerror(scene);
  26823. }
  26824. scene._removePendingData(loadingToken);
  26825. scene.getEngine().hideLoadingUI();
  26826. });
  26827. }
  26828. if (SceneLoader.ShowLoadingScreen) {
  26829. scene.executeWhenReady(function () {
  26830. scene.getEngine().hideLoadingUI();
  26831. });
  26832. }
  26833. };
  26834. var manifestChecked = function (success) {
  26835. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  26836. };
  26837. if (directLoad) {
  26838. loadSceneFromData(directLoad);
  26839. return;
  26840. }
  26841. if (rootUrl.indexOf("file:") === -1) {
  26842. if (scene.getEngine().enableOfflineSupport) {
  26843. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  26844. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  26845. }
  26846. else {
  26847. manifestChecked(true);
  26848. }
  26849. }
  26850. else {
  26851. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  26852. }
  26853. };
  26854. // Flags
  26855. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  26856. SceneLoader._ShowLoadingScreen = true;
  26857. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  26858. // Members
  26859. SceneLoader._registeredPlugins = {};
  26860. return SceneLoader;
  26861. }());
  26862. BABYLON.SceneLoader = SceneLoader;
  26863. ;
  26864. })(BABYLON || (BABYLON = {}));
  26865. var BABYLON;
  26866. (function (BABYLON) {
  26867. var Internals;
  26868. (function (Internals) {
  26869. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  26870. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  26871. var parsedMaterial = parsedData.materials[index];
  26872. if (parsedMaterial.id === id) {
  26873. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  26874. }
  26875. }
  26876. return null;
  26877. };
  26878. var isDescendantOf = function (mesh, names, hierarchyIds) {
  26879. names = (names instanceof Array) ? names : [names];
  26880. for (var i in names) {
  26881. if (mesh.name === names[i]) {
  26882. hierarchyIds.push(mesh.id);
  26883. return true;
  26884. }
  26885. }
  26886. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  26887. hierarchyIds.push(mesh.id);
  26888. return true;
  26889. }
  26890. return false;
  26891. };
  26892. var logOperation = function (operation, producer) {
  26893. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  26894. };
  26895. BABYLON.SceneLoader.RegisterPlugin({
  26896. extensions: ".babylon",
  26897. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  26898. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  26899. // when SceneLoader.debugLogging = true (default), or exception encountered.
  26900. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  26901. // and avoid problems with multiple concurrent .babylon loads.
  26902. var log = "importMesh has failed JSON parse";
  26903. try {
  26904. var parsedData = JSON.parse(data);
  26905. log = "";
  26906. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  26907. var loadedSkeletonsIds = [];
  26908. var loadedMaterialsIds = [];
  26909. var hierarchyIds = [];
  26910. var index;
  26911. var cache;
  26912. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  26913. var parsedMesh = parsedData.meshes[index];
  26914. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  26915. if (meshesNames instanceof Array) {
  26916. // Remove found mesh name from list.
  26917. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  26918. }
  26919. //Geometry?
  26920. if (parsedMesh.geometryId) {
  26921. //does the file contain geometries?
  26922. if (parsedData.geometries) {
  26923. //find the correct geometry and add it to the scene
  26924. var found = false;
  26925. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  26926. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  26927. return;
  26928. }
  26929. else {
  26930. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  26931. if (parsedGeometryData.id === parsedMesh.geometryId) {
  26932. switch (geometryType) {
  26933. case "boxes":
  26934. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  26935. break;
  26936. case "spheres":
  26937. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  26938. break;
  26939. case "cylinders":
  26940. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  26941. break;
  26942. case "toruses":
  26943. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  26944. break;
  26945. case "grounds":
  26946. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  26947. break;
  26948. case "planes":
  26949. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  26950. break;
  26951. case "torusKnots":
  26952. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  26953. break;
  26954. case "vertexData":
  26955. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  26956. break;
  26957. }
  26958. found = true;
  26959. }
  26960. });
  26961. }
  26962. });
  26963. if (!found) {
  26964. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  26965. }
  26966. }
  26967. }
  26968. // Material ?
  26969. if (parsedMesh.materialId) {
  26970. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  26971. if (!materialFound && parsedData.multiMaterials) {
  26972. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  26973. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  26974. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  26975. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  26976. var subMatId = parsedMultiMaterial.materials[matIndex];
  26977. loadedMaterialsIds.push(subMatId);
  26978. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  26979. log += "\n\tMaterial " + mat.toString(fullDetails);
  26980. }
  26981. loadedMaterialsIds.push(parsedMultiMaterial.id);
  26982. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  26983. materialFound = true;
  26984. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  26985. break;
  26986. }
  26987. }
  26988. }
  26989. if (!materialFound) {
  26990. loadedMaterialsIds.push(parsedMesh.materialId);
  26991. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  26992. if (!mat) {
  26993. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  26994. }
  26995. else {
  26996. log += "\n\tMaterial " + mat.toString(fullDetails);
  26997. }
  26998. }
  26999. }
  27000. // Skeleton ?
  27001. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  27002. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  27003. if (!skeletonAlreadyLoaded) {
  27004. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  27005. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  27006. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  27007. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27008. skeletons.push(skeleton);
  27009. loadedSkeletonsIds.push(parsedSkeleton.id);
  27010. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  27011. }
  27012. }
  27013. }
  27014. }
  27015. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27016. meshes.push(mesh);
  27017. log += "\n\tMesh " + mesh.toString(fullDetails);
  27018. }
  27019. }
  27020. // Connecting parents
  27021. var currentMesh;
  27022. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27023. currentMesh = scene.meshes[index];
  27024. if (currentMesh._waitingParentId) {
  27025. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  27026. currentMesh._waitingParentId = undefined;
  27027. }
  27028. }
  27029. // freeze and compute world matrix application
  27030. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27031. currentMesh = scene.meshes[index];
  27032. if (currentMesh._waitingFreezeWorldMatrix) {
  27033. currentMesh.freezeWorldMatrix();
  27034. currentMesh._waitingFreezeWorldMatrix = undefined;
  27035. }
  27036. else {
  27037. currentMesh.computeWorldMatrix(true);
  27038. }
  27039. }
  27040. // Particles
  27041. if (parsedData.particleSystems) {
  27042. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27043. var parsedParticleSystem = parsedData.particleSystems[index];
  27044. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  27045. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  27046. }
  27047. }
  27048. }
  27049. return true;
  27050. }
  27051. catch (err) {
  27052. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  27053. log = null;
  27054. throw err;
  27055. }
  27056. finally {
  27057. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27058. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27059. }
  27060. }
  27061. },
  27062. load: function (scene, data, rootUrl) {
  27063. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27064. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27065. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27066. // and avoid problems with multiple concurrent .babylon loads.
  27067. var log = "importScene has failed JSON parse";
  27068. try {
  27069. var parsedData = JSON.parse(data);
  27070. log = "";
  27071. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27072. // Scene
  27073. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  27074. scene.autoClear = parsedData.autoClear;
  27075. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  27076. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  27077. if (parsedData.gravity) {
  27078. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  27079. }
  27080. // Fog
  27081. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  27082. scene.fogMode = parsedData.fogMode;
  27083. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  27084. scene.fogStart = parsedData.fogStart;
  27085. scene.fogEnd = parsedData.fogEnd;
  27086. scene.fogDensity = parsedData.fogDensity;
  27087. log += "\tFog mode for scene: ";
  27088. switch (scene.fogMode) {
  27089. // getters not compiling, so using hardcoded
  27090. case 1:
  27091. log += "exp\n";
  27092. break;
  27093. case 2:
  27094. log += "exp2\n";
  27095. break;
  27096. case 3:
  27097. log += "linear\n";
  27098. break;
  27099. }
  27100. }
  27101. //Physics
  27102. if (parsedData.physicsEnabled) {
  27103. var physicsPlugin;
  27104. if (parsedData.physicsEngine === "cannon") {
  27105. physicsPlugin = new BABYLON.CannonJSPlugin();
  27106. }
  27107. else if (parsedData.physicsEngine === "oimo") {
  27108. physicsPlugin = new BABYLON.OimoJSPlugin();
  27109. }
  27110. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  27111. //else - default engine, which is currently oimo
  27112. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  27113. scene.enablePhysics(physicsGravity, physicsPlugin);
  27114. }
  27115. //collisions, if defined. otherwise, default is true
  27116. if (parsedData.collisionsEnabled != undefined) {
  27117. scene.collisionsEnabled = parsedData.collisionsEnabled;
  27118. }
  27119. scene.workerCollisions = !!parsedData.workerCollisions;
  27120. var index;
  27121. var cache;
  27122. // Lights
  27123. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  27124. var parsedLight = parsedData.lights[index];
  27125. var light = BABYLON.Light.Parse(parsedLight, scene);
  27126. log += (index === 0 ? "\n\tLights:" : "");
  27127. log += "\n\t\t" + light.toString(fullDetails);
  27128. }
  27129. // Animations
  27130. if (parsedData.animations) {
  27131. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  27132. var parsedAnimation = parsedData.animations[index];
  27133. var animation = BABYLON.Animation.Parse(parsedAnimation);
  27134. scene.animations.push(animation);
  27135. log += (index === 0 ? "\n\tAnimations:" : "");
  27136. log += "\n\t\t" + animation.toString(fullDetails);
  27137. }
  27138. }
  27139. if (parsedData.autoAnimate) {
  27140. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  27141. }
  27142. // Materials
  27143. if (parsedData.materials) {
  27144. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27145. var parsedMaterial = parsedData.materials[index];
  27146. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27147. log += (index === 0 ? "\n\tMaterials:" : "");
  27148. log += "\n\t\t" + mat.toString(fullDetails);
  27149. }
  27150. }
  27151. if (parsedData.multiMaterials) {
  27152. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  27153. var parsedMultiMaterial = parsedData.multiMaterials[index];
  27154. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27155. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  27156. log += "\n\t\t" + mmat.toString(fullDetails);
  27157. }
  27158. }
  27159. // Skeletons
  27160. if (parsedData.skeletons) {
  27161. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  27162. var parsedSkeleton = parsedData.skeletons[index];
  27163. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27164. log += (index === 0 ? "\n\tSkeletons:" : "");
  27165. log += "\n\t\t" + skeleton.toString(fullDetails);
  27166. }
  27167. }
  27168. // Geometries
  27169. var geometries = parsedData.geometries;
  27170. if (geometries) {
  27171. // Boxes
  27172. var boxes = geometries.boxes;
  27173. if (boxes) {
  27174. for (index = 0, cache = boxes.length; index < cache; index++) {
  27175. var parsedBox = boxes[index];
  27176. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  27177. }
  27178. }
  27179. // Spheres
  27180. var spheres = geometries.spheres;
  27181. if (spheres) {
  27182. for (index = 0, cache = spheres.length; index < cache; index++) {
  27183. var parsedSphere = spheres[index];
  27184. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  27185. }
  27186. }
  27187. // Cylinders
  27188. var cylinders = geometries.cylinders;
  27189. if (cylinders) {
  27190. for (index = 0, cache = cylinders.length; index < cache; index++) {
  27191. var parsedCylinder = cylinders[index];
  27192. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  27193. }
  27194. }
  27195. // Toruses
  27196. var toruses = geometries.toruses;
  27197. if (toruses) {
  27198. for (index = 0, cache = toruses.length; index < cache; index++) {
  27199. var parsedTorus = toruses[index];
  27200. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  27201. }
  27202. }
  27203. // Grounds
  27204. var grounds = geometries.grounds;
  27205. if (grounds) {
  27206. for (index = 0, cache = grounds.length; index < cache; index++) {
  27207. var parsedGround = grounds[index];
  27208. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  27209. }
  27210. }
  27211. // Planes
  27212. var planes = geometries.planes;
  27213. if (planes) {
  27214. for (index = 0, cache = planes.length; index < cache; index++) {
  27215. var parsedPlane = planes[index];
  27216. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  27217. }
  27218. }
  27219. // TorusKnots
  27220. var torusKnots = geometries.torusKnots;
  27221. if (torusKnots) {
  27222. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  27223. var parsedTorusKnot = torusKnots[index];
  27224. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  27225. }
  27226. }
  27227. // VertexData
  27228. var vertexData = geometries.vertexData;
  27229. if (vertexData) {
  27230. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27231. var parsedVertexData = vertexData[index];
  27232. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27233. }
  27234. }
  27235. }
  27236. // Meshes
  27237. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27238. var parsedMesh = parsedData.meshes[index];
  27239. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27240. log += (index === 0 ? "\n\tMeshes:" : "");
  27241. log += "\n\t\t" + mesh.toString(fullDetails);
  27242. }
  27243. // Cameras
  27244. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27245. var parsedCamera = parsedData.cameras[index];
  27246. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27247. log += (index === 0 ? "\n\tCameras:" : "");
  27248. log += "\n\t\t" + camera.toString(fullDetails);
  27249. }
  27250. if (parsedData.activeCameraID) {
  27251. scene.setActiveCameraByID(parsedData.activeCameraID);
  27252. }
  27253. // Browsing all the graph to connect the dots
  27254. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  27255. var camera = scene.cameras[index];
  27256. if (camera._waitingParentId) {
  27257. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  27258. camera._waitingParentId = undefined;
  27259. }
  27260. }
  27261. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  27262. var light = scene.lights[index];
  27263. if (light._waitingParentId) {
  27264. light.parent = scene.getLastEntryByID(light._waitingParentId);
  27265. light._waitingParentId = undefined;
  27266. }
  27267. }
  27268. // Sounds
  27269. var loadedSounds = [];
  27270. var loadedSound;
  27271. if (BABYLON.AudioEngine && parsedData.sounds) {
  27272. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  27273. var parsedSound = parsedData.sounds[index];
  27274. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  27275. if (!parsedSound.url)
  27276. parsedSound.url = parsedSound.name;
  27277. if (!loadedSounds[parsedSound.url]) {
  27278. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  27279. loadedSounds[parsedSound.url] = loadedSound;
  27280. }
  27281. else {
  27282. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  27283. }
  27284. }
  27285. else {
  27286. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  27287. }
  27288. }
  27289. }
  27290. loadedSounds = [];
  27291. // Connect parents & children and parse actions
  27292. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27293. var mesh = scene.meshes[index];
  27294. if (mesh._waitingParentId) {
  27295. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  27296. mesh._waitingParentId = undefined;
  27297. }
  27298. if (mesh._waitingActions) {
  27299. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  27300. mesh._waitingActions = undefined;
  27301. }
  27302. }
  27303. // freeze world matrix application
  27304. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27305. var currentMesh = scene.meshes[index];
  27306. if (currentMesh._waitingFreezeWorldMatrix) {
  27307. currentMesh.freezeWorldMatrix();
  27308. currentMesh._waitingFreezeWorldMatrix = undefined;
  27309. }
  27310. else {
  27311. currentMesh.computeWorldMatrix(true);
  27312. }
  27313. }
  27314. // Particles Systems
  27315. if (parsedData.particleSystems) {
  27316. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27317. var parsedParticleSystem = parsedData.particleSystems[index];
  27318. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  27319. }
  27320. }
  27321. // Lens flares
  27322. if (parsedData.lensFlareSystems) {
  27323. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  27324. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  27325. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  27326. }
  27327. }
  27328. // Shadows
  27329. if (parsedData.shadowGenerators) {
  27330. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  27331. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  27332. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  27333. }
  27334. }
  27335. // Actions (scene)
  27336. if (parsedData.actions) {
  27337. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  27338. }
  27339. // Finish
  27340. return true;
  27341. }
  27342. catch (err) {
  27343. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  27344. log = null;
  27345. throw err;
  27346. }
  27347. finally {
  27348. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27349. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27350. }
  27351. }
  27352. }
  27353. });
  27354. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  27355. })(BABYLON || (BABYLON = {}));
  27356. var BABYLON;
  27357. (function (BABYLON) {
  27358. var SpriteManager = (function () {
  27359. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  27360. if (epsilon === void 0) { epsilon = 0.01; }
  27361. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  27362. this.name = name;
  27363. this.sprites = new Array();
  27364. this.renderingGroupId = 0;
  27365. this.layerMask = 0x0FFFFFFF;
  27366. this.fogEnabled = true;
  27367. this.isPickable = false;
  27368. /**
  27369. * An event triggered when the manager is disposed.
  27370. * @type {BABYLON.Observable}
  27371. */
  27372. this.onDisposeObservable = new BABYLON.Observable();
  27373. this._vertexBuffers = {};
  27374. this._capacity = capacity;
  27375. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  27376. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27377. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  27378. if (cellSize.width && cellSize.height) {
  27379. this.cellWidth = cellSize.width;
  27380. this.cellHeight = cellSize.height;
  27381. }
  27382. else if (cellSize !== undefined) {
  27383. this.cellWidth = cellSize;
  27384. this.cellHeight = cellSize;
  27385. }
  27386. else {
  27387. return;
  27388. }
  27389. this._scene = scene;
  27390. this._scene.spriteManagers.push(this);
  27391. var indices = [];
  27392. var index = 0;
  27393. for (var count = 0; count < capacity; count++) {
  27394. indices.push(index);
  27395. indices.push(index + 1);
  27396. indices.push(index + 2);
  27397. indices.push(index);
  27398. indices.push(index + 2);
  27399. indices.push(index + 3);
  27400. index += 4;
  27401. }
  27402. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27403. // VBO
  27404. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  27405. this._vertexData = new Float32Array(capacity * 16 * 4);
  27406. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  27407. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  27408. var options = this._buffer.createVertexBuffer("options", 4, 4);
  27409. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  27410. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  27411. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27412. this._vertexBuffers["options"] = options;
  27413. this._vertexBuffers["cellInfo"] = cellInfo;
  27414. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27415. // Effects
  27416. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  27417. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  27418. }
  27419. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  27420. set: function (callback) {
  27421. if (this._onDisposeObserver) {
  27422. this.onDisposeObservable.remove(this._onDisposeObserver);
  27423. }
  27424. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27425. },
  27426. enumerable: true,
  27427. configurable: true
  27428. });
  27429. Object.defineProperty(SpriteManager.prototype, "texture", {
  27430. get: function () {
  27431. return this._spriteTexture;
  27432. },
  27433. set: function (value) {
  27434. this._spriteTexture = value;
  27435. },
  27436. enumerable: true,
  27437. configurable: true
  27438. });
  27439. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  27440. var arrayOffset = index * 16;
  27441. if (offsetX === 0)
  27442. offsetX = this._epsilon;
  27443. else if (offsetX === 1)
  27444. offsetX = 1 - this._epsilon;
  27445. if (offsetY === 0)
  27446. offsetY = this._epsilon;
  27447. else if (offsetY === 1)
  27448. offsetY = 1 - this._epsilon;
  27449. this._vertexData[arrayOffset] = sprite.position.x;
  27450. this._vertexData[arrayOffset + 1] = sprite.position.y;
  27451. this._vertexData[arrayOffset + 2] = sprite.position.z;
  27452. this._vertexData[arrayOffset + 3] = sprite.angle;
  27453. this._vertexData[arrayOffset + 4] = sprite.width;
  27454. this._vertexData[arrayOffset + 5] = sprite.height;
  27455. this._vertexData[arrayOffset + 6] = offsetX;
  27456. this._vertexData[arrayOffset + 7] = offsetY;
  27457. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  27458. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  27459. var offset = (sprite.cellIndex / rowSize) >> 0;
  27460. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  27461. this._vertexData[arrayOffset + 11] = offset;
  27462. // Color
  27463. this._vertexData[arrayOffset + 12] = sprite.color.r;
  27464. this._vertexData[arrayOffset + 13] = sprite.color.g;
  27465. this._vertexData[arrayOffset + 14] = sprite.color.b;
  27466. this._vertexData[arrayOffset + 15] = sprite.color.a;
  27467. };
  27468. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  27469. var count = Math.min(this._capacity, this.sprites.length);
  27470. var min = BABYLON.Vector3.Zero();
  27471. var max = BABYLON.Vector3.Zero();
  27472. var distance = Number.MAX_VALUE;
  27473. var currentSprite;
  27474. var cameraSpacePosition = BABYLON.Vector3.Zero();
  27475. var cameraView = camera.getViewMatrix();
  27476. for (var index = 0; index < count; index++) {
  27477. var sprite = this.sprites[index];
  27478. if (!sprite) {
  27479. continue;
  27480. }
  27481. if (predicate) {
  27482. if (!predicate(sprite)) {
  27483. continue;
  27484. }
  27485. }
  27486. else if (!sprite.isPickable) {
  27487. continue;
  27488. }
  27489. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  27490. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  27491. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  27492. if (ray.intersectsBoxMinMax(min, max)) {
  27493. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  27494. if (distance > currentDistance) {
  27495. distance = currentDistance;
  27496. currentSprite = sprite;
  27497. if (fastCheck) {
  27498. break;
  27499. }
  27500. }
  27501. }
  27502. }
  27503. if (currentSprite) {
  27504. var result = new BABYLON.PickingInfo();
  27505. result.hit = true;
  27506. result.pickedSprite = currentSprite;
  27507. result.distance = distance;
  27508. return result;
  27509. }
  27510. return null;
  27511. };
  27512. SpriteManager.prototype.render = function () {
  27513. // Check
  27514. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  27515. return;
  27516. var engine = this._scene.getEngine();
  27517. var baseSize = this._spriteTexture.getBaseSize();
  27518. // Sprites
  27519. var deltaTime = engine.getDeltaTime();
  27520. var max = Math.min(this._capacity, this.sprites.length);
  27521. var rowSize = baseSize.width / this.cellWidth;
  27522. var offset = 0;
  27523. for (var index = 0; index < max; index++) {
  27524. var sprite = this.sprites[index];
  27525. if (!sprite) {
  27526. continue;
  27527. }
  27528. sprite._animate(deltaTime);
  27529. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  27530. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  27531. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  27532. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  27533. }
  27534. this._buffer.update(this._vertexData);
  27535. // Render
  27536. var effect = this._effectBase;
  27537. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27538. effect = this._effectFog;
  27539. }
  27540. engine.enableEffect(effect);
  27541. var viewMatrix = this._scene.getViewMatrix();
  27542. effect.setTexture("diffuseSampler", this._spriteTexture);
  27543. effect.setMatrix("view", viewMatrix);
  27544. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  27545. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  27546. // Fog
  27547. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27548. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  27549. effect.setColor3("vFogColor", this._scene.fogColor);
  27550. }
  27551. // VBOs
  27552. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  27553. // Draw order
  27554. engine.setDepthFunctionToLessOrEqual();
  27555. effect.setBool("alphaTest", true);
  27556. engine.setColorWrite(false);
  27557. engine.draw(true, 0, max * 6);
  27558. engine.setColorWrite(true);
  27559. effect.setBool("alphaTest", false);
  27560. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  27561. engine.draw(true, 0, max * 6);
  27562. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27563. };
  27564. SpriteManager.prototype.dispose = function () {
  27565. if (this._buffer) {
  27566. this._buffer.dispose();
  27567. this._buffer = null;
  27568. }
  27569. if (this._indexBuffer) {
  27570. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27571. this._indexBuffer = null;
  27572. }
  27573. if (this._spriteTexture) {
  27574. this._spriteTexture.dispose();
  27575. this._spriteTexture = null;
  27576. }
  27577. // Remove from scene
  27578. var index = this._scene.spriteManagers.indexOf(this);
  27579. this._scene.spriteManagers.splice(index, 1);
  27580. // Callback
  27581. this.onDisposeObservable.notifyObservers(this);
  27582. this.onDisposeObservable.clear();
  27583. };
  27584. return SpriteManager;
  27585. }());
  27586. BABYLON.SpriteManager = SpriteManager;
  27587. })(BABYLON || (BABYLON = {}));
  27588. var BABYLON;
  27589. (function (BABYLON) {
  27590. var Sprite = (function () {
  27591. function Sprite(name, manager) {
  27592. this.name = name;
  27593. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27594. this.width = 1.0;
  27595. this.height = 1.0;
  27596. this.angle = 0;
  27597. this.cellIndex = 0;
  27598. this.invertU = 0;
  27599. this.invertV = 0;
  27600. this.animations = new Array();
  27601. this.isPickable = false;
  27602. this._animationStarted = false;
  27603. this._loopAnimation = false;
  27604. this._fromIndex = 0;
  27605. this._toIndex = 0;
  27606. this._delay = 0;
  27607. this._direction = 1;
  27608. this._frameCount = 0;
  27609. this._time = 0;
  27610. this._manager = manager;
  27611. this._manager.sprites.push(this);
  27612. this.position = BABYLON.Vector3.Zero();
  27613. }
  27614. Object.defineProperty(Sprite.prototype, "size", {
  27615. get: function () {
  27616. return this.width;
  27617. },
  27618. set: function (value) {
  27619. this.width = value;
  27620. this.height = value;
  27621. },
  27622. enumerable: true,
  27623. configurable: true
  27624. });
  27625. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  27626. this._fromIndex = from;
  27627. this._toIndex = to;
  27628. this._loopAnimation = loop;
  27629. this._delay = delay;
  27630. this._animationStarted = true;
  27631. this._direction = from < to ? 1 : -1;
  27632. this.cellIndex = from;
  27633. this._time = 0;
  27634. this._onAnimationEnd = onAnimationEnd;
  27635. };
  27636. Sprite.prototype.stopAnimation = function () {
  27637. this._animationStarted = false;
  27638. };
  27639. Sprite.prototype._animate = function (deltaTime) {
  27640. if (!this._animationStarted)
  27641. return;
  27642. this._time += deltaTime;
  27643. if (this._time > this._delay) {
  27644. this._time = this._time % this._delay;
  27645. this.cellIndex += this._direction;
  27646. if (this.cellIndex === this._toIndex) {
  27647. if (this._loopAnimation) {
  27648. this.cellIndex = this._fromIndex;
  27649. }
  27650. else {
  27651. this._animationStarted = false;
  27652. if (this._onAnimationEnd) {
  27653. this._onAnimationEnd();
  27654. }
  27655. if (this.disposeWhenFinishedAnimating) {
  27656. this.dispose();
  27657. }
  27658. }
  27659. }
  27660. }
  27661. };
  27662. Sprite.prototype.dispose = function () {
  27663. for (var i = 0; i < this._manager.sprites.length; i++) {
  27664. if (this._manager.sprites[i] == this) {
  27665. this._manager.sprites.splice(i, 1);
  27666. }
  27667. }
  27668. };
  27669. return Sprite;
  27670. }());
  27671. BABYLON.Sprite = Sprite;
  27672. })(BABYLON || (BABYLON = {}));
  27673. var BABYLON;
  27674. (function (BABYLON) {
  27675. var Layer = (function () {
  27676. function Layer(name, imgUrl, scene, isBackground, color) {
  27677. this.name = name;
  27678. this.scale = new BABYLON.Vector2(1, 1);
  27679. this.offset = new BABYLON.Vector2(0, 0);
  27680. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  27681. this._vertexBuffers = {};
  27682. // Events
  27683. /**
  27684. * An event triggered when the layer is disposed.
  27685. * @type {BABYLON.Observable}
  27686. */
  27687. this.onDisposeObservable = new BABYLON.Observable();
  27688. /**
  27689. * An event triggered before rendering the scene
  27690. * @type {BABYLON.Observable}
  27691. */
  27692. this.onBeforeRenderObservable = new BABYLON.Observable();
  27693. /**
  27694. * An event triggered after rendering the scene
  27695. * @type {BABYLON.Observable}
  27696. */
  27697. this.onAfterRenderObservable = new BABYLON.Observable();
  27698. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  27699. this.isBackground = isBackground === undefined ? true : isBackground;
  27700. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  27701. this._scene = scene;
  27702. this._scene.layers.push(this);
  27703. var engine = scene.getEngine();
  27704. // VBO
  27705. var vertices = [];
  27706. vertices.push(1, 1);
  27707. vertices.push(-1, 1);
  27708. vertices.push(-1, -1);
  27709. vertices.push(1, -1);
  27710. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  27711. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  27712. // Indices
  27713. var indices = [];
  27714. indices.push(0);
  27715. indices.push(1);
  27716. indices.push(2);
  27717. indices.push(0);
  27718. indices.push(2);
  27719. indices.push(3);
  27720. this._indexBuffer = engine.createIndexBuffer(indices);
  27721. // Effects
  27722. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  27723. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  27724. }
  27725. Object.defineProperty(Layer.prototype, "onDispose", {
  27726. set: function (callback) {
  27727. if (this._onDisposeObserver) {
  27728. this.onDisposeObservable.remove(this._onDisposeObserver);
  27729. }
  27730. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27731. },
  27732. enumerable: true,
  27733. configurable: true
  27734. });
  27735. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  27736. set: function (callback) {
  27737. if (this._onBeforeRenderObserver) {
  27738. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  27739. }
  27740. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  27741. },
  27742. enumerable: true,
  27743. configurable: true
  27744. });
  27745. Object.defineProperty(Layer.prototype, "onAfterRender", {
  27746. set: function (callback) {
  27747. if (this._onAfterRenderObserver) {
  27748. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  27749. }
  27750. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  27751. },
  27752. enumerable: true,
  27753. configurable: true
  27754. });
  27755. Layer.prototype.render = function () {
  27756. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  27757. // Check
  27758. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  27759. return;
  27760. var engine = this._scene.getEngine();
  27761. this.onBeforeRenderObservable.notifyObservers(this);
  27762. // Render
  27763. engine.enableEffect(currentEffect);
  27764. engine.setState(false);
  27765. // Texture
  27766. currentEffect.setTexture("textureSampler", this.texture);
  27767. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  27768. // Color
  27769. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  27770. // Scale / offset
  27771. currentEffect.setVector2("offset", this.offset);
  27772. currentEffect.setVector2("scale", this.scale);
  27773. // VBOs
  27774. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  27775. // Draw order
  27776. if (!this.alphaTest) {
  27777. engine.setAlphaMode(this.alphaBlendingMode);
  27778. engine.draw(true, 0, 6);
  27779. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  27780. }
  27781. else {
  27782. engine.draw(true, 0, 6);
  27783. }
  27784. this.onAfterRenderObservable.notifyObservers(this);
  27785. };
  27786. Layer.prototype.dispose = function () {
  27787. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  27788. if (vertexBuffer) {
  27789. vertexBuffer.dispose();
  27790. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  27791. }
  27792. if (this._indexBuffer) {
  27793. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  27794. this._indexBuffer = null;
  27795. }
  27796. if (this.texture) {
  27797. this.texture.dispose();
  27798. this.texture = null;
  27799. }
  27800. // Remove from scene
  27801. var index = this._scene.layers.indexOf(this);
  27802. this._scene.layers.splice(index, 1);
  27803. // Callback
  27804. this.onDisposeObservable.notifyObservers(this);
  27805. this.onDisposeObservable.clear();
  27806. this.onAfterRenderObservable.clear();
  27807. this.onBeforeRenderObservable.clear();
  27808. };
  27809. return Layer;
  27810. }());
  27811. BABYLON.Layer = Layer;
  27812. })(BABYLON || (BABYLON = {}));
  27813. var BABYLON;
  27814. (function (BABYLON) {
  27815. var Particle = (function () {
  27816. function Particle() {
  27817. this.position = BABYLON.Vector3.Zero();
  27818. this.direction = BABYLON.Vector3.Zero();
  27819. this.color = new BABYLON.Color4(0, 0, 0, 0);
  27820. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  27821. this.lifeTime = 1.0;
  27822. this.age = 0;
  27823. this.size = 0;
  27824. this.angle = 0;
  27825. this.angularSpeed = 0;
  27826. }
  27827. Particle.prototype.copyTo = function (other) {
  27828. other.position.copyFrom(this.position);
  27829. other.direction.copyFrom(this.direction);
  27830. other.color.copyFrom(this.color);
  27831. other.colorStep.copyFrom(this.colorStep);
  27832. other.lifeTime = this.lifeTime;
  27833. other.age = this.age;
  27834. other.size = this.size;
  27835. other.angle = this.angle;
  27836. other.angularSpeed = this.angularSpeed;
  27837. };
  27838. return Particle;
  27839. }());
  27840. BABYLON.Particle = Particle;
  27841. })(BABYLON || (BABYLON = {}));
  27842. var BABYLON;
  27843. (function (BABYLON) {
  27844. var randomNumber = function (min, max) {
  27845. if (min === max) {
  27846. return (min);
  27847. }
  27848. var random = Math.random();
  27849. return ((random * (max - min)) + min);
  27850. };
  27851. var ParticleSystem = (function () {
  27852. function ParticleSystem(name, capacity, scene, customEffect) {
  27853. var _this = this;
  27854. this.name = name;
  27855. // Members
  27856. this.animations = [];
  27857. this.renderingGroupId = 0;
  27858. this.emitter = null;
  27859. this.emitRate = 10;
  27860. this.manualEmitCount = -1;
  27861. this.updateSpeed = 0.01;
  27862. this.targetStopDuration = 0;
  27863. this.disposeOnStop = false;
  27864. this.minEmitPower = 1;
  27865. this.maxEmitPower = 1;
  27866. this.minLifeTime = 1;
  27867. this.maxLifeTime = 1;
  27868. this.minSize = 1;
  27869. this.maxSize = 1;
  27870. this.minAngularSpeed = 0;
  27871. this.maxAngularSpeed = 0;
  27872. this.layerMask = 0x0FFFFFFF;
  27873. /**
  27874. * An event triggered when the system is disposed.
  27875. * @type {BABYLON.Observable}
  27876. */
  27877. this.onDisposeObservable = new BABYLON.Observable();
  27878. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  27879. this.forceDepthWrite = false;
  27880. this.gravity = BABYLON.Vector3.Zero();
  27881. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  27882. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  27883. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  27884. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  27885. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27886. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27887. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  27888. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  27889. this.particles = new Array();
  27890. this._stockParticles = new Array();
  27891. this._newPartsExcess = 0;
  27892. this._vertexBuffers = {};
  27893. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  27894. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  27895. this._scaledDirection = BABYLON.Vector3.Zero();
  27896. this._scaledGravity = BABYLON.Vector3.Zero();
  27897. this._currentRenderId = -1;
  27898. this._started = false;
  27899. this._stopped = false;
  27900. this._actualFrame = 0;
  27901. this.id = name;
  27902. this._capacity = capacity;
  27903. this._scene = scene;
  27904. this._customEffect = customEffect;
  27905. scene.particleSystems.push(this);
  27906. var indices = [];
  27907. var index = 0;
  27908. for (var count = 0; count < capacity; count++) {
  27909. indices.push(index);
  27910. indices.push(index + 1);
  27911. indices.push(index + 2);
  27912. indices.push(index);
  27913. indices.push(index + 2);
  27914. indices.push(index + 3);
  27915. index += 4;
  27916. }
  27917. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  27918. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  27919. this._vertexData = new Float32Array(capacity * 11 * 4);
  27920. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  27921. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  27922. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  27923. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  27924. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  27925. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  27926. this._vertexBuffers["options"] = options;
  27927. // Default behaviors
  27928. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  27929. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  27930. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  27931. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  27932. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  27933. };
  27934. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  27935. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  27936. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  27937. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  27938. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  27939. };
  27940. this.updateFunction = function (particles) {
  27941. for (var index = 0; index < particles.length; index++) {
  27942. var particle = particles[index];
  27943. particle.age += _this._scaledUpdateSpeed;
  27944. if (particle.age >= particle.lifeTime) {
  27945. _this.recycleParticle(particle);
  27946. index--;
  27947. continue;
  27948. }
  27949. else {
  27950. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  27951. particle.color.addInPlace(_this._scaledColorStep);
  27952. if (particle.color.a < 0)
  27953. particle.color.a = 0;
  27954. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  27955. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  27956. particle.position.addInPlace(_this._scaledDirection);
  27957. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  27958. particle.direction.addInPlace(_this._scaledGravity);
  27959. }
  27960. }
  27961. };
  27962. }
  27963. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  27964. set: function (callback) {
  27965. if (this._onDisposeObserver) {
  27966. this.onDisposeObservable.remove(this._onDisposeObserver);
  27967. }
  27968. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27969. },
  27970. enumerable: true,
  27971. configurable: true
  27972. });
  27973. ParticleSystem.prototype.recycleParticle = function (particle) {
  27974. var lastParticle = this.particles.pop();
  27975. if (lastParticle !== particle) {
  27976. lastParticle.copyTo(particle);
  27977. this._stockParticles.push(lastParticle);
  27978. }
  27979. };
  27980. ParticleSystem.prototype.getCapacity = function () {
  27981. return this._capacity;
  27982. };
  27983. ParticleSystem.prototype.isAlive = function () {
  27984. return this._alive;
  27985. };
  27986. ParticleSystem.prototype.isStarted = function () {
  27987. return this._started;
  27988. };
  27989. ParticleSystem.prototype.start = function () {
  27990. this._started = true;
  27991. this._stopped = false;
  27992. this._actualFrame = 0;
  27993. };
  27994. ParticleSystem.prototype.stop = function () {
  27995. this._stopped = true;
  27996. };
  27997. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  27998. var offset = index * 11;
  27999. this._vertexData[offset] = particle.position.x;
  28000. this._vertexData[offset + 1] = particle.position.y;
  28001. this._vertexData[offset + 2] = particle.position.z;
  28002. this._vertexData[offset + 3] = particle.color.r;
  28003. this._vertexData[offset + 4] = particle.color.g;
  28004. this._vertexData[offset + 5] = particle.color.b;
  28005. this._vertexData[offset + 6] = particle.color.a;
  28006. this._vertexData[offset + 7] = particle.angle;
  28007. this._vertexData[offset + 8] = particle.size;
  28008. this._vertexData[offset + 9] = offsetX;
  28009. this._vertexData[offset + 10] = offsetY;
  28010. };
  28011. ParticleSystem.prototype._update = function (newParticles) {
  28012. // Update current
  28013. this._alive = this.particles.length > 0;
  28014. this.updateFunction(this.particles);
  28015. // Add new ones
  28016. var worldMatrix;
  28017. if (this.emitter.position) {
  28018. worldMatrix = this.emitter.getWorldMatrix();
  28019. }
  28020. else {
  28021. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  28022. }
  28023. var particle;
  28024. for (var index = 0; index < newParticles; index++) {
  28025. if (this.particles.length === this._capacity) {
  28026. break;
  28027. }
  28028. if (this._stockParticles.length !== 0) {
  28029. particle = this._stockParticles.pop();
  28030. particle.age = 0;
  28031. }
  28032. else {
  28033. particle = new BABYLON.Particle();
  28034. }
  28035. this.particles.push(particle);
  28036. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  28037. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  28038. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  28039. particle.size = randomNumber(this.minSize, this.maxSize);
  28040. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  28041. this.startPositionFunction(worldMatrix, particle.position, particle);
  28042. var step = randomNumber(0, 1.0);
  28043. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  28044. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  28045. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  28046. }
  28047. };
  28048. ParticleSystem.prototype._getEffect = function () {
  28049. if (this._customEffect) {
  28050. return this._customEffect;
  28051. }
  28052. ;
  28053. var defines = [];
  28054. if (this._scene.clipPlane) {
  28055. defines.push("#define CLIPPLANE");
  28056. }
  28057. // Effect
  28058. var join = defines.join("\n");
  28059. if (this._cachedDefines !== join) {
  28060. this._cachedDefines = join;
  28061. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  28062. }
  28063. return this._effect;
  28064. };
  28065. ParticleSystem.prototype.animate = function () {
  28066. if (!this._started)
  28067. return;
  28068. var effect = this._getEffect();
  28069. // Check
  28070. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  28071. return;
  28072. if (this._currentRenderId === this._scene.getRenderId()) {
  28073. return;
  28074. }
  28075. this._currentRenderId = this._scene.getRenderId();
  28076. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  28077. // determine the number of particles we need to create
  28078. var newParticles;
  28079. if (this.manualEmitCount > -1) {
  28080. newParticles = this.manualEmitCount;
  28081. this._newPartsExcess = 0;
  28082. this.manualEmitCount = 0;
  28083. }
  28084. else {
  28085. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  28086. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  28087. }
  28088. if (this._newPartsExcess > 1.0) {
  28089. newParticles += this._newPartsExcess >> 0;
  28090. this._newPartsExcess -= this._newPartsExcess >> 0;
  28091. }
  28092. this._alive = false;
  28093. if (!this._stopped) {
  28094. this._actualFrame += this._scaledUpdateSpeed;
  28095. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  28096. this.stop();
  28097. }
  28098. else {
  28099. newParticles = 0;
  28100. }
  28101. this._update(newParticles);
  28102. // Stopped?
  28103. if (this._stopped) {
  28104. if (!this._alive) {
  28105. this._started = false;
  28106. if (this.disposeOnStop) {
  28107. this._scene._toBeDisposed.push(this);
  28108. }
  28109. }
  28110. }
  28111. // Update VBO
  28112. var offset = 0;
  28113. for (var index = 0; index < this.particles.length; index++) {
  28114. var particle = this.particles[index];
  28115. this._appendParticleVertex(offset++, particle, 0, 0);
  28116. this._appendParticleVertex(offset++, particle, 1, 0);
  28117. this._appendParticleVertex(offset++, particle, 1, 1);
  28118. this._appendParticleVertex(offset++, particle, 0, 1);
  28119. }
  28120. this._vertexBuffer.update(this._vertexData);
  28121. };
  28122. ParticleSystem.prototype.render = function () {
  28123. var effect = this._getEffect();
  28124. // Check
  28125. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  28126. return 0;
  28127. var engine = this._scene.getEngine();
  28128. // Render
  28129. engine.enableEffect(effect);
  28130. engine.setState(false);
  28131. var viewMatrix = this._scene.getViewMatrix();
  28132. effect.setTexture("diffuseSampler", this.particleTexture);
  28133. effect.setMatrix("view", viewMatrix);
  28134. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28135. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  28136. if (this._scene.clipPlane) {
  28137. var clipPlane = this._scene.clipPlane;
  28138. var invView = viewMatrix.clone();
  28139. invView.invert();
  28140. effect.setMatrix("invView", invView);
  28141. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28142. }
  28143. // VBOs
  28144. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28145. // Draw order
  28146. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  28147. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  28148. }
  28149. else {
  28150. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28151. }
  28152. if (this.forceDepthWrite) {
  28153. engine.setDepthWrite(true);
  28154. }
  28155. engine.draw(true, 0, this.particles.length * 6);
  28156. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28157. return this.particles.length;
  28158. };
  28159. ParticleSystem.prototype.dispose = function () {
  28160. if (this._vertexBuffer) {
  28161. this._vertexBuffer.dispose();
  28162. this._vertexBuffer = null;
  28163. }
  28164. if (this._indexBuffer) {
  28165. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28166. this._indexBuffer = null;
  28167. }
  28168. if (this.particleTexture) {
  28169. this.particleTexture.dispose();
  28170. this.particleTexture = null;
  28171. }
  28172. // Remove from scene
  28173. var index = this._scene.particleSystems.indexOf(this);
  28174. this._scene.particleSystems.splice(index, 1);
  28175. // Callback
  28176. this.onDisposeObservable.notifyObservers(this);
  28177. this.onDisposeObservable.clear();
  28178. };
  28179. // Clone
  28180. ParticleSystem.prototype.clone = function (name, newEmitter) {
  28181. var result = new ParticleSystem(name, this._capacity, this._scene);
  28182. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  28183. if (newEmitter === undefined) {
  28184. newEmitter = this.emitter;
  28185. }
  28186. result.emitter = newEmitter;
  28187. if (this.particleTexture) {
  28188. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  28189. }
  28190. result.start();
  28191. return result;
  28192. };
  28193. ParticleSystem.prototype.serialize = function () {
  28194. var serializationObject = {};
  28195. serializationObject.name = this.name;
  28196. serializationObject.id = this.id;
  28197. // Emitter
  28198. if (this.emitter.position) {
  28199. serializationObject.emitterId = this.emitter.id;
  28200. }
  28201. else {
  28202. serializationObject.emitter = this.emitter.asArray();
  28203. }
  28204. serializationObject.capacity = this.getCapacity();
  28205. if (this.particleTexture) {
  28206. serializationObject.textureName = this.particleTexture.name;
  28207. }
  28208. // Animations
  28209. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28210. // Particle system
  28211. serializationObject.minAngularSpeed = this.minAngularSpeed;
  28212. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  28213. serializationObject.minSize = this.minSize;
  28214. serializationObject.maxSize = this.maxSize;
  28215. serializationObject.minEmitPower = this.minEmitPower;
  28216. serializationObject.maxEmitPower = this.maxEmitPower;
  28217. serializationObject.minLifeTime = this.minLifeTime;
  28218. serializationObject.maxLifeTime = this.maxLifeTime;
  28219. serializationObject.emitRate = this.emitRate;
  28220. serializationObject.minEmitBox = this.minEmitBox.asArray();
  28221. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  28222. serializationObject.gravity = this.gravity.asArray();
  28223. serializationObject.direction1 = this.direction1.asArray();
  28224. serializationObject.direction2 = this.direction2.asArray();
  28225. serializationObject.color1 = this.color1.asArray();
  28226. serializationObject.color2 = this.color2.asArray();
  28227. serializationObject.colorDead = this.colorDead.asArray();
  28228. serializationObject.updateSpeed = this.updateSpeed;
  28229. serializationObject.targetStopDuration = this.targetStopDuration;
  28230. serializationObject.textureMask = this.textureMask.asArray();
  28231. serializationObject.blendMode = this.blendMode;
  28232. return serializationObject;
  28233. };
  28234. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28235. var name = parsedParticleSystem.name;
  28236. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28237. if (parsedParticleSystem.id) {
  28238. particleSystem.id = parsedParticleSystem.id;
  28239. }
  28240. // Texture
  28241. if (parsedParticleSystem.textureName) {
  28242. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28243. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28244. }
  28245. // Emitter
  28246. if (parsedParticleSystem.emitterId) {
  28247. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28248. }
  28249. else {
  28250. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  28251. }
  28252. // Animations
  28253. if (parsedParticleSystem.animations) {
  28254. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  28255. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  28256. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  28257. }
  28258. }
  28259. if (parsedParticleSystem.autoAnimate) {
  28260. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  28261. }
  28262. // Particle system
  28263. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  28264. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  28265. particleSystem.minSize = parsedParticleSystem.minSize;
  28266. particleSystem.maxSize = parsedParticleSystem.maxSize;
  28267. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  28268. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  28269. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  28270. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  28271. particleSystem.emitRate = parsedParticleSystem.emitRate;
  28272. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  28273. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  28274. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  28275. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  28276. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  28277. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  28278. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  28279. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  28280. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  28281. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  28282. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  28283. particleSystem.blendMode = parsedParticleSystem.blendMode;
  28284. if (!parsedParticleSystem.preventAutoStart) {
  28285. particleSystem.start();
  28286. }
  28287. return particleSystem;
  28288. };
  28289. // Statics
  28290. ParticleSystem.BLENDMODE_ONEONE = 0;
  28291. ParticleSystem.BLENDMODE_STANDARD = 1;
  28292. return ParticleSystem;
  28293. }());
  28294. BABYLON.ParticleSystem = ParticleSystem;
  28295. })(BABYLON || (BABYLON = {}));
  28296. var BABYLON;
  28297. (function (BABYLON) {
  28298. var AnimationRange = (function () {
  28299. function AnimationRange(name, from, to) {
  28300. this.name = name;
  28301. this.from = from;
  28302. this.to = to;
  28303. }
  28304. AnimationRange.prototype.clone = function () {
  28305. return new AnimationRange(this.name, this.from, this.to);
  28306. };
  28307. return AnimationRange;
  28308. }());
  28309. BABYLON.AnimationRange = AnimationRange;
  28310. /**
  28311. * Composed of a frame, and an action function
  28312. */
  28313. var AnimationEvent = (function () {
  28314. function AnimationEvent(frame, action, onlyOnce) {
  28315. this.frame = frame;
  28316. this.action = action;
  28317. this.onlyOnce = onlyOnce;
  28318. this.isDone = false;
  28319. }
  28320. return AnimationEvent;
  28321. }());
  28322. BABYLON.AnimationEvent = AnimationEvent;
  28323. var PathCursor = (function () {
  28324. function PathCursor(path) {
  28325. this.path = path;
  28326. this._onchange = new Array();
  28327. this.value = 0;
  28328. this.animations = new Array();
  28329. }
  28330. PathCursor.prototype.getPoint = function () {
  28331. var point = this.path.getPointAtLengthPosition(this.value);
  28332. return new BABYLON.Vector3(point.x, 0, point.y);
  28333. };
  28334. PathCursor.prototype.moveAhead = function (step) {
  28335. if (step === void 0) { step = 0.002; }
  28336. this.move(step);
  28337. return this;
  28338. };
  28339. PathCursor.prototype.moveBack = function (step) {
  28340. if (step === void 0) { step = 0.002; }
  28341. this.move(-step);
  28342. return this;
  28343. };
  28344. PathCursor.prototype.move = function (step) {
  28345. if (Math.abs(step) > 1) {
  28346. throw "step size should be less than 1.";
  28347. }
  28348. this.value += step;
  28349. this.ensureLimits();
  28350. this.raiseOnChange();
  28351. return this;
  28352. };
  28353. PathCursor.prototype.ensureLimits = function () {
  28354. while (this.value > 1) {
  28355. this.value -= 1;
  28356. }
  28357. while (this.value < 0) {
  28358. this.value += 1;
  28359. }
  28360. return this;
  28361. };
  28362. // used by animation engine
  28363. PathCursor.prototype.markAsDirty = function (propertyName) {
  28364. this.ensureLimits();
  28365. this.raiseOnChange();
  28366. return this;
  28367. };
  28368. PathCursor.prototype.raiseOnChange = function () {
  28369. var _this = this;
  28370. this._onchange.forEach(function (f) { return f(_this); });
  28371. return this;
  28372. };
  28373. PathCursor.prototype.onchange = function (f) {
  28374. this._onchange.push(f);
  28375. return this;
  28376. };
  28377. return PathCursor;
  28378. }());
  28379. BABYLON.PathCursor = PathCursor;
  28380. var Animation = (function () {
  28381. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  28382. this.name = name;
  28383. this.targetProperty = targetProperty;
  28384. this.framePerSecond = framePerSecond;
  28385. this.dataType = dataType;
  28386. this.loopMode = loopMode;
  28387. this.enableBlending = enableBlending;
  28388. this._offsetsCache = {};
  28389. this._highLimitsCache = {};
  28390. this._stopped = false;
  28391. this._blendingFactor = 0;
  28392. // The set of event that will be linked to this animation
  28393. this._events = new Array();
  28394. this.allowMatricesInterpolation = false;
  28395. this.blendingSpeed = 0.01;
  28396. this._ranges = {};
  28397. this.targetPropertyPath = targetProperty.split(".");
  28398. this.dataType = dataType;
  28399. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  28400. }
  28401. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  28402. var dataType = undefined;
  28403. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  28404. dataType = Animation.ANIMATIONTYPE_FLOAT;
  28405. }
  28406. else if (from instanceof BABYLON.Quaternion) {
  28407. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  28408. }
  28409. else if (from instanceof BABYLON.Vector3) {
  28410. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  28411. }
  28412. else if (from instanceof BABYLON.Vector2) {
  28413. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  28414. }
  28415. else if (from instanceof BABYLON.Color3) {
  28416. dataType = Animation.ANIMATIONTYPE_COLOR3;
  28417. }
  28418. else if (from instanceof BABYLON.Size) {
  28419. dataType = Animation.ANIMATIONTYPE_SIZE;
  28420. }
  28421. if (dataType == undefined) {
  28422. return null;
  28423. }
  28424. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  28425. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  28426. animation.setKeys(keys);
  28427. if (easingFunction !== undefined) {
  28428. animation.setEasingFunction(easingFunction);
  28429. }
  28430. return animation;
  28431. };
  28432. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28433. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28434. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28435. };
  28436. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  28437. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  28438. node.animations.push(animation);
  28439. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  28440. };
  28441. // Methods
  28442. /**
  28443. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  28444. */
  28445. Animation.prototype.toString = function (fullDetails) {
  28446. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  28447. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  28448. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  28449. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  28450. if (fullDetails) {
  28451. ret += ", Ranges: {";
  28452. var first = true;
  28453. for (var name in this._ranges) {
  28454. if (first) {
  28455. ret += ", ";
  28456. first = false;
  28457. }
  28458. ret += name;
  28459. }
  28460. ret += "}";
  28461. }
  28462. return ret;
  28463. };
  28464. /**
  28465. * Add an event to this animation.
  28466. */
  28467. Animation.prototype.addEvent = function (event) {
  28468. this._events.push(event);
  28469. };
  28470. /**
  28471. * Remove all events found at the given frame
  28472. * @param frame
  28473. */
  28474. Animation.prototype.removeEvents = function (frame) {
  28475. for (var index = 0; index < this._events.length; index++) {
  28476. if (this._events[index].frame === frame) {
  28477. this._events.splice(index, 1);
  28478. index--;
  28479. }
  28480. }
  28481. };
  28482. Animation.prototype.createRange = function (name, from, to) {
  28483. // check name not already in use; could happen for bones after serialized
  28484. if (!this._ranges[name]) {
  28485. this._ranges[name] = new AnimationRange(name, from, to);
  28486. }
  28487. };
  28488. Animation.prototype.deleteRange = function (name, deleteFrames) {
  28489. if (deleteFrames === void 0) { deleteFrames = true; }
  28490. if (this._ranges[name]) {
  28491. if (deleteFrames) {
  28492. var from = this._ranges[name].from;
  28493. var to = this._ranges[name].to;
  28494. // this loop MUST go high to low for multiple splices to work
  28495. for (var key = this._keys.length - 1; key >= 0; key--) {
  28496. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  28497. this._keys.splice(key, 1);
  28498. }
  28499. }
  28500. }
  28501. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  28502. }
  28503. };
  28504. Animation.prototype.getRange = function (name) {
  28505. return this._ranges[name];
  28506. };
  28507. Animation.prototype.reset = function () {
  28508. this._offsetsCache = {};
  28509. this._highLimitsCache = {};
  28510. this.currentFrame = 0;
  28511. this._blendingFactor = 0;
  28512. this._originalBlendValue = null;
  28513. };
  28514. Animation.prototype.isStopped = function () {
  28515. return this._stopped;
  28516. };
  28517. Animation.prototype.getKeys = function () {
  28518. return this._keys;
  28519. };
  28520. Animation.prototype.getHighestFrame = function () {
  28521. var ret = 0;
  28522. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  28523. if (ret < this._keys[key].frame) {
  28524. ret = this._keys[key].frame;
  28525. }
  28526. }
  28527. return ret;
  28528. };
  28529. Animation.prototype.getEasingFunction = function () {
  28530. return this._easingFunction;
  28531. };
  28532. Animation.prototype.setEasingFunction = function (easingFunction) {
  28533. this._easingFunction = easingFunction;
  28534. };
  28535. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  28536. return startValue + (endValue - startValue) * gradient;
  28537. };
  28538. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  28539. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  28540. };
  28541. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  28542. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  28543. };
  28544. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  28545. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  28546. };
  28547. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  28548. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  28549. };
  28550. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  28551. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  28552. };
  28553. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  28554. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  28555. };
  28556. Animation.prototype.clone = function () {
  28557. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  28558. if (this._keys) {
  28559. clone.setKeys(this._keys);
  28560. }
  28561. if (this._ranges) {
  28562. clone._ranges = {};
  28563. for (var name in this._ranges) {
  28564. clone._ranges[name] = this._ranges[name].clone();
  28565. }
  28566. }
  28567. return clone;
  28568. };
  28569. Animation.prototype.setKeys = function (values) {
  28570. this._keys = values.slice(0);
  28571. this._offsetsCache = {};
  28572. this._highLimitsCache = {};
  28573. };
  28574. Animation.prototype._getKeyValue = function (value) {
  28575. if (typeof value === "function") {
  28576. return value();
  28577. }
  28578. return value;
  28579. };
  28580. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  28581. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  28582. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  28583. }
  28584. this.currentFrame = currentFrame;
  28585. // Try to get a hash to find the right key
  28586. 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));
  28587. if (this._keys[startKey].frame >= currentFrame) {
  28588. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  28589. startKey--;
  28590. }
  28591. }
  28592. for (var key = startKey; key < this._keys.length; key++) {
  28593. if (this._keys[key + 1].frame >= currentFrame) {
  28594. var startValue = this._getKeyValue(this._keys[key].value);
  28595. var endValue = this._getKeyValue(this._keys[key + 1].value);
  28596. // gradient : percent of currentFrame between the frame inf and the frame sup
  28597. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  28598. // check for easingFunction and correction of gradient
  28599. if (this._easingFunction != null) {
  28600. gradient = this._easingFunction.ease(gradient);
  28601. }
  28602. switch (this.dataType) {
  28603. // Float
  28604. case Animation.ANIMATIONTYPE_FLOAT:
  28605. switch (loopMode) {
  28606. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28607. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28608. return this.floatInterpolateFunction(startValue, endValue, gradient);
  28609. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28610. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  28611. }
  28612. break;
  28613. // Quaternion
  28614. case Animation.ANIMATIONTYPE_QUATERNION:
  28615. var quaternion = null;
  28616. switch (loopMode) {
  28617. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28618. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28619. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  28620. break;
  28621. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28622. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28623. break;
  28624. }
  28625. return quaternion;
  28626. // Vector3
  28627. case Animation.ANIMATIONTYPE_VECTOR3:
  28628. switch (loopMode) {
  28629. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28630. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28631. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  28632. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28633. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28634. }
  28635. // Vector2
  28636. case Animation.ANIMATIONTYPE_VECTOR2:
  28637. switch (loopMode) {
  28638. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28639. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28640. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  28641. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28642. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28643. }
  28644. // Size
  28645. case Animation.ANIMATIONTYPE_SIZE:
  28646. switch (loopMode) {
  28647. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28648. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28649. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  28650. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28651. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28652. }
  28653. // Color3
  28654. case Animation.ANIMATIONTYPE_COLOR3:
  28655. switch (loopMode) {
  28656. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28657. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28658. return this.color3InterpolateFunction(startValue, endValue, gradient);
  28659. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28660. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  28661. }
  28662. // Matrix
  28663. case Animation.ANIMATIONTYPE_MATRIX:
  28664. switch (loopMode) {
  28665. case Animation.ANIMATIONLOOPMODE_CYCLE:
  28666. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  28667. if (this.allowMatricesInterpolation) {
  28668. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  28669. }
  28670. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  28671. return startValue;
  28672. }
  28673. default:
  28674. break;
  28675. }
  28676. break;
  28677. }
  28678. }
  28679. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  28680. };
  28681. Animation.prototype.setValue = function (currentValue, blend) {
  28682. if (blend === void 0) { blend = false; }
  28683. // Set value
  28684. var path;
  28685. var destination;
  28686. if (this.targetPropertyPath.length > 1) {
  28687. var property = this._target[this.targetPropertyPath[0]];
  28688. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  28689. property = property[this.targetPropertyPath[index]];
  28690. }
  28691. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  28692. destination = property;
  28693. }
  28694. else {
  28695. path = this.targetPropertyPath[0];
  28696. destination = this._target;
  28697. }
  28698. // Blending
  28699. if (this.enableBlending && this._blendingFactor <= 1.0) {
  28700. if (!this._originalBlendValue) {
  28701. if (destination[path].clone) {
  28702. this._originalBlendValue = destination[path].clone();
  28703. }
  28704. else {
  28705. this._originalBlendValue = destination[path];
  28706. }
  28707. }
  28708. if (this._originalBlendValue.prototype) {
  28709. if (this._originalBlendValue.prototype.Lerp) {
  28710. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  28711. }
  28712. else {
  28713. destination[path] = currentValue;
  28714. }
  28715. }
  28716. else if (this._originalBlendValue.m) {
  28717. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  28718. }
  28719. else {
  28720. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  28721. }
  28722. this._blendingFactor += this.blendingSpeed;
  28723. }
  28724. else {
  28725. destination[path] = currentValue;
  28726. }
  28727. if (this._target.markAsDirty) {
  28728. this._target.markAsDirty(this.targetProperty);
  28729. }
  28730. };
  28731. Animation.prototype.goToFrame = function (frame) {
  28732. if (frame < this._keys[0].frame) {
  28733. frame = this._keys[0].frame;
  28734. }
  28735. else if (frame > this._keys[this._keys.length - 1].frame) {
  28736. frame = this._keys[this._keys.length - 1].frame;
  28737. }
  28738. var currentValue = this._interpolate(frame, 0, this.loopMode);
  28739. this.setValue(currentValue);
  28740. };
  28741. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  28742. if (blend === void 0) { blend = false; }
  28743. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  28744. this._stopped = true;
  28745. return false;
  28746. }
  28747. var returnValue = true;
  28748. // Adding a start key at frame 0 if missing
  28749. if (this._keys[0].frame !== 0) {
  28750. var newKey = { frame: 0, value: this._keys[0].value };
  28751. this._keys.splice(0, 0, newKey);
  28752. }
  28753. // Check limits
  28754. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  28755. from = this._keys[0].frame;
  28756. }
  28757. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  28758. to = this._keys[this._keys.length - 1].frame;
  28759. }
  28760. // Compute ratio
  28761. var range = to - from;
  28762. var offsetValue;
  28763. // ratio represents the frame delta between from and to
  28764. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  28765. var highLimitValue = 0;
  28766. if (ratio > range && !loop) {
  28767. returnValue = false;
  28768. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  28769. }
  28770. else {
  28771. // Get max value if required
  28772. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  28773. var keyOffset = to.toString() + from.toString();
  28774. if (!this._offsetsCache[keyOffset]) {
  28775. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28776. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  28777. switch (this.dataType) {
  28778. // Float
  28779. case Animation.ANIMATIONTYPE_FLOAT:
  28780. this._offsetsCache[keyOffset] = toValue - fromValue;
  28781. break;
  28782. // Quaternion
  28783. case Animation.ANIMATIONTYPE_QUATERNION:
  28784. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28785. break;
  28786. // Vector3
  28787. case Animation.ANIMATIONTYPE_VECTOR3:
  28788. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28789. // Vector2
  28790. case Animation.ANIMATIONTYPE_VECTOR2:
  28791. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28792. // Size
  28793. case Animation.ANIMATIONTYPE_SIZE:
  28794. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28795. // Color3
  28796. case Animation.ANIMATIONTYPE_COLOR3:
  28797. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  28798. default:
  28799. break;
  28800. }
  28801. this._highLimitsCache[keyOffset] = toValue;
  28802. }
  28803. highLimitValue = this._highLimitsCache[keyOffset];
  28804. offsetValue = this._offsetsCache[keyOffset];
  28805. }
  28806. }
  28807. if (offsetValue === undefined) {
  28808. switch (this.dataType) {
  28809. // Float
  28810. case Animation.ANIMATIONTYPE_FLOAT:
  28811. offsetValue = 0;
  28812. break;
  28813. // Quaternion
  28814. case Animation.ANIMATIONTYPE_QUATERNION:
  28815. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  28816. break;
  28817. // Vector3
  28818. case Animation.ANIMATIONTYPE_VECTOR3:
  28819. offsetValue = BABYLON.Vector3.Zero();
  28820. break;
  28821. // Vector2
  28822. case Animation.ANIMATIONTYPE_VECTOR2:
  28823. offsetValue = BABYLON.Vector2.Zero();
  28824. break;
  28825. // Size
  28826. case Animation.ANIMATIONTYPE_SIZE:
  28827. offsetValue = BABYLON.Size.Zero();
  28828. break;
  28829. // Color3
  28830. case Animation.ANIMATIONTYPE_COLOR3:
  28831. offsetValue = BABYLON.Color3.Black();
  28832. }
  28833. }
  28834. // Compute value
  28835. var repeatCount = (ratio / range) >> 0;
  28836. var currentFrame = returnValue ? from + ratio % range : to;
  28837. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  28838. // Set value
  28839. this.setValue(currentValue);
  28840. // Check events
  28841. for (var index = 0; index < this._events.length; index++) {
  28842. if (currentFrame >= this._events[index].frame) {
  28843. var event = this._events[index];
  28844. if (!event.isDone) {
  28845. // If event should be done only once, remove it.
  28846. if (event.onlyOnce) {
  28847. this._events.splice(index, 1);
  28848. index--;
  28849. }
  28850. event.isDone = true;
  28851. event.action();
  28852. } // Don't do anything if the event has already be done.
  28853. }
  28854. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  28855. // reset event, the animation is looping
  28856. this._events[index].isDone = false;
  28857. }
  28858. }
  28859. if (!returnValue) {
  28860. this._stopped = true;
  28861. }
  28862. return returnValue;
  28863. };
  28864. Animation.prototype.serialize = function () {
  28865. var serializationObject = {};
  28866. serializationObject.name = this.name;
  28867. serializationObject.property = this.targetProperty;
  28868. serializationObject.framePerSecond = this.framePerSecond;
  28869. serializationObject.dataType = this.dataType;
  28870. serializationObject.loopBehavior = this.loopMode;
  28871. var dataType = this.dataType;
  28872. serializationObject.keys = [];
  28873. var keys = this.getKeys();
  28874. for (var index = 0; index < keys.length; index++) {
  28875. var animationKey = keys[index];
  28876. var key = {};
  28877. key.frame = animationKey.frame;
  28878. switch (dataType) {
  28879. case Animation.ANIMATIONTYPE_FLOAT:
  28880. key.values = [animationKey.value];
  28881. break;
  28882. case Animation.ANIMATIONTYPE_QUATERNION:
  28883. case Animation.ANIMATIONTYPE_MATRIX:
  28884. case Animation.ANIMATIONTYPE_VECTOR3:
  28885. case Animation.ANIMATIONTYPE_COLOR3:
  28886. key.values = animationKey.value.asArray();
  28887. break;
  28888. }
  28889. serializationObject.keys.push(key);
  28890. }
  28891. serializationObject.ranges = [];
  28892. for (var name in this._ranges) {
  28893. var range = {};
  28894. range.name = name;
  28895. range.from = this._ranges[name].from;
  28896. range.to = this._ranges[name].to;
  28897. serializationObject.ranges.push(range);
  28898. }
  28899. return serializationObject;
  28900. };
  28901. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  28902. get: function () {
  28903. return Animation._ANIMATIONTYPE_FLOAT;
  28904. },
  28905. enumerable: true,
  28906. configurable: true
  28907. });
  28908. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  28909. get: function () {
  28910. return Animation._ANIMATIONTYPE_VECTOR3;
  28911. },
  28912. enumerable: true,
  28913. configurable: true
  28914. });
  28915. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  28916. get: function () {
  28917. return Animation._ANIMATIONTYPE_VECTOR2;
  28918. },
  28919. enumerable: true,
  28920. configurable: true
  28921. });
  28922. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  28923. get: function () {
  28924. return Animation._ANIMATIONTYPE_SIZE;
  28925. },
  28926. enumerable: true,
  28927. configurable: true
  28928. });
  28929. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  28930. get: function () {
  28931. return Animation._ANIMATIONTYPE_QUATERNION;
  28932. },
  28933. enumerable: true,
  28934. configurable: true
  28935. });
  28936. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  28937. get: function () {
  28938. return Animation._ANIMATIONTYPE_MATRIX;
  28939. },
  28940. enumerable: true,
  28941. configurable: true
  28942. });
  28943. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  28944. get: function () {
  28945. return Animation._ANIMATIONTYPE_COLOR3;
  28946. },
  28947. enumerable: true,
  28948. configurable: true
  28949. });
  28950. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  28951. get: function () {
  28952. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  28953. },
  28954. enumerable: true,
  28955. configurable: true
  28956. });
  28957. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  28958. get: function () {
  28959. return Animation._ANIMATIONLOOPMODE_CYCLE;
  28960. },
  28961. enumerable: true,
  28962. configurable: true
  28963. });
  28964. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  28965. get: function () {
  28966. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  28967. },
  28968. enumerable: true,
  28969. configurable: true
  28970. });
  28971. Animation.Parse = function (parsedAnimation) {
  28972. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  28973. var dataType = parsedAnimation.dataType;
  28974. var keys = [];
  28975. var data;
  28976. var index;
  28977. for (index = 0; index < parsedAnimation.keys.length; index++) {
  28978. var key = parsedAnimation.keys[index];
  28979. switch (dataType) {
  28980. case Animation.ANIMATIONTYPE_FLOAT:
  28981. data = key.values[0];
  28982. break;
  28983. case Animation.ANIMATIONTYPE_QUATERNION:
  28984. data = BABYLON.Quaternion.FromArray(key.values);
  28985. break;
  28986. case Animation.ANIMATIONTYPE_MATRIX:
  28987. data = BABYLON.Matrix.FromArray(key.values);
  28988. break;
  28989. case Animation.ANIMATIONTYPE_COLOR3:
  28990. data = BABYLON.Color3.FromArray(key.values);
  28991. break;
  28992. case Animation.ANIMATIONTYPE_VECTOR3:
  28993. default:
  28994. data = BABYLON.Vector3.FromArray(key.values);
  28995. break;
  28996. }
  28997. keys.push({
  28998. frame: key.frame,
  28999. value: data
  29000. });
  29001. }
  29002. animation.setKeys(keys);
  29003. if (parsedAnimation.ranges) {
  29004. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29005. data = parsedAnimation.ranges[index];
  29006. animation.createRange(data.name, data.from, data.to);
  29007. }
  29008. }
  29009. return animation;
  29010. };
  29011. Animation.AppendSerializedAnimations = function (source, destination) {
  29012. if (source.animations) {
  29013. destination.animations = [];
  29014. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29015. var animation = source.animations[animationIndex];
  29016. destination.animations.push(animation.serialize());
  29017. }
  29018. }
  29019. };
  29020. // Statics
  29021. Animation._ANIMATIONTYPE_FLOAT = 0;
  29022. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29023. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29024. Animation._ANIMATIONTYPE_MATRIX = 3;
  29025. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29026. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29027. Animation._ANIMATIONTYPE_SIZE = 6;
  29028. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29029. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29030. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29031. return Animation;
  29032. }());
  29033. BABYLON.Animation = Animation;
  29034. })(BABYLON || (BABYLON = {}));
  29035. var BABYLON;
  29036. (function (BABYLON) {
  29037. var Animatable = (function () {
  29038. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29039. if (fromFrame === void 0) { fromFrame = 0; }
  29040. if (toFrame === void 0) { toFrame = 100; }
  29041. if (loopAnimation === void 0) { loopAnimation = false; }
  29042. if (speedRatio === void 0) { speedRatio = 1.0; }
  29043. this.target = target;
  29044. this.fromFrame = fromFrame;
  29045. this.toFrame = toFrame;
  29046. this.loopAnimation = loopAnimation;
  29047. this.speedRatio = speedRatio;
  29048. this.onAnimationEnd = onAnimationEnd;
  29049. this._animations = new Array();
  29050. this._paused = false;
  29051. this.animationStarted = false;
  29052. if (animations) {
  29053. this.appendAnimations(target, animations);
  29054. }
  29055. this._scene = scene;
  29056. scene._activeAnimatables.push(this);
  29057. }
  29058. // Methods
  29059. Animatable.prototype.getAnimations = function () {
  29060. return this._animations;
  29061. };
  29062. Animatable.prototype.appendAnimations = function (target, animations) {
  29063. for (var index = 0; index < animations.length; index++) {
  29064. var animation = animations[index];
  29065. animation._target = target;
  29066. this._animations.push(animation);
  29067. }
  29068. };
  29069. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29070. var animations = this._animations;
  29071. for (var index = 0; index < animations.length; index++) {
  29072. if (animations[index].targetProperty === property) {
  29073. return animations[index];
  29074. }
  29075. }
  29076. return null;
  29077. };
  29078. Animatable.prototype.reset = function () {
  29079. var animations = this._animations;
  29080. for (var index = 0; index < animations.length; index++) {
  29081. animations[index].reset();
  29082. }
  29083. this._localDelayOffset = null;
  29084. this._pausedDelay = null;
  29085. };
  29086. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29087. var animations = this._animations;
  29088. for (var index = 0; index < animations.length; index++) {
  29089. animations[index].enableBlending = true;
  29090. animations[index].blendingSpeed = blendingSpeed;
  29091. }
  29092. };
  29093. Animatable.prototype.disableBlending = function () {
  29094. var animations = this._animations;
  29095. for (var index = 0; index < animations.length; index++) {
  29096. animations[index].enableBlending = false;
  29097. }
  29098. };
  29099. Animatable.prototype.goToFrame = function (frame) {
  29100. var animations = this._animations;
  29101. for (var index = 0; index < animations.length; index++) {
  29102. animations[index].goToFrame(frame);
  29103. }
  29104. };
  29105. Animatable.prototype.pause = function () {
  29106. if (this._paused) {
  29107. return;
  29108. }
  29109. this._paused = true;
  29110. };
  29111. Animatable.prototype.restart = function () {
  29112. this._paused = false;
  29113. };
  29114. Animatable.prototype.stop = function (animationName) {
  29115. var index = this._scene._activeAnimatables.indexOf(this);
  29116. if (index > -1) {
  29117. var animations = this._animations;
  29118. var numberOfAnimationsStopped = 0;
  29119. for (var index = animations.length - 1; index >= 0; index--) {
  29120. if (typeof animationName === "string" && animations[index].name != animationName) {
  29121. continue;
  29122. }
  29123. animations[index].reset();
  29124. animations.splice(index, 1);
  29125. numberOfAnimationsStopped++;
  29126. }
  29127. if (animations.length == numberOfAnimationsStopped) {
  29128. this._scene._activeAnimatables.splice(index, 1);
  29129. if (this.onAnimationEnd) {
  29130. this.onAnimationEnd();
  29131. }
  29132. }
  29133. }
  29134. };
  29135. Animatable.prototype._animate = function (delay) {
  29136. if (this._paused) {
  29137. this.animationStarted = false;
  29138. if (!this._pausedDelay) {
  29139. this._pausedDelay = delay;
  29140. }
  29141. return true;
  29142. }
  29143. if (!this._localDelayOffset) {
  29144. this._localDelayOffset = delay;
  29145. }
  29146. else if (this._pausedDelay) {
  29147. this._localDelayOffset += delay - this._pausedDelay;
  29148. this._pausedDelay = null;
  29149. }
  29150. // Animating
  29151. var running = false;
  29152. var animations = this._animations;
  29153. var index;
  29154. for (index = 0; index < animations.length; index++) {
  29155. var animation = animations[index];
  29156. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29157. running = running || isRunning;
  29158. }
  29159. this.animationStarted = running;
  29160. if (!running) {
  29161. // Remove from active animatables
  29162. index = this._scene._activeAnimatables.indexOf(this);
  29163. this._scene._activeAnimatables.splice(index, 1);
  29164. }
  29165. if (!running && this.onAnimationEnd) {
  29166. this.onAnimationEnd();
  29167. this.onAnimationEnd = null;
  29168. }
  29169. return running;
  29170. };
  29171. return Animatable;
  29172. }());
  29173. BABYLON.Animatable = Animatable;
  29174. })(BABYLON || (BABYLON = {}));
  29175. var BABYLON;
  29176. (function (BABYLON) {
  29177. var EasingFunction = (function () {
  29178. function EasingFunction() {
  29179. // Properties
  29180. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29181. }
  29182. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29183. get: function () {
  29184. return EasingFunction._EASINGMODE_EASEIN;
  29185. },
  29186. enumerable: true,
  29187. configurable: true
  29188. });
  29189. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29190. get: function () {
  29191. return EasingFunction._EASINGMODE_EASEOUT;
  29192. },
  29193. enumerable: true,
  29194. configurable: true
  29195. });
  29196. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29197. get: function () {
  29198. return EasingFunction._EASINGMODE_EASEINOUT;
  29199. },
  29200. enumerable: true,
  29201. configurable: true
  29202. });
  29203. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29204. var n = Math.min(Math.max(easingMode, 0), 2);
  29205. this._easingMode = n;
  29206. };
  29207. EasingFunction.prototype.getEasingMode = function () {
  29208. return this._easingMode;
  29209. };
  29210. EasingFunction.prototype.easeInCore = function (gradient) {
  29211. throw new Error('You must implement this method');
  29212. };
  29213. EasingFunction.prototype.ease = function (gradient) {
  29214. switch (this._easingMode) {
  29215. case EasingFunction.EASINGMODE_EASEIN:
  29216. return this.easeInCore(gradient);
  29217. case EasingFunction.EASINGMODE_EASEOUT:
  29218. return (1 - this.easeInCore(1 - gradient));
  29219. }
  29220. if (gradient >= 0.5) {
  29221. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29222. }
  29223. return (this.easeInCore(gradient * 2) * 0.5);
  29224. };
  29225. //Statics
  29226. EasingFunction._EASINGMODE_EASEIN = 0;
  29227. EasingFunction._EASINGMODE_EASEOUT = 1;
  29228. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29229. return EasingFunction;
  29230. }());
  29231. BABYLON.EasingFunction = EasingFunction;
  29232. var CircleEase = (function (_super) {
  29233. __extends(CircleEase, _super);
  29234. function CircleEase() {
  29235. _super.apply(this, arguments);
  29236. }
  29237. CircleEase.prototype.easeInCore = function (gradient) {
  29238. gradient = Math.max(0, Math.min(1, gradient));
  29239. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  29240. };
  29241. return CircleEase;
  29242. }(EasingFunction));
  29243. BABYLON.CircleEase = CircleEase;
  29244. var BackEase = (function (_super) {
  29245. __extends(BackEase, _super);
  29246. function BackEase(amplitude) {
  29247. if (amplitude === void 0) { amplitude = 1; }
  29248. _super.call(this);
  29249. this.amplitude = amplitude;
  29250. }
  29251. BackEase.prototype.easeInCore = function (gradient) {
  29252. var num = Math.max(0, this.amplitude);
  29253. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  29254. };
  29255. return BackEase;
  29256. }(EasingFunction));
  29257. BABYLON.BackEase = BackEase;
  29258. var BounceEase = (function (_super) {
  29259. __extends(BounceEase, _super);
  29260. function BounceEase(bounces, bounciness) {
  29261. if (bounces === void 0) { bounces = 3; }
  29262. if (bounciness === void 0) { bounciness = 2; }
  29263. _super.call(this);
  29264. this.bounces = bounces;
  29265. this.bounciness = bounciness;
  29266. }
  29267. BounceEase.prototype.easeInCore = function (gradient) {
  29268. var y = Math.max(0.0, this.bounces);
  29269. var bounciness = this.bounciness;
  29270. if (bounciness <= 1.0) {
  29271. bounciness = 1.001;
  29272. }
  29273. var num9 = Math.pow(bounciness, y);
  29274. var num5 = 1.0 - bounciness;
  29275. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  29276. var num15 = gradient * num4;
  29277. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  29278. var num3 = Math.floor(num65);
  29279. var num13 = num3 + 1.0;
  29280. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  29281. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  29282. var num7 = (num8 + num12) * 0.5;
  29283. var num6 = gradient - num7;
  29284. var num2 = num7 - num8;
  29285. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  29286. };
  29287. return BounceEase;
  29288. }(EasingFunction));
  29289. BABYLON.BounceEase = BounceEase;
  29290. var CubicEase = (function (_super) {
  29291. __extends(CubicEase, _super);
  29292. function CubicEase() {
  29293. _super.apply(this, arguments);
  29294. }
  29295. CubicEase.prototype.easeInCore = function (gradient) {
  29296. return (gradient * gradient * gradient);
  29297. };
  29298. return CubicEase;
  29299. }(EasingFunction));
  29300. BABYLON.CubicEase = CubicEase;
  29301. var ElasticEase = (function (_super) {
  29302. __extends(ElasticEase, _super);
  29303. function ElasticEase(oscillations, springiness) {
  29304. if (oscillations === void 0) { oscillations = 3; }
  29305. if (springiness === void 0) { springiness = 3; }
  29306. _super.call(this);
  29307. this.oscillations = oscillations;
  29308. this.springiness = springiness;
  29309. }
  29310. ElasticEase.prototype.easeInCore = function (gradient) {
  29311. var num2;
  29312. var num3 = Math.max(0.0, this.oscillations);
  29313. var num = Math.max(0.0, this.springiness);
  29314. if (num == 0) {
  29315. num2 = gradient;
  29316. }
  29317. else {
  29318. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  29319. }
  29320. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  29321. };
  29322. return ElasticEase;
  29323. }(EasingFunction));
  29324. BABYLON.ElasticEase = ElasticEase;
  29325. var ExponentialEase = (function (_super) {
  29326. __extends(ExponentialEase, _super);
  29327. function ExponentialEase(exponent) {
  29328. if (exponent === void 0) { exponent = 2; }
  29329. _super.call(this);
  29330. this.exponent = exponent;
  29331. }
  29332. ExponentialEase.prototype.easeInCore = function (gradient) {
  29333. if (this.exponent <= 0) {
  29334. return gradient;
  29335. }
  29336. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  29337. };
  29338. return ExponentialEase;
  29339. }(EasingFunction));
  29340. BABYLON.ExponentialEase = ExponentialEase;
  29341. var PowerEase = (function (_super) {
  29342. __extends(PowerEase, _super);
  29343. function PowerEase(power) {
  29344. if (power === void 0) { power = 2; }
  29345. _super.call(this);
  29346. this.power = power;
  29347. }
  29348. PowerEase.prototype.easeInCore = function (gradient) {
  29349. var y = Math.max(0.0, this.power);
  29350. return Math.pow(gradient, y);
  29351. };
  29352. return PowerEase;
  29353. }(EasingFunction));
  29354. BABYLON.PowerEase = PowerEase;
  29355. var QuadraticEase = (function (_super) {
  29356. __extends(QuadraticEase, _super);
  29357. function QuadraticEase() {
  29358. _super.apply(this, arguments);
  29359. }
  29360. QuadraticEase.prototype.easeInCore = function (gradient) {
  29361. return (gradient * gradient);
  29362. };
  29363. return QuadraticEase;
  29364. }(EasingFunction));
  29365. BABYLON.QuadraticEase = QuadraticEase;
  29366. var QuarticEase = (function (_super) {
  29367. __extends(QuarticEase, _super);
  29368. function QuarticEase() {
  29369. _super.apply(this, arguments);
  29370. }
  29371. QuarticEase.prototype.easeInCore = function (gradient) {
  29372. return (gradient * gradient * gradient * gradient);
  29373. };
  29374. return QuarticEase;
  29375. }(EasingFunction));
  29376. BABYLON.QuarticEase = QuarticEase;
  29377. var QuinticEase = (function (_super) {
  29378. __extends(QuinticEase, _super);
  29379. function QuinticEase() {
  29380. _super.apply(this, arguments);
  29381. }
  29382. QuinticEase.prototype.easeInCore = function (gradient) {
  29383. return (gradient * gradient * gradient * gradient * gradient);
  29384. };
  29385. return QuinticEase;
  29386. }(EasingFunction));
  29387. BABYLON.QuinticEase = QuinticEase;
  29388. var SineEase = (function (_super) {
  29389. __extends(SineEase, _super);
  29390. function SineEase() {
  29391. _super.apply(this, arguments);
  29392. }
  29393. SineEase.prototype.easeInCore = function (gradient) {
  29394. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  29395. };
  29396. return SineEase;
  29397. }(EasingFunction));
  29398. BABYLON.SineEase = SineEase;
  29399. var BezierCurveEase = (function (_super) {
  29400. __extends(BezierCurveEase, _super);
  29401. function BezierCurveEase(x1, y1, x2, y2) {
  29402. if (x1 === void 0) { x1 = 0; }
  29403. if (y1 === void 0) { y1 = 0; }
  29404. if (x2 === void 0) { x2 = 1; }
  29405. if (y2 === void 0) { y2 = 1; }
  29406. _super.call(this);
  29407. this.x1 = x1;
  29408. this.y1 = y1;
  29409. this.x2 = x2;
  29410. this.y2 = y2;
  29411. }
  29412. BezierCurveEase.prototype.easeInCore = function (gradient) {
  29413. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  29414. };
  29415. return BezierCurveEase;
  29416. }(EasingFunction));
  29417. BABYLON.BezierCurveEase = BezierCurveEase;
  29418. })(BABYLON || (BABYLON = {}));
  29419. var BABYLON;
  29420. (function (BABYLON) {
  29421. var Bone = (function (_super) {
  29422. __extends(Bone, _super);
  29423. function Bone(name, skeleton, parentBone, matrix, restPose) {
  29424. _super.call(this, name, skeleton.getScene());
  29425. this.name = name;
  29426. this.children = new Array();
  29427. this.animations = new Array();
  29428. this._worldTransform = new BABYLON.Matrix();
  29429. this._absoluteTransform = new BABYLON.Matrix();
  29430. this._invertedAbsoluteTransform = new BABYLON.Matrix();
  29431. this._scaleMatrix = BABYLON.Matrix.Identity();
  29432. this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  29433. this._skeleton = skeleton;
  29434. this._matrix = matrix;
  29435. this._baseMatrix = matrix;
  29436. this._restPose = restPose ? restPose : matrix.clone();
  29437. skeleton.bones.push(this);
  29438. if (parentBone) {
  29439. this._parent = parentBone;
  29440. parentBone.children.push(this);
  29441. }
  29442. else {
  29443. this._parent = null;
  29444. }
  29445. this._updateDifferenceMatrix();
  29446. }
  29447. // Members
  29448. Bone.prototype.getParent = function () {
  29449. return this._parent;
  29450. };
  29451. Bone.prototype.getLocalMatrix = function () {
  29452. return this._matrix;
  29453. };
  29454. Bone.prototype.getBaseMatrix = function () {
  29455. return this._baseMatrix;
  29456. };
  29457. Bone.prototype.getRestPose = function () {
  29458. return this._restPose;
  29459. };
  29460. Bone.prototype.returnToRest = function () {
  29461. this.updateMatrix(this._restPose.clone());
  29462. };
  29463. Bone.prototype.getWorldMatrix = function () {
  29464. return this._worldTransform;
  29465. };
  29466. Bone.prototype.getInvertedAbsoluteTransform = function () {
  29467. return this._invertedAbsoluteTransform;
  29468. };
  29469. Bone.prototype.getAbsoluteTransform = function () {
  29470. return this._absoluteTransform;
  29471. };
  29472. // Methods
  29473. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  29474. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  29475. this._baseMatrix = matrix.clone();
  29476. this._matrix = matrix.clone();
  29477. this._skeleton._markAsDirty();
  29478. if (updateDifferenceMatrix) {
  29479. this._updateDifferenceMatrix();
  29480. }
  29481. };
  29482. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  29483. if (!rootMatrix) {
  29484. rootMatrix = this._baseMatrix;
  29485. }
  29486. if (this._parent) {
  29487. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29488. }
  29489. else {
  29490. this._absoluteTransform.copyFrom(rootMatrix);
  29491. }
  29492. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  29493. for (var index = 0; index < this.children.length; index++) {
  29494. this.children[index]._updateDifferenceMatrix();
  29495. }
  29496. };
  29497. Bone.prototype.markAsDirty = function () {
  29498. this._currentRenderId++;
  29499. this._skeleton._markAsDirty();
  29500. };
  29501. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  29502. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29503. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  29504. // all animation may be coming from a library skeleton, so may need to create animation
  29505. if (this.animations.length === 0) {
  29506. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  29507. this.animations[0].setKeys([]);
  29508. }
  29509. // get animation info / verify there is such a range from the source bone
  29510. var sourceRange = source.animations[0].getRange(rangeName);
  29511. if (!sourceRange) {
  29512. return false;
  29513. }
  29514. var from = sourceRange.from;
  29515. var to = sourceRange.to;
  29516. var sourceKeys = source.animations[0].getKeys();
  29517. // rescaling prep
  29518. var sourceBoneLength = source.length;
  29519. var sourceParent = source.getParent();
  29520. var parent = this.getParent();
  29521. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  29522. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  29523. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  29524. var destKeys = this.animations[0].getKeys();
  29525. // loop vars declaration
  29526. var orig;
  29527. var origTranslation;
  29528. var mat;
  29529. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  29530. orig = sourceKeys[key];
  29531. if (orig.frame >= from && orig.frame <= to) {
  29532. if (rescaleAsRequired) {
  29533. mat = orig.value.clone();
  29534. // scale based on parent ratio, when bone has parent
  29535. if (parentScalingReqd) {
  29536. origTranslation = mat.getTranslation();
  29537. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  29538. }
  29539. else if (dimensionsScalingReqd) {
  29540. origTranslation = mat.getTranslation();
  29541. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  29542. }
  29543. else {
  29544. mat = orig.value;
  29545. }
  29546. }
  29547. else {
  29548. mat = orig.value;
  29549. }
  29550. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  29551. }
  29552. }
  29553. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  29554. return true;
  29555. };
  29556. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  29557. if (scaleChildren === void 0) { scaleChildren = false; }
  29558. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  29559. };
  29560. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  29561. if (scaleChildren === void 0) { scaleChildren = false; }
  29562. var locMat = this.getLocalMatrix();
  29563. var origLocMat = BABYLON.Tmp.Matrix[0];
  29564. origLocMat.copyFrom(locMat);
  29565. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  29566. origLocMatInv.copyFrom(origLocMat);
  29567. origLocMatInv.invert();
  29568. var scaleMat = BABYLON.Tmp.Matrix[2];
  29569. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  29570. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  29571. this._scaleVector.x *= x;
  29572. this._scaleVector.y *= y;
  29573. this._scaleVector.z *= z;
  29574. locMat.multiplyToRef(origLocMatInv, locMat);
  29575. locMat.multiplyToRef(scaleMat, locMat);
  29576. locMat.multiplyToRef(origLocMat, locMat);
  29577. var parent = this.getParent();
  29578. if (parent) {
  29579. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  29580. }
  29581. else {
  29582. this.getAbsoluteTransform().copyFrom(locMat);
  29583. }
  29584. var len = this.children.length;
  29585. for (var i = 0; i < len; i++) {
  29586. var parentAbsMat = this.children[i]._parent.getAbsoluteTransform();
  29587. this.children[i].getLocalMatrix().multiplyToRef(parentAbsMat, this.children[i].getAbsoluteTransform());
  29588. }
  29589. scaleMat.invert();
  29590. if (this.children[0]) {
  29591. var child = this.children[0];
  29592. var cm = child.getLocalMatrix();
  29593. cm.multiplyToRef(scaleMat, cm);
  29594. var lm = child.getLocalMatrix();
  29595. lm.m[12] *= x;
  29596. lm.m[13] *= y;
  29597. lm.m[14] *= z;
  29598. }
  29599. if (scaleChildren) {
  29600. for (var i = 0; i < len; i++) {
  29601. this.children[i].scale(x, y, z, scaleChildren);
  29602. }
  29603. }
  29604. this.markAsDirty();
  29605. };
  29606. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  29607. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29608. if (mesh === void 0) { mesh = null; }
  29609. var rotMat = BABYLON.Tmp.Matrix[0];
  29610. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  29611. var rotMatInv = BABYLON.Tmp.Matrix[1];
  29612. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  29613. rotMatInv.multiplyToRef(rotMat, rotMat);
  29614. this._rotateWithMatrix(rotMat, space, mesh);
  29615. };
  29616. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  29617. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29618. if (mesh === void 0) { mesh = null; }
  29619. var rmat = BABYLON.Tmp.Matrix[0];
  29620. rmat.m[12] = 0;
  29621. rmat.m[13] = 0;
  29622. rmat.m[14] = 0;
  29623. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  29624. this._rotateWithMatrix(rmat, space, mesh);
  29625. };
  29626. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  29627. var rotMat = BABYLON.Tmp.Matrix[0];
  29628. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  29629. var rotMatInv = BABYLON.Tmp.Matrix[1];
  29630. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  29631. rotMatInv.multiplyToRef(rotMat, rotMat);
  29632. this._rotateWithMatrix(rotMat, space, mesh);
  29633. };
  29634. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  29635. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29636. if (mesh === void 0) { mesh = null; }
  29637. var lmat = this.getLocalMatrix();
  29638. var lx = lmat.m[12];
  29639. var ly = lmat.m[13];
  29640. var lz = lmat.m[14];
  29641. var parent = this.getParent();
  29642. var parentScale = BABYLON.Tmp.Matrix[3];
  29643. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  29644. if (parent) {
  29645. if (space == BABYLON.Space.WORLD) {
  29646. if (mesh) {
  29647. parentScale.copyFrom(mesh.getWorldMatrix());
  29648. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  29649. }
  29650. else {
  29651. parentScale.copyFrom(parent.getAbsoluteTransform());
  29652. }
  29653. }
  29654. else {
  29655. parentScale = parent._scaleMatrix;
  29656. }
  29657. parentScaleInv.copyFrom(parentScale);
  29658. parentScaleInv.invert();
  29659. lmat.multiplyToRef(parentScale, lmat);
  29660. lmat.multiplyToRef(rmat, lmat);
  29661. lmat.multiplyToRef(parentScaleInv, lmat);
  29662. }
  29663. else {
  29664. if (space == BABYLON.Space.WORLD && mesh) {
  29665. parentScale.copyFrom(mesh.getWorldMatrix());
  29666. parentScaleInv.copyFrom(parentScale);
  29667. parentScaleInv.invert();
  29668. lmat.multiplyToRef(parentScale, lmat);
  29669. lmat.multiplyToRef(rmat, lmat);
  29670. lmat.multiplyToRef(parentScaleInv, lmat);
  29671. }
  29672. else {
  29673. lmat.multiplyToRef(rmat, lmat);
  29674. }
  29675. }
  29676. lmat.m[12] = lx;
  29677. lmat.m[13] = ly;
  29678. lmat.m[14] = lz;
  29679. if (parent) {
  29680. var parentAbsMat = this._parent.getAbsoluteTransform();
  29681. lmat.multiplyToRef(parentAbsMat, this.getAbsoluteTransform());
  29682. }
  29683. else {
  29684. this.getAbsoluteTransform().copyFrom(lmat);
  29685. }
  29686. var len = this.children.length;
  29687. for (var i = 0; i < len; i++) {
  29688. var parentAbsMat = this.children[i]._parent.getAbsoluteTransform();
  29689. this.children[i].getLocalMatrix().multiplyToRef(parentAbsMat, this.children[i].getAbsoluteTransform());
  29690. }
  29691. this.markAsDirty();
  29692. };
  29693. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  29694. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  29695. if (mesh === void 0) { mesh = null; }
  29696. if (space == BABYLON.Space.WORLD) {
  29697. rotMatInv.copyFrom(this.getAbsoluteTransform());
  29698. if (mesh) {
  29699. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  29700. }
  29701. rotMatInv.invert();
  29702. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  29703. scaleMatrix.copyFrom(this._scaleMatrix);
  29704. scaleMatrix.m[0] *= -1;
  29705. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  29706. }
  29707. else {
  29708. rotMatInv.copyFrom(this.getLocalMatrix());
  29709. rotMatInv.invert();
  29710. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  29711. scaleMatrix.copyFrom(this._scaleMatrix);
  29712. if (this._parent) {
  29713. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  29714. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  29715. pscaleMatrix.invert();
  29716. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  29717. }
  29718. else {
  29719. scaleMatrix.m[0] *= -1;
  29720. }
  29721. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  29722. }
  29723. };
  29724. Bone.prototype.getScale = function () {
  29725. return this._scaleVector.clone();
  29726. };
  29727. Bone.prototype.getScaleToRef = function (result) {
  29728. result.copyFrom(this._scaleVector);
  29729. };
  29730. Bone.prototype.getAbsolutePosition = function (mesh) {
  29731. if (mesh === void 0) { mesh = null; }
  29732. var pos = BABYLON.Vector3.Zero();
  29733. this.getAbsolutePositionToRef(mesh, pos);
  29734. return pos;
  29735. };
  29736. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  29737. if (mesh === void 0) { mesh = null; }
  29738. this._skeleton.computeAbsoluteTransforms();
  29739. var tmat = BABYLON.Tmp.Matrix[0];
  29740. if (mesh) {
  29741. tmat.copyFrom(this.getAbsoluteTransform());
  29742. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  29743. }
  29744. else {
  29745. tmat = this.getAbsoluteTransform();
  29746. }
  29747. result.x = tmat.m[12];
  29748. result.y = tmat.m[13];
  29749. result.z = tmat.m[14];
  29750. };
  29751. Bone.prototype.computeAbsoluteTransforms = function () {
  29752. if (this._parent) {
  29753. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  29754. }
  29755. else {
  29756. this._absoluteTransform.copyFrom(this._matrix);
  29757. }
  29758. var children = this.children;
  29759. var len = children.length;
  29760. for (var i = 0; i < len; i++) {
  29761. children[i].computeAbsoluteTransforms();
  29762. }
  29763. };
  29764. return Bone;
  29765. }(BABYLON.Node));
  29766. BABYLON.Bone = Bone;
  29767. })(BABYLON || (BABYLON = {}));
  29768. var BABYLON;
  29769. (function (BABYLON) {
  29770. var Skeleton = (function () {
  29771. function Skeleton(name, id, scene) {
  29772. this.name = name;
  29773. this.id = id;
  29774. this.bones = new Array();
  29775. this.needInitialSkinMatrix = false;
  29776. this._isDirty = true;
  29777. this._meshesWithPoseMatrix = new Array();
  29778. this._identity = BABYLON.Matrix.Identity();
  29779. this._ranges = {};
  29780. this._lastAbsoluteTransformsUpdateId = -1;
  29781. this.bones = [];
  29782. this._scene = scene;
  29783. scene.skeletons.push(this);
  29784. //make sure it will recalculate the matrix next time prepare is called.
  29785. this._isDirty = true;
  29786. }
  29787. // Members
  29788. Skeleton.prototype.getTransformMatrices = function (mesh) {
  29789. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  29790. return mesh._bonesTransformMatrices;
  29791. }
  29792. return this._transformMatrices;
  29793. };
  29794. Skeleton.prototype.getScene = function () {
  29795. return this._scene;
  29796. };
  29797. // Methods
  29798. /**
  29799. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29800. */
  29801. Skeleton.prototype.toString = function (fullDetails) {
  29802. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  29803. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29804. if (fullDetails) {
  29805. ret += ", Ranges: {";
  29806. var first = true;
  29807. for (var name_1 in this._ranges) {
  29808. if (first) {
  29809. ret += ", ";
  29810. first = false;
  29811. }
  29812. ret += name_1;
  29813. }
  29814. ret += "}";
  29815. }
  29816. return ret;
  29817. };
  29818. /**
  29819. * Get bone's index searching by name
  29820. * @param {string} name is bone's name to search for
  29821. * @return {number} Indice of the bone. Returns -1 if not found
  29822. */
  29823. Skeleton.prototype.getBoneIndexByName = function (name) {
  29824. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  29825. if (this.bones[boneIndex].name === name) {
  29826. return boneIndex;
  29827. }
  29828. }
  29829. return -1;
  29830. };
  29831. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  29832. // check name not already in use
  29833. if (!this._ranges[name]) {
  29834. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  29835. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29836. if (this.bones[i].animations[0]) {
  29837. this.bones[i].animations[0].createRange(name, from, to);
  29838. }
  29839. }
  29840. }
  29841. };
  29842. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  29843. if (deleteFrames === void 0) { deleteFrames = true; }
  29844. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29845. if (this.bones[i].animations[0]) {
  29846. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  29847. }
  29848. }
  29849. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29850. };
  29851. Skeleton.prototype.getAnimationRange = function (name) {
  29852. return this._ranges[name];
  29853. };
  29854. /**
  29855. * Returns as an Array, all AnimationRanges defined on this skeleton
  29856. */
  29857. Skeleton.prototype.getAnimationRanges = function () {
  29858. var animationRanges = [];
  29859. var name;
  29860. var i = 0;
  29861. for (name in this._ranges) {
  29862. animationRanges[i] = this._ranges[name];
  29863. i++;
  29864. }
  29865. return animationRanges;
  29866. };
  29867. /**
  29868. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  29869. */
  29870. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  29871. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  29872. if (this._ranges[name] || !source.getAnimationRange(name)) {
  29873. return false;
  29874. }
  29875. var ret = true;
  29876. var frameOffset = this._getHighestAnimationFrame() + 1;
  29877. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  29878. var boneDict = {};
  29879. var sourceBones = source.bones;
  29880. var nBones;
  29881. var i;
  29882. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  29883. boneDict[sourceBones[i].name] = sourceBones[i];
  29884. }
  29885. if (this.bones.length !== sourceBones.length) {
  29886. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  29887. ret = false;
  29888. }
  29889. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  29890. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  29891. var boneName = this.bones[i].name;
  29892. var sourceBone = boneDict[boneName];
  29893. if (sourceBone) {
  29894. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  29895. }
  29896. else {
  29897. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  29898. ret = false;
  29899. }
  29900. }
  29901. // do not call createAnimationRange(), since it also is done to bones, which was already done
  29902. var range = source.getAnimationRange(name);
  29903. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  29904. return ret;
  29905. };
  29906. Skeleton.prototype.returnToRest = function () {
  29907. for (var index = 0; index < this.bones.length; index++) {
  29908. this.bones[index].returnToRest();
  29909. }
  29910. };
  29911. Skeleton.prototype._getHighestAnimationFrame = function () {
  29912. var ret = 0;
  29913. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  29914. if (this.bones[i].animations[0]) {
  29915. var highest = this.bones[i].animations[0].getHighestFrame();
  29916. if (ret < highest) {
  29917. ret = highest;
  29918. }
  29919. }
  29920. }
  29921. return ret;
  29922. };
  29923. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  29924. var range = this.getAnimationRange(name);
  29925. if (!range) {
  29926. return null;
  29927. }
  29928. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  29929. };
  29930. Skeleton.prototype._markAsDirty = function () {
  29931. this._isDirty = true;
  29932. };
  29933. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  29934. this._meshesWithPoseMatrix.push(mesh);
  29935. };
  29936. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  29937. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  29938. if (index > -1) {
  29939. this._meshesWithPoseMatrix.splice(index, 1);
  29940. }
  29941. };
  29942. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  29943. for (var index = 0; index < this.bones.length; index++) {
  29944. var bone = this.bones[index];
  29945. var parentBone = bone.getParent();
  29946. if (parentBone) {
  29947. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  29948. }
  29949. else {
  29950. if (initialSkinMatrix) {
  29951. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  29952. }
  29953. else {
  29954. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  29955. }
  29956. }
  29957. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  29958. }
  29959. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  29960. };
  29961. Skeleton.prototype.prepare = function () {
  29962. if (!this._isDirty) {
  29963. return;
  29964. }
  29965. if (this.needInitialSkinMatrix) {
  29966. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  29967. var mesh = this._meshesWithPoseMatrix[index];
  29968. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  29969. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29970. }
  29971. var poseMatrix = mesh.getPoseMatrix();
  29972. // Prepare bones
  29973. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  29974. var bone = this.bones[boneIndex];
  29975. if (!bone.getParent()) {
  29976. var matrix = bone.getBaseMatrix();
  29977. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  29978. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  29979. }
  29980. }
  29981. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  29982. }
  29983. }
  29984. else {
  29985. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  29986. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  29987. }
  29988. this._computeTransformMatrices(this._transformMatrices, null);
  29989. }
  29990. this._isDirty = false;
  29991. this._scene._activeBones.addCount(this.bones.length, false);
  29992. };
  29993. Skeleton.prototype.getAnimatables = function () {
  29994. if (!this._animatables || this._animatables.length !== this.bones.length) {
  29995. this._animatables = [];
  29996. for (var index = 0; index < this.bones.length; index++) {
  29997. this._animatables.push(this.bones[index]);
  29998. }
  29999. }
  30000. return this._animatables;
  30001. };
  30002. Skeleton.prototype.clone = function (name, id) {
  30003. var result = new Skeleton(name, id || name, this._scene);
  30004. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  30005. for (var index = 0; index < this.bones.length; index++) {
  30006. var source = this.bones[index];
  30007. var parentBone = null;
  30008. if (source.getParent()) {
  30009. var parentIndex = this.bones.indexOf(source.getParent());
  30010. parentBone = result.bones[parentIndex];
  30011. }
  30012. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  30013. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  30014. }
  30015. if (this._ranges) {
  30016. result._ranges = {};
  30017. for (var rangeName in this._ranges) {
  30018. result._ranges[rangeName] = this._ranges[rangeName].clone();
  30019. }
  30020. }
  30021. this._isDirty = true;
  30022. return result;
  30023. };
  30024. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  30025. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  30026. this.bones.forEach(function (bone) {
  30027. bone.animations.forEach(function (animation) {
  30028. animation.enableBlending = true;
  30029. animation.blendingSpeed = blendingSpeed;
  30030. });
  30031. });
  30032. };
  30033. Skeleton.prototype.dispose = function () {
  30034. this._meshesWithPoseMatrix = [];
  30035. // Animations
  30036. this.getScene().stopAnimation(this);
  30037. // Remove from scene
  30038. this.getScene().removeSkeleton(this);
  30039. };
  30040. Skeleton.prototype.serialize = function () {
  30041. var serializationObject = {};
  30042. serializationObject.name = this.name;
  30043. serializationObject.id = this.id;
  30044. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  30045. serializationObject.bones = [];
  30046. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  30047. for (var index = 0; index < this.bones.length; index++) {
  30048. var bone = this.bones[index];
  30049. var serializedBone = {
  30050. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  30051. name: bone.name,
  30052. matrix: bone.getLocalMatrix().toArray(),
  30053. rest: bone.getRestPose().toArray()
  30054. };
  30055. serializationObject.bones.push(serializedBone);
  30056. if (bone.length) {
  30057. serializedBone.length = bone.length;
  30058. }
  30059. if (bone.animations && bone.animations.length > 0) {
  30060. serializedBone.animation = bone.animations[0].serialize();
  30061. }
  30062. serializationObject.ranges = [];
  30063. for (var name in this._ranges) {
  30064. var range = {};
  30065. range.name = name;
  30066. range.from = this._ranges[name].from;
  30067. range.to = this._ranges[name].to;
  30068. serializationObject.ranges.push(range);
  30069. }
  30070. }
  30071. return serializationObject;
  30072. };
  30073. Skeleton.Parse = function (parsedSkeleton, scene) {
  30074. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  30075. if (parsedSkeleton.dimensionsAtRest) {
  30076. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  30077. }
  30078. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  30079. var index;
  30080. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  30081. var parsedBone = parsedSkeleton.bones[index];
  30082. var parentBone = null;
  30083. if (parsedBone.parentBoneIndex > -1) {
  30084. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  30085. }
  30086. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  30087. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  30088. if (parsedBone.length) {
  30089. bone.length = parsedBone.length;
  30090. }
  30091. if (parsedBone.animation) {
  30092. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  30093. }
  30094. }
  30095. // placed after bones, so createAnimationRange can cascade down
  30096. if (parsedSkeleton.ranges) {
  30097. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  30098. var data = parsedSkeleton.ranges[index];
  30099. skeleton.createAnimationRange(data.name, data.from, data.to);
  30100. }
  30101. }
  30102. return skeleton;
  30103. };
  30104. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  30105. if (forceUpdate === void 0) { forceUpdate = false; }
  30106. var renderId = this._scene.getRenderId();
  30107. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  30108. this.bones[0].computeAbsoluteTransforms();
  30109. this._lastAbsoluteTransformsUpdateId = renderId;
  30110. }
  30111. };
  30112. return Skeleton;
  30113. }());
  30114. BABYLON.Skeleton = Skeleton;
  30115. })(BABYLON || (BABYLON = {}));
  30116. var BABYLON;
  30117. (function (BABYLON) {
  30118. var PostProcess = (function () {
  30119. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  30120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  30121. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  30122. this.name = name;
  30123. this.width = -1;
  30124. this.height = -1;
  30125. /*
  30126. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  30127. Can only be used on a single postprocess or on the last one of a chain.
  30128. */
  30129. this.enablePixelPerfectMode = false;
  30130. this._reusable = false;
  30131. this._textures = new BABYLON.SmartArray(2);
  30132. this._currentRenderTextureInd = 0;
  30133. this._scaleRatio = new BABYLON.Vector2(1, 1);
  30134. // Events
  30135. /**
  30136. * An event triggered when the postprocess is activated.
  30137. * @type {BABYLON.Observable}
  30138. */
  30139. this.onActivateObservable = new BABYLON.Observable();
  30140. /**
  30141. * An event triggered when the postprocess changes its size.
  30142. * @type {BABYLON.Observable}
  30143. */
  30144. this.onSizeChangedObservable = new BABYLON.Observable();
  30145. /**
  30146. * An event triggered when the postprocess applies its effect.
  30147. * @type {BABYLON.Observable}
  30148. */
  30149. this.onApplyObservable = new BABYLON.Observable();
  30150. /**
  30151. * An event triggered before rendering the postprocess
  30152. * @type {BABYLON.Observable}
  30153. */
  30154. this.onBeforeRenderObservable = new BABYLON.Observable();
  30155. /**
  30156. * An event triggered after rendering the postprocess
  30157. * @type {BABYLON.Observable}
  30158. */
  30159. this.onAfterRenderObservable = new BABYLON.Observable();
  30160. if (camera != null) {
  30161. this._camera = camera;
  30162. this._scene = camera.getScene();
  30163. camera.attachPostProcess(this);
  30164. this._engine = this._scene.getEngine();
  30165. }
  30166. else {
  30167. this._engine = engine;
  30168. }
  30169. this._options = options;
  30170. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  30171. this._reusable = reusable || false;
  30172. this._textureType = textureType;
  30173. this._samplers = samplers || [];
  30174. this._samplers.push("textureSampler");
  30175. this._fragmentUrl = fragmentUrl;
  30176. this._parameters = parameters || [];
  30177. this._parameters.push("scale");
  30178. this.updateEffect(defines);
  30179. }
  30180. Object.defineProperty(PostProcess.prototype, "onActivate", {
  30181. set: function (callback) {
  30182. if (this._onActivateObserver) {
  30183. this.onActivateObservable.remove(this._onActivateObserver);
  30184. }
  30185. this._onActivateObserver = this.onActivateObservable.add(callback);
  30186. },
  30187. enumerable: true,
  30188. configurable: true
  30189. });
  30190. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  30191. set: function (callback) {
  30192. if (this._onSizeChangedObserver) {
  30193. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  30194. }
  30195. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  30196. },
  30197. enumerable: true,
  30198. configurable: true
  30199. });
  30200. Object.defineProperty(PostProcess.prototype, "onApply", {
  30201. set: function (callback) {
  30202. if (this._onApplyObserver) {
  30203. this.onApplyObservable.remove(this._onApplyObserver);
  30204. }
  30205. this._onApplyObserver = this.onApplyObservable.add(callback);
  30206. },
  30207. enumerable: true,
  30208. configurable: true
  30209. });
  30210. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  30211. set: function (callback) {
  30212. if (this._onBeforeRenderObserver) {
  30213. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  30214. }
  30215. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  30216. },
  30217. enumerable: true,
  30218. configurable: true
  30219. });
  30220. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  30221. set: function (callback) {
  30222. if (this._onAfterRenderObserver) {
  30223. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  30224. }
  30225. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  30226. },
  30227. enumerable: true,
  30228. configurable: true
  30229. });
  30230. PostProcess.prototype.updateEffect = function (defines) {
  30231. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  30232. };
  30233. PostProcess.prototype.isReusable = function () {
  30234. return this._reusable;
  30235. };
  30236. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  30237. PostProcess.prototype.markTextureDirty = function () {
  30238. this.width = -1;
  30239. };
  30240. PostProcess.prototype.activate = function (camera, sourceTexture) {
  30241. camera = camera || this._camera;
  30242. var scene = camera.getScene();
  30243. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  30244. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  30245. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  30246. var desiredWidth = this._options.width || requiredWidth;
  30247. var desiredHeight = this._options.height || requiredHeight;
  30248. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  30249. if (!this._options.width) {
  30250. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  30251. }
  30252. if (!this._options.height) {
  30253. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  30254. }
  30255. }
  30256. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  30257. if (this._textures.length > 0) {
  30258. for (var i = 0; i < this._textures.length; i++) {
  30259. this._engine._releaseTexture(this._textures.data[i]);
  30260. }
  30261. this._textures.reset();
  30262. }
  30263. this.width = desiredWidth;
  30264. this.height = desiredHeight;
  30265. var textureSize = { width: this.width, height: this.height };
  30266. var textureOptions = {
  30267. generateMipMaps: false,
  30268. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  30269. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  30270. samplingMode: this.renderTargetSamplingMode,
  30271. type: this._textureType
  30272. };
  30273. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  30274. if (this._reusable) {
  30275. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  30276. }
  30277. this.onSizeChangedObservable.notifyObservers(this);
  30278. }
  30279. if (this.enablePixelPerfectMode) {
  30280. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  30281. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  30282. }
  30283. else {
  30284. this._scaleRatio.copyFromFloats(1, 1);
  30285. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  30286. }
  30287. this.onActivateObservable.notifyObservers(camera);
  30288. // Clear
  30289. if (this.clearColor) {
  30290. this._engine.clear(this.clearColor, true, true, true);
  30291. }
  30292. else {
  30293. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  30294. }
  30295. if (this._reusable) {
  30296. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  30297. }
  30298. };
  30299. Object.defineProperty(PostProcess.prototype, "isSupported", {
  30300. get: function () {
  30301. return this._effect.isSupported;
  30302. },
  30303. enumerable: true,
  30304. configurable: true
  30305. });
  30306. PostProcess.prototype.apply = function () {
  30307. // Check
  30308. if (!this._effect.isReady())
  30309. return null;
  30310. // States
  30311. this._engine.enableEffect(this._effect);
  30312. this._engine.setState(false);
  30313. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  30314. this._engine.setDepthBuffer(false);
  30315. this._engine.setDepthWrite(false);
  30316. // Texture
  30317. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  30318. // Parameters
  30319. this._effect.setVector2("scale", this._scaleRatio);
  30320. this.onApplyObservable.notifyObservers(this._effect);
  30321. return this._effect;
  30322. };
  30323. PostProcess.prototype.dispose = function (camera) {
  30324. camera = camera || this._camera;
  30325. if (this._textures.length > 0) {
  30326. for (var i = 0; i < this._textures.length; i++) {
  30327. this._engine._releaseTexture(this._textures.data[i]);
  30328. }
  30329. this._textures.reset();
  30330. }
  30331. if (!camera) {
  30332. return;
  30333. }
  30334. camera.detachPostProcess(this);
  30335. var index = camera._postProcesses.indexOf(this);
  30336. if (index === 0 && camera._postProcesses.length > 0) {
  30337. this._camera._postProcesses[0].markTextureDirty();
  30338. }
  30339. this.onActivateObservable.clear();
  30340. this.onAfterRenderObservable.clear();
  30341. this.onApplyObservable.clear();
  30342. this.onBeforeRenderObservable.clear();
  30343. this.onSizeChangedObservable.clear();
  30344. };
  30345. return PostProcess;
  30346. }());
  30347. BABYLON.PostProcess = PostProcess;
  30348. })(BABYLON || (BABYLON = {}));
  30349. var BABYLON;
  30350. (function (BABYLON) {
  30351. var PostProcessManager = (function () {
  30352. function PostProcessManager(scene) {
  30353. this._vertexBuffers = {};
  30354. this._scene = scene;
  30355. }
  30356. PostProcessManager.prototype._prepareBuffers = function () {
  30357. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  30358. return;
  30359. }
  30360. // VBO
  30361. var vertices = [];
  30362. vertices.push(1, 1);
  30363. vertices.push(-1, 1);
  30364. vertices.push(-1, -1);
  30365. vertices.push(1, -1);
  30366. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  30367. // Indices
  30368. var indices = [];
  30369. indices.push(0);
  30370. indices.push(1);
  30371. indices.push(2);
  30372. indices.push(0);
  30373. indices.push(2);
  30374. indices.push(3);
  30375. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  30376. };
  30377. // Methods
  30378. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  30379. var postProcesses = this._scene.activeCamera._postProcesses;
  30380. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30381. return false;
  30382. }
  30383. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  30384. return true;
  30385. };
  30386. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  30387. var engine = this._scene.getEngine();
  30388. for (var index = 0; index < postProcesses.length; index++) {
  30389. if (index < postProcesses.length - 1) {
  30390. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30391. }
  30392. else {
  30393. if (targetTexture) {
  30394. engine.bindFramebuffer(targetTexture);
  30395. }
  30396. else {
  30397. engine.restoreDefaultFramebuffer();
  30398. }
  30399. }
  30400. var pp = postProcesses[index];
  30401. var effect = pp.apply();
  30402. if (effect) {
  30403. pp.onBeforeRenderObservable.notifyObservers(effect);
  30404. // VBOs
  30405. this._prepareBuffers();
  30406. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30407. // Draw order
  30408. engine.draw(true, 0, 6);
  30409. pp.onAfterRenderObservable.notifyObservers(effect);
  30410. }
  30411. }
  30412. // Restore depth buffer
  30413. engine.setDepthBuffer(true);
  30414. engine.setDepthWrite(true);
  30415. };
  30416. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  30417. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  30418. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  30419. return;
  30420. }
  30421. var engine = this._scene.getEngine();
  30422. for (var index = 0, len = postProcesses.length; index < len; index++) {
  30423. if (index < len - 1) {
  30424. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  30425. }
  30426. else {
  30427. if (targetTexture) {
  30428. engine.bindFramebuffer(targetTexture, faceIndex);
  30429. }
  30430. else {
  30431. engine.restoreDefaultFramebuffer();
  30432. }
  30433. }
  30434. if (doNotPresent) {
  30435. break;
  30436. }
  30437. var pp = postProcesses[index];
  30438. var effect = pp.apply();
  30439. if (effect) {
  30440. pp.onBeforeRenderObservable.notifyObservers(effect);
  30441. // VBOs
  30442. this._prepareBuffers();
  30443. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  30444. // Draw order
  30445. engine.draw(true, 0, 6);
  30446. pp.onAfterRenderObservable.notifyObservers(effect);
  30447. }
  30448. }
  30449. // Restore depth buffer
  30450. engine.setDepthBuffer(true);
  30451. engine.setDepthWrite(true);
  30452. };
  30453. PostProcessManager.prototype.dispose = function () {
  30454. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  30455. if (buffer) {
  30456. buffer.dispose();
  30457. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  30458. }
  30459. if (this._indexBuffer) {
  30460. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  30461. this._indexBuffer = null;
  30462. }
  30463. };
  30464. return PostProcessManager;
  30465. }());
  30466. BABYLON.PostProcessManager = PostProcessManager;
  30467. })(BABYLON || (BABYLON = {}));
  30468. var BABYLON;
  30469. (function (BABYLON) {
  30470. var PassPostProcess = (function (_super) {
  30471. __extends(PassPostProcess, _super);
  30472. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  30473. _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable);
  30474. }
  30475. return PassPostProcess;
  30476. }(BABYLON.PostProcess));
  30477. BABYLON.PassPostProcess = PassPostProcess;
  30478. })(BABYLON || (BABYLON = {}));
  30479. var BABYLON;
  30480. (function (BABYLON) {
  30481. /**
  30482. * This is a holder class for the physics joint created by the physics plugin.
  30483. * It holds a set of functions to control the underlying joint.
  30484. */
  30485. var PhysicsJoint = (function () {
  30486. function PhysicsJoint(type, jointData) {
  30487. this.type = type;
  30488. this.jointData = jointData;
  30489. jointData.nativeParams = jointData.nativeParams || {};
  30490. }
  30491. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  30492. get: function () {
  30493. return this._physicsJoint;
  30494. },
  30495. set: function (newJoint) {
  30496. if (this._physicsJoint) {
  30497. }
  30498. this._physicsJoint = newJoint;
  30499. },
  30500. enumerable: true,
  30501. configurable: true
  30502. });
  30503. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  30504. set: function (physicsPlugin) {
  30505. this._physicsPlugin = physicsPlugin;
  30506. },
  30507. enumerable: true,
  30508. configurable: true
  30509. });
  30510. /**
  30511. * Execute a function that is physics-plugin specific.
  30512. * @param {Function} func the function that will be executed.
  30513. * It accepts two parameters: the physics world and the physics joint.
  30514. */
  30515. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  30516. func(this._physicsPlugin.world, this._physicsJoint);
  30517. };
  30518. //TODO check if the native joints are the same
  30519. //Joint Types
  30520. PhysicsJoint.DistanceJoint = 0;
  30521. PhysicsJoint.HingeJoint = 1;
  30522. PhysicsJoint.BallAndSocketJoint = 2;
  30523. PhysicsJoint.WheelJoint = 3;
  30524. PhysicsJoint.SliderJoint = 4;
  30525. //OIMO
  30526. PhysicsJoint.PrismaticJoint = 5;
  30527. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  30528. PhysicsJoint.UniversalJoint = 6;
  30529. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  30530. //Cannon
  30531. //Similar to a Ball-Joint. Different in params
  30532. PhysicsJoint.PointToPointJoint = 8;
  30533. //Cannon only at the moment
  30534. PhysicsJoint.SpringJoint = 9;
  30535. PhysicsJoint.LockJoint = 10;
  30536. return PhysicsJoint;
  30537. }());
  30538. BABYLON.PhysicsJoint = PhysicsJoint;
  30539. /**
  30540. * A class representing a physics distance joint.
  30541. */
  30542. var DistanceJoint = (function (_super) {
  30543. __extends(DistanceJoint, _super);
  30544. function DistanceJoint(jointData) {
  30545. _super.call(this, PhysicsJoint.DistanceJoint, jointData);
  30546. }
  30547. /**
  30548. * Update the predefined distance.
  30549. */
  30550. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  30551. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  30552. };
  30553. return DistanceJoint;
  30554. }(PhysicsJoint));
  30555. BABYLON.DistanceJoint = DistanceJoint;
  30556. var MotorEnabledJoint = (function (_super) {
  30557. __extends(MotorEnabledJoint, _super);
  30558. function MotorEnabledJoint(type, jointData) {
  30559. _super.call(this, type, jointData);
  30560. }
  30561. /**
  30562. * Set the motor values.
  30563. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30564. * @param {number} force the force to apply
  30565. * @param {number} maxForce max force for this motor.
  30566. */
  30567. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  30568. this._physicsPlugin.setMotor(this, force, maxForce);
  30569. };
  30570. /**
  30571. * Set the motor's limits.
  30572. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30573. */
  30574. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30575. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30576. };
  30577. return MotorEnabledJoint;
  30578. }(PhysicsJoint));
  30579. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  30580. /**
  30581. * This class represents a single hinge physics joint
  30582. */
  30583. var HingeJoint = (function (_super) {
  30584. __extends(HingeJoint, _super);
  30585. function HingeJoint(jointData) {
  30586. _super.call(this, PhysicsJoint.HingeJoint, jointData);
  30587. }
  30588. /**
  30589. * Set the motor values.
  30590. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30591. * @param {number} force the force to apply
  30592. * @param {number} maxForce max force for this motor.
  30593. */
  30594. HingeJoint.prototype.setMotor = function (force, maxForce) {
  30595. this._physicsPlugin.setMotor(this, force, maxForce);
  30596. };
  30597. /**
  30598. * Set the motor's limits.
  30599. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30600. */
  30601. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  30602. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  30603. };
  30604. return HingeJoint;
  30605. }(MotorEnabledJoint));
  30606. BABYLON.HingeJoint = HingeJoint;
  30607. /**
  30608. * This class represents a dual hinge physics joint (same as wheel joint)
  30609. */
  30610. var Hinge2Joint = (function (_super) {
  30611. __extends(Hinge2Joint, _super);
  30612. function Hinge2Joint(jointData) {
  30613. _super.call(this, PhysicsJoint.Hinge2Joint, jointData);
  30614. }
  30615. /**
  30616. * Set the motor values.
  30617. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30618. * @param {number} force the force to apply
  30619. * @param {number} maxForce max force for this motor.
  30620. * @param {motorIndex} the motor's index, 0 or 1.
  30621. */
  30622. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  30623. if (motorIndex === void 0) { motorIndex = 0; }
  30624. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  30625. };
  30626. /**
  30627. * Set the motor limits.
  30628. * Attention, this function is plugin specific. Engines won't react 100% the same.
  30629. * @param {number} upperLimit the upper limit
  30630. * @param {number} lowerLimit lower limit
  30631. * @param {motorIndex} the motor's index, 0 or 1.
  30632. */
  30633. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  30634. if (motorIndex === void 0) { motorIndex = 0; }
  30635. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  30636. };
  30637. return Hinge2Joint;
  30638. }(MotorEnabledJoint));
  30639. BABYLON.Hinge2Joint = Hinge2Joint;
  30640. })(BABYLON || (BABYLON = {}));
  30641. var BABYLON;
  30642. (function (BABYLON) {
  30643. var PhysicsImpostor = (function () {
  30644. function PhysicsImpostor(object, type, _options, _scene) {
  30645. var _this = this;
  30646. if (_options === void 0) { _options = { mass: 0 }; }
  30647. this.object = object;
  30648. this.type = type;
  30649. this._options = _options;
  30650. this._scene = _scene;
  30651. this._bodyUpdateRequired = false;
  30652. this._onBeforePhysicsStepCallbacks = new Array();
  30653. this._onAfterPhysicsStepCallbacks = new Array();
  30654. this._onPhysicsCollideCallbacks = [];
  30655. this._deltaPosition = BABYLON.Vector3.Zero();
  30656. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  30657. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  30658. /**
  30659. * this function is executed by the physics engine.
  30660. */
  30661. this.beforeStep = function () {
  30662. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  30663. //conjugate deltaRotation
  30664. if (_this._deltaRotationConjugated) {
  30665. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  30666. }
  30667. else {
  30668. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  30669. }
  30670. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  30671. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  30672. func(_this);
  30673. });
  30674. };
  30675. /**
  30676. * this function is executed by the physics engine.
  30677. */
  30678. this.afterStep = function () {
  30679. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  30680. func(_this);
  30681. });
  30682. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  30683. _this.object.position.addInPlace(_this._deltaPosition);
  30684. if (_this._deltaRotation) {
  30685. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  30686. }
  30687. };
  30688. //event and body object due to cannon's event-based architecture.
  30689. this.onCollide = function (e) {
  30690. if (!_this._onPhysicsCollideCallbacks.length)
  30691. return;
  30692. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  30693. if (otherImpostor) {
  30694. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  30695. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  30696. }).forEach(function (obj) {
  30697. obj.callback(_this, otherImpostor);
  30698. });
  30699. }
  30700. };
  30701. //sanity check!
  30702. if (!this.object) {
  30703. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  30704. return;
  30705. }
  30706. //legacy support for old syntax.
  30707. if (!this._scene && object.getScene) {
  30708. this._scene = object.getScene();
  30709. }
  30710. this._physicsEngine = this._scene.getPhysicsEngine();
  30711. if (!this._physicsEngine) {
  30712. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  30713. }
  30714. else {
  30715. //set the object's quaternion, if not set
  30716. if (!this.object.rotationQuaternion) {
  30717. if (this.object.rotation) {
  30718. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  30719. }
  30720. else {
  30721. this.object.rotationQuaternion = new BABYLON.Quaternion();
  30722. }
  30723. }
  30724. //default options params
  30725. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  30726. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  30727. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  30728. this._joints = [];
  30729. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  30730. if (!this.object.parent) {
  30731. this._init();
  30732. }
  30733. }
  30734. }
  30735. /**
  30736. * This function will completly initialize this impostor.
  30737. * It will create a new body - but only if this mesh has no parent.
  30738. * If it has, this impostor will not be used other than to define the impostor
  30739. * of the child mesh.
  30740. */
  30741. PhysicsImpostor.prototype._init = function () {
  30742. this._physicsEngine.removeImpostor(this);
  30743. this.physicsBody = null;
  30744. this._parent = this._parent || this._getPhysicsParent();
  30745. if (!this.parent) {
  30746. this._physicsEngine.addImpostor(this);
  30747. }
  30748. };
  30749. PhysicsImpostor.prototype._getPhysicsParent = function () {
  30750. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  30751. var parentMesh = this.object.parent;
  30752. return parentMesh.physicsImpostor;
  30753. }
  30754. return;
  30755. };
  30756. /**
  30757. * Should a new body be generated.
  30758. */
  30759. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  30760. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  30761. };
  30762. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  30763. this.forceUpdate();
  30764. };
  30765. /**
  30766. * Force a regeneration of this or the parent's impostor's body.
  30767. * Use under cautious - This will remove all joints already implemented.
  30768. */
  30769. PhysicsImpostor.prototype.forceUpdate = function () {
  30770. this._init();
  30771. if (this.parent) {
  30772. this.parent.forceUpdate();
  30773. }
  30774. };
  30775. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  30776. /*public get mesh(): AbstractMesh {
  30777. return this._mesh;
  30778. }*/
  30779. /**
  30780. * Gets the body that holds this impostor. Either its own, or its parent.
  30781. */
  30782. get: function () {
  30783. return this._parent ? this._parent.physicsBody : this._physicsBody;
  30784. },
  30785. /**
  30786. * Set the physics body. Used mainly by the physics engine/plugin
  30787. */
  30788. set: function (physicsBody) {
  30789. if (this._physicsBody) {
  30790. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  30791. }
  30792. this._physicsBody = physicsBody;
  30793. this.resetUpdateFlags();
  30794. },
  30795. enumerable: true,
  30796. configurable: true
  30797. });
  30798. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  30799. get: function () {
  30800. return this._parent;
  30801. },
  30802. set: function (value) {
  30803. this._parent = value;
  30804. },
  30805. enumerable: true,
  30806. configurable: true
  30807. });
  30808. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  30809. this._bodyUpdateRequired = false;
  30810. };
  30811. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  30812. if (this.object.getBoundingInfo) {
  30813. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  30814. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  30815. }
  30816. else {
  30817. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  30818. }
  30819. };
  30820. PhysicsImpostor.prototype.getObjectCenter = function () {
  30821. if (this.object.getBoundingInfo) {
  30822. return this.object.getBoundingInfo().boundingBox.center;
  30823. }
  30824. else {
  30825. return this.object.position;
  30826. }
  30827. };
  30828. /**
  30829. * Get a specific parametes from the options parameter.
  30830. */
  30831. PhysicsImpostor.prototype.getParam = function (paramName) {
  30832. return this._options[paramName];
  30833. };
  30834. /**
  30835. * Sets a specific parameter in the options given to the physics plugin
  30836. */
  30837. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  30838. this._options[paramName] = value;
  30839. this._bodyUpdateRequired = true;
  30840. };
  30841. /**
  30842. * Specifically change the body's mass option. Won't recreate the physics body object
  30843. */
  30844. PhysicsImpostor.prototype.setMass = function (mass) {
  30845. if (this.getParam("mass") !== mass) {
  30846. this.setParam("mass", mass);
  30847. }
  30848. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  30849. };
  30850. PhysicsImpostor.prototype.getLinearVelocity = function () {
  30851. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  30852. };
  30853. /**
  30854. * Set the body's linear velocity.
  30855. */
  30856. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  30857. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  30858. };
  30859. PhysicsImpostor.prototype.getAngularVelocity = function () {
  30860. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  30861. };
  30862. /**
  30863. * Set the body's linear velocity.
  30864. */
  30865. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  30866. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  30867. };
  30868. /**
  30869. * Execute a function with the physics plugin native code.
  30870. * Provide a function the will have two variables - the world object and the physics body object.
  30871. */
  30872. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  30873. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  30874. };
  30875. /**
  30876. * Register a function that will be executed before the physics world is stepping forward.
  30877. */
  30878. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  30879. this._onBeforePhysicsStepCallbacks.push(func);
  30880. };
  30881. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  30882. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  30883. if (index > -1) {
  30884. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  30885. }
  30886. else {
  30887. BABYLON.Tools.Warn("Function to remove was not found");
  30888. }
  30889. };
  30890. /**
  30891. * Register a function that will be executed after the physics step
  30892. */
  30893. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  30894. this._onAfterPhysicsStepCallbacks.push(func);
  30895. };
  30896. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  30897. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  30898. if (index > -1) {
  30899. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  30900. }
  30901. else {
  30902. BABYLON.Tools.Warn("Function to remove was not found");
  30903. }
  30904. };
  30905. /**
  30906. * register a function that will be executed when this impostor collides against a different body.
  30907. */
  30908. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  30909. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30910. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  30911. };
  30912. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  30913. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  30914. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  30915. if (index > -1) {
  30916. this._onPhysicsCollideCallbacks.splice(index, 1);
  30917. }
  30918. else {
  30919. BABYLON.Tools.Warn("Function to remove was not found");
  30920. }
  30921. };
  30922. /**
  30923. * Apply a force
  30924. */
  30925. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  30926. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  30927. };
  30928. /**
  30929. * Apply an impulse
  30930. */
  30931. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  30932. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  30933. };
  30934. /**
  30935. * A help function to create a joint.
  30936. */
  30937. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  30938. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  30939. this.addJoint(otherImpostor, joint);
  30940. };
  30941. /**
  30942. * Add a joint to this impostor with a different impostor.
  30943. */
  30944. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  30945. this._joints.push({
  30946. otherImpostor: otherImpostor,
  30947. joint: joint
  30948. });
  30949. this._physicsEngine.addJoint(this, otherImpostor, joint);
  30950. };
  30951. /**
  30952. * Will keep this body still, in a sleep mode.
  30953. */
  30954. PhysicsImpostor.prototype.sleep = function () {
  30955. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  30956. };
  30957. /**
  30958. * Wake the body up.
  30959. */
  30960. PhysicsImpostor.prototype.wakeUp = function () {
  30961. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  30962. };
  30963. PhysicsImpostor.prototype.clone = function (newObject) {
  30964. if (!newObject)
  30965. return null;
  30966. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  30967. };
  30968. PhysicsImpostor.prototype.dispose = function () {
  30969. var _this = this;
  30970. //no dispose if no physics engine is available.
  30971. if (!this._physicsEngine) {
  30972. return;
  30973. }
  30974. this._joints.forEach(function (j) {
  30975. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  30976. });
  30977. //dispose the physics body
  30978. this._physicsEngine.removeImpostor(this);
  30979. if (this.parent) {
  30980. this.parent.forceUpdate();
  30981. }
  30982. else {
  30983. }
  30984. };
  30985. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  30986. this._deltaPosition.copyFrom(position);
  30987. };
  30988. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  30989. if (!this._deltaRotation) {
  30990. this._deltaRotation = new BABYLON.Quaternion();
  30991. }
  30992. this._deltaRotation.copyFrom(rotation);
  30993. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  30994. };
  30995. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  30996. //Impostor types
  30997. PhysicsImpostor.NoImpostor = 0;
  30998. PhysicsImpostor.SphereImpostor = 1;
  30999. PhysicsImpostor.BoxImpostor = 2;
  31000. PhysicsImpostor.PlaneImpostor = 3;
  31001. PhysicsImpostor.MeshImpostor = 4;
  31002. PhysicsImpostor.CylinderImpostor = 7;
  31003. PhysicsImpostor.ParticleImpostor = 8;
  31004. PhysicsImpostor.HeightmapImpostor = 9;
  31005. return PhysicsImpostor;
  31006. }());
  31007. BABYLON.PhysicsImpostor = PhysicsImpostor;
  31008. })(BABYLON || (BABYLON = {}));
  31009. var BABYLON;
  31010. (function (BABYLON) {
  31011. var PhysicsEngine = (function () {
  31012. function PhysicsEngine(gravity, _physicsPlugin) {
  31013. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  31014. this._physicsPlugin = _physicsPlugin;
  31015. //new methods and parameters
  31016. this._impostors = [];
  31017. this._joints = [];
  31018. if (!this._physicsPlugin.isSupported()) {
  31019. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  31020. + "Please make sure it is included.");
  31021. }
  31022. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  31023. this.setGravity(gravity);
  31024. this.setTimeStep();
  31025. }
  31026. PhysicsEngine.prototype.setGravity = function (gravity) {
  31027. this.gravity = gravity;
  31028. this._physicsPlugin.setGravity(this.gravity);
  31029. };
  31030. /**
  31031. * Set the time step of the physics engine.
  31032. * default is 1/60.
  31033. * To slow it down, enter 1/600 for example.
  31034. * To speed it up, 1/30
  31035. * @param {number} newTimeStep the new timestep to apply to this world.
  31036. */
  31037. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  31038. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  31039. this._physicsPlugin.setTimeStep(newTimeStep);
  31040. };
  31041. PhysicsEngine.prototype.dispose = function () {
  31042. this._impostors.forEach(function (impostor) {
  31043. impostor.dispose();
  31044. });
  31045. this._physicsPlugin.dispose();
  31046. };
  31047. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  31048. return this._physicsPlugin.name;
  31049. };
  31050. /**
  31051. * Adding a new impostor for the impostor tracking.
  31052. * This will be done by the impostor itself.
  31053. * @param {PhysicsImpostor} impostor the impostor to add
  31054. */
  31055. PhysicsEngine.prototype.addImpostor = function (impostor) {
  31056. impostor.uniqueId = this._impostors.push(impostor);
  31057. //if no parent, generate the body
  31058. if (!impostor.parent) {
  31059. this._physicsPlugin.generatePhysicsBody(impostor);
  31060. }
  31061. };
  31062. /**
  31063. * Remove an impostor from the engine.
  31064. * This impostor and its mesh will not longer be updated by the physics engine.
  31065. * @param {PhysicsImpostor} impostor the impostor to remove
  31066. */
  31067. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  31068. var index = this._impostors.indexOf(impostor);
  31069. if (index > -1) {
  31070. var removed = this._impostors.splice(index, 1);
  31071. //Is it needed?
  31072. if (removed.length) {
  31073. //this will also remove it from the world.
  31074. removed[0].physicsBody = null;
  31075. }
  31076. }
  31077. };
  31078. /**
  31079. * Add a joint to the physics engine
  31080. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  31081. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  31082. * @param {PhysicsJoint} the joint that will connect both impostors.
  31083. */
  31084. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  31085. var impostorJoint = {
  31086. mainImpostor: mainImpostor,
  31087. connectedImpostor: connectedImpostor,
  31088. joint: joint
  31089. };
  31090. joint.physicsPlugin = this._physicsPlugin;
  31091. this._joints.push(impostorJoint);
  31092. this._physicsPlugin.generateJoint(impostorJoint);
  31093. };
  31094. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  31095. var matchingJoints = this._joints.filter(function (impostorJoint) {
  31096. return (impostorJoint.connectedImpostor === connectedImpostor
  31097. && impostorJoint.joint === joint
  31098. && impostorJoint.mainImpostor === mainImpostor);
  31099. });
  31100. if (matchingJoints.length) {
  31101. this._physicsPlugin.removeJoint(matchingJoints[0]);
  31102. }
  31103. };
  31104. /**
  31105. * Called by the scene. no need to call it.
  31106. */
  31107. PhysicsEngine.prototype._step = function (delta) {
  31108. var _this = this;
  31109. //check if any mesh has no body / requires an update
  31110. this._impostors.forEach(function (impostor) {
  31111. if (impostor.isBodyInitRequired()) {
  31112. _this._physicsPlugin.generatePhysicsBody(impostor);
  31113. }
  31114. });
  31115. if (delta > 0.1) {
  31116. delta = 0.1;
  31117. }
  31118. else if (delta <= 0) {
  31119. delta = 1.0 / 60.0;
  31120. }
  31121. this._physicsPlugin.executeStep(delta, this._impostors);
  31122. };
  31123. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  31124. return this._physicsPlugin;
  31125. };
  31126. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  31127. for (var i = 0; i < this._impostors.length; ++i) {
  31128. if (this._impostors[i].object === object) {
  31129. return this._impostors[i];
  31130. }
  31131. }
  31132. };
  31133. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  31134. for (var i = 0; i < this._impostors.length; ++i) {
  31135. if (this._impostors[i].physicsBody === body) {
  31136. return this._impostors[i];
  31137. }
  31138. }
  31139. };
  31140. // Statics, Legacy support.
  31141. /**
  31142. * @Deprecated
  31143. *
  31144. */
  31145. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  31146. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  31147. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  31148. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  31149. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  31150. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  31151. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  31152. PhysicsEngine.CapsuleImpostor = -1;
  31153. PhysicsEngine.ConeImpostor = -1;
  31154. PhysicsEngine.ConvexHullImpostor = -1;
  31155. PhysicsEngine.Epsilon = 0.001;
  31156. return PhysicsEngine;
  31157. }());
  31158. BABYLON.PhysicsEngine = PhysicsEngine;
  31159. })(BABYLON || (BABYLON = {}));
  31160. var BABYLON;
  31161. (function (BABYLON) {
  31162. var VertexData = (function () {
  31163. function VertexData() {
  31164. }
  31165. VertexData.prototype.set = function (data, kind) {
  31166. switch (kind) {
  31167. case BABYLON.VertexBuffer.PositionKind:
  31168. this.positions = data;
  31169. break;
  31170. case BABYLON.VertexBuffer.NormalKind:
  31171. this.normals = data;
  31172. break;
  31173. case BABYLON.VertexBuffer.UVKind:
  31174. this.uvs = data;
  31175. break;
  31176. case BABYLON.VertexBuffer.UV2Kind:
  31177. this.uvs2 = data;
  31178. break;
  31179. case BABYLON.VertexBuffer.UV3Kind:
  31180. this.uvs3 = data;
  31181. break;
  31182. case BABYLON.VertexBuffer.UV4Kind:
  31183. this.uvs4 = data;
  31184. break;
  31185. case BABYLON.VertexBuffer.UV5Kind:
  31186. this.uvs5 = data;
  31187. break;
  31188. case BABYLON.VertexBuffer.UV6Kind:
  31189. this.uvs6 = data;
  31190. break;
  31191. case BABYLON.VertexBuffer.ColorKind:
  31192. this.colors = data;
  31193. break;
  31194. case BABYLON.VertexBuffer.MatricesIndicesKind:
  31195. this.matricesIndices = data;
  31196. break;
  31197. case BABYLON.VertexBuffer.MatricesWeightsKind:
  31198. this.matricesWeights = data;
  31199. break;
  31200. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  31201. this.matricesIndicesExtra = data;
  31202. break;
  31203. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  31204. this.matricesWeightsExtra = data;
  31205. break;
  31206. }
  31207. };
  31208. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  31209. this._applyTo(mesh, updatable);
  31210. };
  31211. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  31212. this._applyTo(geometry, updatable);
  31213. };
  31214. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  31215. this._update(mesh);
  31216. };
  31217. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  31218. this._update(geometry);
  31219. };
  31220. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  31221. if (this.positions) {
  31222. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  31223. }
  31224. if (this.normals) {
  31225. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  31226. }
  31227. if (this.uvs) {
  31228. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  31229. }
  31230. if (this.uvs2) {
  31231. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  31232. }
  31233. if (this.uvs3) {
  31234. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  31235. }
  31236. if (this.uvs4) {
  31237. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  31238. }
  31239. if (this.uvs5) {
  31240. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  31241. }
  31242. if (this.uvs6) {
  31243. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  31244. }
  31245. if (this.colors) {
  31246. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  31247. }
  31248. if (this.matricesIndices) {
  31249. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  31250. }
  31251. if (this.matricesWeights) {
  31252. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  31253. }
  31254. if (this.matricesIndicesExtra) {
  31255. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  31256. }
  31257. if (this.matricesWeightsExtra) {
  31258. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  31259. }
  31260. if (this.indices) {
  31261. meshOrGeometry.setIndices(this.indices);
  31262. }
  31263. };
  31264. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  31265. if (this.positions) {
  31266. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  31267. }
  31268. if (this.normals) {
  31269. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  31270. }
  31271. if (this.uvs) {
  31272. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  31273. }
  31274. if (this.uvs2) {
  31275. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  31276. }
  31277. if (this.uvs3) {
  31278. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  31279. }
  31280. if (this.uvs4) {
  31281. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  31282. }
  31283. if (this.uvs5) {
  31284. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  31285. }
  31286. if (this.uvs6) {
  31287. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  31288. }
  31289. if (this.colors) {
  31290. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  31291. }
  31292. if (this.matricesIndices) {
  31293. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  31294. }
  31295. if (this.matricesWeights) {
  31296. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  31297. }
  31298. if (this.matricesIndicesExtra) {
  31299. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  31300. }
  31301. if (this.matricesWeightsExtra) {
  31302. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  31303. }
  31304. if (this.indices) {
  31305. meshOrGeometry.setIndices(this.indices);
  31306. }
  31307. };
  31308. VertexData.prototype.transform = function (matrix) {
  31309. var transformed = BABYLON.Vector3.Zero();
  31310. var index;
  31311. if (this.positions) {
  31312. var position = BABYLON.Vector3.Zero();
  31313. for (index = 0; index < this.positions.length; index += 3) {
  31314. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  31315. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  31316. this.positions[index] = transformed.x;
  31317. this.positions[index + 1] = transformed.y;
  31318. this.positions[index + 2] = transformed.z;
  31319. }
  31320. }
  31321. if (this.normals) {
  31322. var normal = BABYLON.Vector3.Zero();
  31323. for (index = 0; index < this.normals.length; index += 3) {
  31324. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  31325. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  31326. this.normals[index] = transformed.x;
  31327. this.normals[index + 1] = transformed.y;
  31328. this.normals[index + 2] = transformed.z;
  31329. }
  31330. }
  31331. };
  31332. VertexData.prototype.merge = function (other) {
  31333. if (other.indices) {
  31334. if (!this.indices) {
  31335. this.indices = [];
  31336. }
  31337. var offset = this.positions ? this.positions.length / 3 : 0;
  31338. for (var index = 0; index < other.indices.length; index++) {
  31339. //TODO check type - if Int32Array!
  31340. this.indices.push(other.indices[index] + offset);
  31341. }
  31342. }
  31343. this.positions = this._mergeElement(this.positions, other.positions);
  31344. this.normals = this._mergeElement(this.normals, other.normals);
  31345. this.uvs = this._mergeElement(this.uvs, other.uvs);
  31346. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  31347. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  31348. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  31349. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  31350. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  31351. this.colors = this._mergeElement(this.colors, other.colors);
  31352. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  31353. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  31354. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  31355. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  31356. };
  31357. VertexData.prototype._mergeElement = function (source, other) {
  31358. if (!other)
  31359. return source;
  31360. if (!source)
  31361. return other;
  31362. var len = other.length + source.length;
  31363. var isSrcTypedArray = source instanceof Float32Array;
  31364. var isOthTypedArray = other instanceof Float32Array;
  31365. // use non-loop method when the source is Float32Array
  31366. if (isSrcTypedArray) {
  31367. var ret32 = new Float32Array(len);
  31368. ret32.set(source);
  31369. ret32.set(other, source.length);
  31370. return ret32;
  31371. }
  31372. else if (!isOthTypedArray) {
  31373. return source.concat(other);
  31374. }
  31375. else {
  31376. var ret = source.slice(0); // copy source to a separate array
  31377. for (var i = 0, len = other.length; i < len; i++) {
  31378. ret.push(other[i]);
  31379. }
  31380. return ret;
  31381. }
  31382. };
  31383. VertexData.prototype.serialize = function () {
  31384. var serializationObject = this.serialize();
  31385. if (this.positions) {
  31386. serializationObject.positions = this.positions;
  31387. }
  31388. if (this.normals) {
  31389. serializationObject.normals = this.normals;
  31390. }
  31391. if (this.uvs) {
  31392. serializationObject.uvs = this.uvs;
  31393. }
  31394. if (this.uvs2) {
  31395. serializationObject.uvs2 = this.uvs2;
  31396. }
  31397. if (this.uvs3) {
  31398. serializationObject.uvs3 = this.uvs3;
  31399. }
  31400. if (this.uvs4) {
  31401. serializationObject.uvs4 = this.uvs4;
  31402. }
  31403. if (this.uvs5) {
  31404. serializationObject.uvs5 = this.uvs5;
  31405. }
  31406. if (this.uvs6) {
  31407. serializationObject.uvs6 = this.uvs6;
  31408. }
  31409. if (this.colors) {
  31410. serializationObject.colors = this.colors;
  31411. }
  31412. if (this.matricesIndices) {
  31413. serializationObject.matricesIndices = this.matricesIndices;
  31414. serializationObject.matricesIndices._isExpanded = true;
  31415. }
  31416. if (this.matricesWeights) {
  31417. serializationObject.matricesWeights = this.matricesWeights;
  31418. }
  31419. if (this.matricesIndicesExtra) {
  31420. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  31421. serializationObject.matricesIndicesExtra._isExpanded = true;
  31422. }
  31423. if (this.matricesWeightsExtra) {
  31424. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  31425. }
  31426. serializationObject.indices = this.indices;
  31427. return serializationObject;
  31428. };
  31429. // Statics
  31430. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  31431. return VertexData._ExtractFrom(mesh, copyWhenShared);
  31432. };
  31433. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  31434. return VertexData._ExtractFrom(geometry, copyWhenShared);
  31435. };
  31436. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  31437. var result = new VertexData();
  31438. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  31439. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  31440. }
  31441. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  31442. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  31443. }
  31444. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  31445. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  31446. }
  31447. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  31448. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  31449. }
  31450. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  31451. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  31452. }
  31453. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  31454. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  31455. }
  31456. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  31457. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  31458. }
  31459. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  31460. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  31461. }
  31462. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  31463. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  31464. }
  31465. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  31466. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  31467. }
  31468. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  31469. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  31470. }
  31471. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  31472. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  31473. }
  31474. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  31475. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  31476. }
  31477. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  31478. return result;
  31479. };
  31480. VertexData.CreateRibbon = function (options) {
  31481. var pathArray = options.pathArray;
  31482. var closeArray = options.closeArray || false;
  31483. var closePath = options.closePath || false;
  31484. var invertUV = options.invertUV || false;
  31485. var defaultOffset = Math.floor(pathArray[0].length / 2);
  31486. var offset = options.offset || defaultOffset;
  31487. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  31488. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31489. var positions = [];
  31490. var indices = [];
  31491. var normals = [];
  31492. var uvs = [];
  31493. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  31494. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  31495. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  31496. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  31497. var minlg; // minimal length among all paths from pathArray
  31498. var lg = []; // array of path lengths : nb of vertex per path
  31499. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  31500. var p; // path iterator
  31501. var i; // point iterator
  31502. var j; // point iterator
  31503. // if single path in pathArray
  31504. if (pathArray.length < 2) {
  31505. var ar1 = [];
  31506. var ar2 = [];
  31507. for (i = 0; i < pathArray[0].length - offset; i++) {
  31508. ar1.push(pathArray[0][i]);
  31509. ar2.push(pathArray[0][i + offset]);
  31510. }
  31511. pathArray = [ar1, ar2];
  31512. }
  31513. // positions and horizontal distances (u)
  31514. var idc = 0;
  31515. var closePathCorr = (closePath) ? 1 : 0;
  31516. var path;
  31517. var l;
  31518. minlg = pathArray[0].length;
  31519. var vectlg;
  31520. var dist;
  31521. for (p = 0; p < pathArray.length; p++) {
  31522. uTotalDistance[p] = 0;
  31523. us[p] = [0];
  31524. path = pathArray[p];
  31525. l = path.length;
  31526. minlg = (minlg < l) ? minlg : l;
  31527. j = 0;
  31528. while (j < l) {
  31529. positions.push(path[j].x, path[j].y, path[j].z);
  31530. if (j > 0) {
  31531. vectlg = path[j].subtract(path[j - 1]).length();
  31532. dist = vectlg + uTotalDistance[p];
  31533. us[p].push(dist);
  31534. uTotalDistance[p] = dist;
  31535. }
  31536. j++;
  31537. }
  31538. if (closePath) {
  31539. j--;
  31540. positions.push(path[0].x, path[0].y, path[0].z);
  31541. vectlg = path[j].subtract(path[0]).length();
  31542. dist = vectlg + uTotalDistance[p];
  31543. us[p].push(dist);
  31544. uTotalDistance[p] = dist;
  31545. }
  31546. lg[p] = l + closePathCorr;
  31547. idx[p] = idc;
  31548. idc += (l + closePathCorr);
  31549. }
  31550. // vertical distances (v)
  31551. var path1;
  31552. var path2;
  31553. var vertex1;
  31554. var vertex2;
  31555. for (i = 0; i < minlg + closePathCorr; i++) {
  31556. vTotalDistance[i] = 0;
  31557. vs[i] = [0];
  31558. for (p = 0; p < pathArray.length - 1; p++) {
  31559. path1 = pathArray[p];
  31560. path2 = pathArray[p + 1];
  31561. if (i === minlg) {
  31562. vertex1 = path1[0];
  31563. vertex2 = path2[0];
  31564. }
  31565. else {
  31566. vertex1 = path1[i];
  31567. vertex2 = path2[i];
  31568. }
  31569. vectlg = vertex2.subtract(vertex1).length();
  31570. dist = vectlg + vTotalDistance[i];
  31571. vs[i].push(dist);
  31572. vTotalDistance[i] = dist;
  31573. }
  31574. if (closeArray) {
  31575. path1 = pathArray[p];
  31576. path2 = pathArray[0];
  31577. if (i === minlg) {
  31578. vertex2 = path2[0];
  31579. }
  31580. vectlg = vertex2.subtract(vertex1).length();
  31581. dist = vectlg + vTotalDistance[i];
  31582. vTotalDistance[i] = dist;
  31583. }
  31584. }
  31585. // uvs
  31586. var u;
  31587. var v;
  31588. for (p = 0; p < pathArray.length; p++) {
  31589. for (i = 0; i < minlg + closePathCorr; i++) {
  31590. u = us[p][i] / uTotalDistance[p];
  31591. v = vs[i][p] / vTotalDistance[i];
  31592. if (invertUV) {
  31593. uvs.push(v, u);
  31594. }
  31595. else {
  31596. uvs.push(u, v);
  31597. }
  31598. }
  31599. }
  31600. // indices
  31601. p = 0; // path index
  31602. var pi = 0; // positions array index
  31603. var l1 = lg[p] - 1; // path1 length
  31604. var l2 = lg[p + 1] - 1; // path2 length
  31605. var min = (l1 < l2) ? l1 : l2; // current path stop index
  31606. var shft = idx[1] - idx[0]; // shift
  31607. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  31608. while (pi <= min && p < path1nb) {
  31609. // 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
  31610. indices.push(pi, pi + shft, pi + 1);
  31611. indices.push(pi + shft + 1, pi + 1, pi + shft);
  31612. pi += 1;
  31613. if (pi === min) {
  31614. p++;
  31615. if (p === lg.length - 1) {
  31616. shft = idx[0] - idx[p];
  31617. l1 = lg[p] - 1;
  31618. l2 = lg[0] - 1;
  31619. }
  31620. else {
  31621. shft = idx[p + 1] - idx[p];
  31622. l1 = lg[p] - 1;
  31623. l2 = lg[p + 1] - 1;
  31624. }
  31625. pi = idx[p];
  31626. min = (l1 < l2) ? l1 + pi : l2 + pi;
  31627. }
  31628. }
  31629. // normals
  31630. VertexData.ComputeNormals(positions, indices, normals);
  31631. if (closePath) {
  31632. var indexFirst = 0;
  31633. var indexLast = 0;
  31634. for (p = 0; p < pathArray.length; p++) {
  31635. indexFirst = idx[p] * 3;
  31636. if (p + 1 < pathArray.length) {
  31637. indexLast = (idx[p + 1] - 1) * 3;
  31638. }
  31639. else {
  31640. indexLast = normals.length - 3;
  31641. }
  31642. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  31643. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  31644. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  31645. normals[indexLast] = normals[indexFirst];
  31646. normals[indexLast + 1] = normals[indexFirst + 1];
  31647. normals[indexLast + 2] = normals[indexFirst + 2];
  31648. }
  31649. }
  31650. // sides
  31651. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31652. // Result
  31653. var vertexData = new VertexData();
  31654. vertexData.indices = indices;
  31655. vertexData.positions = positions;
  31656. vertexData.normals = normals;
  31657. vertexData.uvs = uvs;
  31658. if (closePath) {
  31659. vertexData._idx = idx;
  31660. }
  31661. return vertexData;
  31662. };
  31663. VertexData.CreateBox = function (options) {
  31664. var normalsSource = [
  31665. new BABYLON.Vector3(0, 0, 1),
  31666. new BABYLON.Vector3(0, 0, -1),
  31667. new BABYLON.Vector3(1, 0, 0),
  31668. new BABYLON.Vector3(-1, 0, 0),
  31669. new BABYLON.Vector3(0, 1, 0),
  31670. new BABYLON.Vector3(0, -1, 0)
  31671. ];
  31672. var indices = [];
  31673. var positions = [];
  31674. var normals = [];
  31675. var uvs = [];
  31676. var width = options.width || options.size || 1;
  31677. var height = options.height || options.size || 1;
  31678. var depth = options.depth || options.size || 1;
  31679. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31680. var faceUV = options.faceUV || new Array(6);
  31681. var faceColors = options.faceColors;
  31682. var colors = [];
  31683. // default face colors and UV if undefined
  31684. for (var f = 0; f < 6; f++) {
  31685. if (faceUV[f] === undefined) {
  31686. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31687. }
  31688. if (faceColors && faceColors[f] === undefined) {
  31689. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31690. }
  31691. }
  31692. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  31693. // Create each face in turn.
  31694. for (var index = 0; index < normalsSource.length; index++) {
  31695. var normal = normalsSource[index];
  31696. // Get two vectors perpendicular to the face normal and to each other.
  31697. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  31698. var side2 = BABYLON.Vector3.Cross(normal, side1);
  31699. // Six indices (two triangles) per face.
  31700. var verticesLength = positions.length / 3;
  31701. indices.push(verticesLength);
  31702. indices.push(verticesLength + 1);
  31703. indices.push(verticesLength + 2);
  31704. indices.push(verticesLength);
  31705. indices.push(verticesLength + 2);
  31706. indices.push(verticesLength + 3);
  31707. // Four vertices per face.
  31708. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  31709. positions.push(vertex.x, vertex.y, vertex.z);
  31710. normals.push(normal.x, normal.y, normal.z);
  31711. uvs.push(faceUV[index].z, faceUV[index].w);
  31712. if (faceColors) {
  31713. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31714. }
  31715. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  31716. positions.push(vertex.x, vertex.y, vertex.z);
  31717. normals.push(normal.x, normal.y, normal.z);
  31718. uvs.push(faceUV[index].x, faceUV[index].w);
  31719. if (faceColors) {
  31720. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31721. }
  31722. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  31723. positions.push(vertex.x, vertex.y, vertex.z);
  31724. normals.push(normal.x, normal.y, normal.z);
  31725. uvs.push(faceUV[index].x, faceUV[index].y);
  31726. if (faceColors) {
  31727. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31728. }
  31729. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  31730. positions.push(vertex.x, vertex.y, vertex.z);
  31731. normals.push(normal.x, normal.y, normal.z);
  31732. uvs.push(faceUV[index].z, faceUV[index].y);
  31733. if (faceColors) {
  31734. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  31735. }
  31736. }
  31737. // sides
  31738. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31739. // Result
  31740. var vertexData = new VertexData();
  31741. vertexData.indices = indices;
  31742. vertexData.positions = positions;
  31743. vertexData.normals = normals;
  31744. vertexData.uvs = uvs;
  31745. if (faceColors) {
  31746. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  31747. vertexData.colors = totalColors;
  31748. }
  31749. return vertexData;
  31750. };
  31751. VertexData.CreateSphere = function (options) {
  31752. var segments = options.segments || 32;
  31753. var diameterX = options.diameterX || options.diameter || 1;
  31754. var diameterY = options.diameterY || options.diameter || 1;
  31755. var diameterZ = options.diameterZ || options.diameter || 1;
  31756. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31757. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  31758. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31759. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  31760. var totalZRotationSteps = 2 + segments;
  31761. var totalYRotationSteps = 2 * totalZRotationSteps;
  31762. var indices = [];
  31763. var positions = [];
  31764. var normals = [];
  31765. var uvs = [];
  31766. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  31767. var normalizedZ = zRotationStep / totalZRotationSteps;
  31768. var angleZ = normalizedZ * Math.PI * slice;
  31769. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  31770. var normalizedY = yRotationStep / totalYRotationSteps;
  31771. var angleY = normalizedY * Math.PI * 2 * arc;
  31772. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  31773. var rotationY = BABYLON.Matrix.RotationY(angleY);
  31774. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  31775. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  31776. var vertex = complete.multiply(radius);
  31777. var normal = complete.divide(radius).normalize();
  31778. positions.push(vertex.x, vertex.y, vertex.z);
  31779. normals.push(normal.x, normal.y, normal.z);
  31780. uvs.push(normalizedY, normalizedZ);
  31781. }
  31782. if (zRotationStep > 0) {
  31783. var verticesCount = positions.length / 3;
  31784. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  31785. indices.push((firstIndex));
  31786. indices.push((firstIndex + 1));
  31787. indices.push(firstIndex + totalYRotationSteps + 1);
  31788. indices.push((firstIndex + totalYRotationSteps + 1));
  31789. indices.push((firstIndex + 1));
  31790. indices.push((firstIndex + totalYRotationSteps + 2));
  31791. }
  31792. }
  31793. }
  31794. // Sides
  31795. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  31796. // Result
  31797. var vertexData = new VertexData();
  31798. vertexData.indices = indices;
  31799. vertexData.positions = positions;
  31800. vertexData.normals = normals;
  31801. vertexData.uvs = uvs;
  31802. return vertexData;
  31803. };
  31804. // Cylinder and cone
  31805. VertexData.CreateCylinder = function (options) {
  31806. var height = options.height || 2;
  31807. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  31808. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  31809. var tessellation = options.tessellation || 24;
  31810. var subdivisions = options.subdivisions || 1;
  31811. var hasRings = options.hasRings;
  31812. var enclose = options.enclose;
  31813. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  31814. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  31815. var faceUV = options.faceUV || new Array(3);
  31816. var faceColors = options.faceColors;
  31817. // default face colors and UV if undefined
  31818. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  31819. var ringNb = (hasRings) ? subdivisions : 1;
  31820. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  31821. var f;
  31822. for (f = 0; f < surfaceNb; f++) {
  31823. if (faceColors && faceColors[f] === undefined) {
  31824. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  31825. }
  31826. }
  31827. for (f = 0; f < surfaceNb; f++) {
  31828. if (faceUV && faceUV[f] === undefined) {
  31829. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  31830. }
  31831. }
  31832. var indices = [];
  31833. var positions = [];
  31834. var normals = [];
  31835. var uvs = [];
  31836. var colors = [];
  31837. var angle_step = Math.PI * 2 * arc / tessellation;
  31838. var angle;
  31839. var h;
  31840. var radius;
  31841. var tan = (diameterBottom - diameterTop) / 2 / height;
  31842. var ringVertex = BABYLON.Vector3.Zero();
  31843. var ringNormal = BABYLON.Vector3.Zero();
  31844. var ringFirstVertex = BABYLON.Vector3.Zero();
  31845. var ringFirstNormal = BABYLON.Vector3.Zero();
  31846. var quadNormal = BABYLON.Vector3.Zero();
  31847. var Y = BABYLON.Axis.Y;
  31848. // positions, normals, uvs
  31849. var i;
  31850. var j;
  31851. var r;
  31852. var ringIdx = 1;
  31853. var s = 1; // surface index
  31854. var cs = 0;
  31855. var v = 0;
  31856. for (i = 0; i <= subdivisions; i++) {
  31857. h = i / subdivisions;
  31858. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  31859. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  31860. for (r = 0; r < ringIdx; r++) {
  31861. if (hasRings) {
  31862. s += r;
  31863. }
  31864. if (enclose) {
  31865. s += 2 * r;
  31866. }
  31867. for (j = 0; j <= tessellation; j++) {
  31868. angle = j * angle_step;
  31869. // position
  31870. ringVertex.x = Math.cos(-angle) * radius;
  31871. ringVertex.y = -height / 2 + h * height;
  31872. ringVertex.z = Math.sin(-angle) * radius;
  31873. // normal
  31874. if (diameterTop === 0 && i === subdivisions) {
  31875. // if no top cap, reuse former normals
  31876. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  31877. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  31878. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  31879. }
  31880. else {
  31881. ringNormal.x = ringVertex.x;
  31882. ringNormal.z = ringVertex.z;
  31883. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  31884. ringNormal.normalize();
  31885. }
  31886. // keep first ring vertex values for enclose
  31887. if (j === 0) {
  31888. ringFirstVertex.copyFrom(ringVertex);
  31889. ringFirstNormal.copyFrom(ringNormal);
  31890. }
  31891. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31892. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  31893. if (hasRings) {
  31894. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  31895. }
  31896. else {
  31897. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  31898. }
  31899. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  31900. if (faceColors) {
  31901. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  31902. }
  31903. }
  31904. // if enclose, add four vertices and their dedicated normals
  31905. if (arc !== 1 && enclose) {
  31906. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  31907. positions.push(0, ringVertex.y, 0);
  31908. positions.push(0, ringVertex.y, 0);
  31909. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  31910. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  31911. quadNormal.normalize();
  31912. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31913. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  31914. quadNormal.normalize();
  31915. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  31916. if (hasRings) {
  31917. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  31918. }
  31919. else {
  31920. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  31921. }
  31922. uvs.push(faceUV[s + 1].x, v);
  31923. uvs.push(faceUV[s + 1].z, v);
  31924. if (hasRings) {
  31925. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  31926. }
  31927. else {
  31928. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  31929. }
  31930. uvs.push(faceUV[s + 2].x, v);
  31931. uvs.push(faceUV[s + 2].z, v);
  31932. if (faceColors) {
  31933. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31934. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  31935. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31936. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  31937. }
  31938. }
  31939. if (cs !== s) {
  31940. cs = s;
  31941. }
  31942. }
  31943. }
  31944. // indices
  31945. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  31946. var s;
  31947. i = 0;
  31948. for (s = 0; s < subdivisions; s++) {
  31949. for (j = 0; j < tessellation; j++) {
  31950. var i0 = i * (e + 1) + j;
  31951. var i1 = (i + 1) * (e + 1) + j;
  31952. var i2 = i * (e + 1) + (j + 1);
  31953. var i3 = (i + 1) * (e + 1) + (j + 1);
  31954. indices.push(i0, i1, i2);
  31955. indices.push(i3, i2, i1);
  31956. }
  31957. if (arc !== 1 && enclose) {
  31958. indices.push(i0 + 2, i1 + 2, i2 + 2);
  31959. indices.push(i3 + 2, i2 + 2, i1 + 2);
  31960. indices.push(i0 + 4, i1 + 4, i2 + 4);
  31961. indices.push(i3 + 4, i2 + 4, i1 + 4);
  31962. }
  31963. i = (hasRings) ? (i + 2) : (i + 1);
  31964. }
  31965. // Caps
  31966. var createCylinderCap = function (isTop) {
  31967. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  31968. if (radius === 0) {
  31969. return;
  31970. }
  31971. // Cap positions, normals & uvs
  31972. var angle;
  31973. var circleVector;
  31974. var i;
  31975. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  31976. var c;
  31977. if (faceColors) {
  31978. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  31979. }
  31980. // cap center
  31981. var vbase = positions.length / 3;
  31982. var offset = isTop ? height / 2 : -height / 2;
  31983. var center = new BABYLON.Vector3(0, offset, 0);
  31984. positions.push(center.x, center.y, center.z);
  31985. normals.push(0, isTop ? 1 : -1, 0);
  31986. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  31987. if (faceColors) {
  31988. colors.push(c.r, c.g, c.b, c.a);
  31989. }
  31990. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  31991. for (i = 0; i <= tessellation; i++) {
  31992. angle = Math.PI * 2 * i * arc / tessellation;
  31993. var cos = Math.cos(-angle);
  31994. var sin = Math.sin(-angle);
  31995. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  31996. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  31997. positions.push(circleVector.x, circleVector.y, circleVector.z);
  31998. normals.push(0, isTop ? 1 : -1, 0);
  31999. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  32000. if (faceColors) {
  32001. colors.push(c.r, c.g, c.b, c.a);
  32002. }
  32003. }
  32004. // Cap indices
  32005. for (i = 0; i < tessellation; i++) {
  32006. if (!isTop) {
  32007. indices.push(vbase);
  32008. indices.push(vbase + (i + 1));
  32009. indices.push(vbase + (i + 2));
  32010. }
  32011. else {
  32012. indices.push(vbase);
  32013. indices.push(vbase + (i + 2));
  32014. indices.push(vbase + (i + 1));
  32015. }
  32016. }
  32017. };
  32018. // add caps to geometry
  32019. createCylinderCap(false);
  32020. createCylinderCap(true);
  32021. // Sides
  32022. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32023. var vertexData = new VertexData();
  32024. vertexData.indices = indices;
  32025. vertexData.positions = positions;
  32026. vertexData.normals = normals;
  32027. vertexData.uvs = uvs;
  32028. if (faceColors) {
  32029. vertexData.colors = colors;
  32030. }
  32031. return vertexData;
  32032. };
  32033. VertexData.CreateTorus = function (options) {
  32034. var indices = [];
  32035. var positions = [];
  32036. var normals = [];
  32037. var uvs = [];
  32038. var diameter = options.diameter || 1;
  32039. var thickness = options.thickness || 0.5;
  32040. var tessellation = options.tessellation || 16;
  32041. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32042. var stride = tessellation + 1;
  32043. for (var i = 0; i <= tessellation; i++) {
  32044. var u = i / tessellation;
  32045. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  32046. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  32047. for (var j = 0; j <= tessellation; j++) {
  32048. var v = 1 - j / tessellation;
  32049. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  32050. var dx = Math.cos(innerAngle);
  32051. var dy = Math.sin(innerAngle);
  32052. // Create a vertex.
  32053. var normal = new BABYLON.Vector3(dx, dy, 0);
  32054. var position = normal.scale(thickness / 2);
  32055. var textureCoordinate = new BABYLON.Vector2(u, v);
  32056. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  32057. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  32058. positions.push(position.x, position.y, position.z);
  32059. normals.push(normal.x, normal.y, normal.z);
  32060. uvs.push(textureCoordinate.x, textureCoordinate.y);
  32061. // And create indices for two triangles.
  32062. var nextI = (i + 1) % stride;
  32063. var nextJ = (j + 1) % stride;
  32064. indices.push(i * stride + j);
  32065. indices.push(i * stride + nextJ);
  32066. indices.push(nextI * stride + j);
  32067. indices.push(i * stride + nextJ);
  32068. indices.push(nextI * stride + nextJ);
  32069. indices.push(nextI * stride + j);
  32070. }
  32071. }
  32072. // Sides
  32073. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32074. // Result
  32075. var vertexData = new VertexData();
  32076. vertexData.indices = indices;
  32077. vertexData.positions = positions;
  32078. vertexData.normals = normals;
  32079. vertexData.uvs = uvs;
  32080. return vertexData;
  32081. };
  32082. VertexData.CreateLineSystem = function (options) {
  32083. var indices = [];
  32084. var positions = [];
  32085. var lines = options.lines;
  32086. var idx = 0;
  32087. for (var l = 0; l < lines.length; l++) {
  32088. var points = lines[l];
  32089. for (var index = 0; index < points.length; index++) {
  32090. positions.push(points[index].x, points[index].y, points[index].z);
  32091. if (index > 0) {
  32092. indices.push(idx - 1);
  32093. indices.push(idx);
  32094. }
  32095. idx++;
  32096. }
  32097. }
  32098. var vertexData = new VertexData();
  32099. vertexData.indices = indices;
  32100. vertexData.positions = positions;
  32101. return vertexData;
  32102. };
  32103. VertexData.CreateDashedLines = function (options) {
  32104. var dashSize = options.dashSize || 3;
  32105. var gapSize = options.gapSize || 1;
  32106. var dashNb = options.dashNb || 200;
  32107. var points = options.points;
  32108. var positions = new Array();
  32109. var indices = new Array();
  32110. var curvect = BABYLON.Vector3.Zero();
  32111. var lg = 0;
  32112. var nb = 0;
  32113. var shft = 0;
  32114. var dashshft = 0;
  32115. var curshft = 0;
  32116. var idx = 0;
  32117. var i = 0;
  32118. for (i = 0; i < points.length - 1; i++) {
  32119. points[i + 1].subtractToRef(points[i], curvect);
  32120. lg += curvect.length();
  32121. }
  32122. shft = lg / dashNb;
  32123. dashshft = dashSize * shft / (dashSize + gapSize);
  32124. for (i = 0; i < points.length - 1; i++) {
  32125. points[i + 1].subtractToRef(points[i], curvect);
  32126. nb = Math.floor(curvect.length() / shft);
  32127. curvect.normalize();
  32128. for (var j = 0; j < nb; j++) {
  32129. curshft = shft * j;
  32130. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  32131. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  32132. indices.push(idx, idx + 1);
  32133. idx += 2;
  32134. }
  32135. }
  32136. // Result
  32137. var vertexData = new VertexData();
  32138. vertexData.positions = positions;
  32139. vertexData.indices = indices;
  32140. return vertexData;
  32141. };
  32142. VertexData.CreateGround = function (options) {
  32143. var indices = [];
  32144. var positions = [];
  32145. var normals = [];
  32146. var uvs = [];
  32147. var row, col;
  32148. var width = options.width || 1;
  32149. var height = options.height || 1;
  32150. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  32151. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  32152. for (row = 0; row <= subdivisionsY; row++) {
  32153. for (col = 0; col <= subdivisionsX; col++) {
  32154. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  32155. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32156. positions.push(position.x, position.y, position.z);
  32157. normals.push(normal.x, normal.y, normal.z);
  32158. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  32159. }
  32160. }
  32161. for (row = 0; row < subdivisionsY; row++) {
  32162. for (col = 0; col < subdivisionsX; col++) {
  32163. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32164. indices.push(col + 1 + row * (subdivisionsX + 1));
  32165. indices.push(col + row * (subdivisionsX + 1));
  32166. indices.push(col + (row + 1) * (subdivisionsX + 1));
  32167. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  32168. indices.push(col + row * (subdivisionsX + 1));
  32169. }
  32170. }
  32171. // Result
  32172. var vertexData = new VertexData();
  32173. vertexData.indices = indices;
  32174. vertexData.positions = positions;
  32175. vertexData.normals = normals;
  32176. vertexData.uvs = uvs;
  32177. return vertexData;
  32178. };
  32179. VertexData.CreateTiledGround = function (options) {
  32180. var xmin = options.xmin || -1.0;
  32181. var zmin = options.zmin || -1.0;
  32182. var xmax = options.xmax || 1.0;
  32183. var zmax = options.zmax || 1.0;
  32184. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  32185. var precision = options.precision || { w: 1, h: 1 };
  32186. var indices = [];
  32187. var positions = [];
  32188. var normals = [];
  32189. var uvs = [];
  32190. var row, col, tileRow, tileCol;
  32191. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  32192. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  32193. precision.w = (precision.w < 1) ? 1 : precision.w;
  32194. precision.h = (precision.h < 1) ? 1 : precision.h;
  32195. var tileSize = {
  32196. 'w': (xmax - xmin) / subdivisions.w,
  32197. 'h': (zmax - zmin) / subdivisions.h
  32198. };
  32199. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  32200. // Indices
  32201. var base = positions.length / 3;
  32202. var rowLength = precision.w + 1;
  32203. for (row = 0; row < precision.h; row++) {
  32204. for (col = 0; col < precision.w; col++) {
  32205. var square = [
  32206. base + col + row * rowLength,
  32207. base + (col + 1) + row * rowLength,
  32208. base + (col + 1) + (row + 1) * rowLength,
  32209. base + col + (row + 1) * rowLength
  32210. ];
  32211. indices.push(square[1]);
  32212. indices.push(square[2]);
  32213. indices.push(square[3]);
  32214. indices.push(square[0]);
  32215. indices.push(square[1]);
  32216. indices.push(square[3]);
  32217. }
  32218. }
  32219. // Position, normals and uvs
  32220. var position = BABYLON.Vector3.Zero();
  32221. var normal = new BABYLON.Vector3(0, 1.0, 0);
  32222. for (row = 0; row <= precision.h; row++) {
  32223. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  32224. for (col = 0; col <= precision.w; col++) {
  32225. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  32226. position.y = 0;
  32227. positions.push(position.x, position.y, position.z);
  32228. normals.push(normal.x, normal.y, normal.z);
  32229. uvs.push(col / precision.w, row / precision.h);
  32230. }
  32231. }
  32232. }
  32233. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  32234. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  32235. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  32236. }
  32237. }
  32238. // Result
  32239. var vertexData = new VertexData();
  32240. vertexData.indices = indices;
  32241. vertexData.positions = positions;
  32242. vertexData.normals = normals;
  32243. vertexData.uvs = uvs;
  32244. return vertexData;
  32245. };
  32246. VertexData.CreateGroundFromHeightMap = function (options) {
  32247. var indices = [];
  32248. var positions = [];
  32249. var normals = [];
  32250. var uvs = [];
  32251. var row, col;
  32252. // Vertices
  32253. for (row = 0; row <= options.subdivisions; row++) {
  32254. for (col = 0; col <= options.subdivisions; col++) {
  32255. 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));
  32256. // Compute height
  32257. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  32258. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  32259. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  32260. var r = options.buffer[pos] / 255.0;
  32261. var g = options.buffer[pos + 1] / 255.0;
  32262. var b = options.buffer[pos + 2] / 255.0;
  32263. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32264. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  32265. // Add vertex
  32266. positions.push(position.x, position.y, position.z);
  32267. normals.push(0, 0, 0);
  32268. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  32269. }
  32270. }
  32271. // Indices
  32272. for (row = 0; row < options.subdivisions; row++) {
  32273. for (col = 0; col < options.subdivisions; col++) {
  32274. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32275. indices.push(col + 1 + row * (options.subdivisions + 1));
  32276. indices.push(col + row * (options.subdivisions + 1));
  32277. indices.push(col + (row + 1) * (options.subdivisions + 1));
  32278. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  32279. indices.push(col + row * (options.subdivisions + 1));
  32280. }
  32281. }
  32282. // Normals
  32283. VertexData.ComputeNormals(positions, indices, normals);
  32284. // Result
  32285. var vertexData = new VertexData();
  32286. vertexData.indices = indices;
  32287. vertexData.positions = positions;
  32288. vertexData.normals = normals;
  32289. vertexData.uvs = uvs;
  32290. return vertexData;
  32291. };
  32292. VertexData.CreatePlane = function (options) {
  32293. var indices = [];
  32294. var positions = [];
  32295. var normals = [];
  32296. var uvs = [];
  32297. var width = options.width || options.size || 1;
  32298. var height = options.height || options.size || 1;
  32299. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32300. // Vertices
  32301. var halfWidth = width / 2.0;
  32302. var halfHeight = height / 2.0;
  32303. positions.push(-halfWidth, -halfHeight, 0);
  32304. normals.push(0, 0, -1.0);
  32305. uvs.push(0.0, 0.0);
  32306. positions.push(halfWidth, -halfHeight, 0);
  32307. normals.push(0, 0, -1.0);
  32308. uvs.push(1.0, 0.0);
  32309. positions.push(halfWidth, halfHeight, 0);
  32310. normals.push(0, 0, -1.0);
  32311. uvs.push(1.0, 1.0);
  32312. positions.push(-halfWidth, halfHeight, 0);
  32313. normals.push(0, 0, -1.0);
  32314. uvs.push(0.0, 1.0);
  32315. // Indices
  32316. indices.push(0);
  32317. indices.push(1);
  32318. indices.push(2);
  32319. indices.push(0);
  32320. indices.push(2);
  32321. indices.push(3);
  32322. // Sides
  32323. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32324. // Result
  32325. var vertexData = new VertexData();
  32326. vertexData.indices = indices;
  32327. vertexData.positions = positions;
  32328. vertexData.normals = normals;
  32329. vertexData.uvs = uvs;
  32330. return vertexData;
  32331. };
  32332. VertexData.CreateDisc = function (options) {
  32333. var positions = [];
  32334. var indices = [];
  32335. var normals = [];
  32336. var uvs = [];
  32337. var radius = options.radius || 0.5;
  32338. var tessellation = options.tessellation || 64;
  32339. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  32340. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32341. // positions and uvs
  32342. positions.push(0, 0, 0); // disc center first
  32343. uvs.push(0.5, 0.5);
  32344. var theta = Math.PI * 2 * arc;
  32345. var step = theta / tessellation;
  32346. for (var a = 0; a < theta; a += step) {
  32347. var x = Math.cos(a);
  32348. var y = Math.sin(a);
  32349. var u = (x + 1) / 2;
  32350. var v = (1 - y) / 2;
  32351. positions.push(radius * x, radius * y, 0);
  32352. uvs.push(u, v);
  32353. }
  32354. if (arc === 1) {
  32355. positions.push(positions[3], positions[4], positions[5]); // close the circle
  32356. uvs.push(uvs[2], uvs[3]);
  32357. }
  32358. //indices
  32359. var vertexNb = positions.length / 3;
  32360. for (var i = 1; i < vertexNb - 1; i++) {
  32361. indices.push(i + 1, 0, i);
  32362. }
  32363. // result
  32364. VertexData.ComputeNormals(positions, indices, normals);
  32365. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32366. var vertexData = new VertexData();
  32367. vertexData.indices = indices;
  32368. vertexData.positions = positions;
  32369. vertexData.normals = normals;
  32370. vertexData.uvs = uvs;
  32371. return vertexData;
  32372. };
  32373. VertexData.CreateIcoSphere = function (options) {
  32374. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32375. var radius = options.radius || 1;
  32376. var flat = (options.flat === undefined) ? true : options.flat;
  32377. var subdivisions = options.subdivisions || 4;
  32378. var radiusX = options.radiusX || radius;
  32379. var radiusY = options.radiusY || radius;
  32380. var radiusZ = options.radiusZ || radius;
  32381. var t = (1 + Math.sqrt(5)) / 2;
  32382. // 12 vertex x,y,z
  32383. var ico_vertices = [
  32384. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  32385. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  32386. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  32387. ];
  32388. // index of 3 vertex makes a face of icopshere
  32389. var ico_indices = [
  32390. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  32391. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  32392. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  32393. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  32394. ];
  32395. // vertex for uv have aliased position, not for UV
  32396. var vertices_unalias_id = [
  32397. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  32398. // vertex alias
  32399. 0,
  32400. 2,
  32401. 3,
  32402. 3,
  32403. 3,
  32404. 4,
  32405. 7,
  32406. 8,
  32407. 9,
  32408. 9,
  32409. 10,
  32410. 11 // 23: B + 12
  32411. ];
  32412. // uv as integer step (not pixels !)
  32413. var ico_vertexuv = [
  32414. 5, 1, 3, 1, 6, 4, 0, 0,
  32415. 5, 3, 4, 2, 2, 2, 4, 0,
  32416. 2, 0, 1, 1, 6, 0, 6, 2,
  32417. // vertex alias (for same vertex on different faces)
  32418. 0, 4,
  32419. 3, 3,
  32420. 4, 4,
  32421. 3, 1,
  32422. 4, 2,
  32423. 4, 4,
  32424. 0, 2,
  32425. 1, 1,
  32426. 2, 2,
  32427. 3, 3,
  32428. 1, 3,
  32429. 2, 4 // 23: B + 12
  32430. ];
  32431. // Vertices[0, 1, ...9, A, B] : position on UV plane
  32432. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  32433. // First island of uv mapping
  32434. // v = 4h 3+ 2
  32435. // v = 3h 9+ 4
  32436. // v = 2h 9+ 5 B
  32437. // v = 1h 9 1 0
  32438. // v = 0h 3 8 7 A
  32439. // u = 0 1 2 3 4 5 6 *a
  32440. // Second island of uv mapping
  32441. // v = 4h 0+ B+ 4+
  32442. // v = 3h A+ 2+
  32443. // v = 2h 7+ 6 3+
  32444. // v = 1h 8+ 3+
  32445. // v = 0h
  32446. // u = 0 1 2 3 4 5 6 *a
  32447. // Face layout on texture UV mapping
  32448. // ============
  32449. // \ 4 /\ 16 / ======
  32450. // \ / \ / /\ 11 /
  32451. // \/ 7 \/ / \ /
  32452. // ======= / 10 \/
  32453. // /\ 17 /\ =======
  32454. // / \ / \ \ 15 /\
  32455. // / 8 \/ 12 \ \ / \
  32456. // ============ \/ 6 \
  32457. // \ 18 /\ ============
  32458. // \ / \ \ 5 /\ 0 /
  32459. // \/ 13 \ \ / \ /
  32460. // ======= \/ 1 \/
  32461. // =============
  32462. // /\ 19 /\ 2 /\
  32463. // / \ / \ / \
  32464. // / 14 \/ 9 \/ 3 \
  32465. // ===================
  32466. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  32467. var ustep = 138 / 1024;
  32468. var vstep = 239 / 1024;
  32469. var uoffset = 60 / 1024;
  32470. var voffset = 26 / 1024;
  32471. // Second island should have margin, not to touch the first island
  32472. // avoid any borderline artefact in pixel rounding
  32473. var island_u_offset = -40 / 1024;
  32474. var island_v_offset = +20 / 1024;
  32475. // face is either island 0 or 1 :
  32476. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  32477. var island = [
  32478. 0, 0, 0, 0, 1,
  32479. 0, 0, 1, 1, 0,
  32480. 0, 0, 1, 1, 0,
  32481. 0, 1, 1, 1, 0 // 15 - 19
  32482. ];
  32483. var indices = [];
  32484. var positions = [];
  32485. var normals = [];
  32486. var uvs = [];
  32487. var current_indice = 0;
  32488. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  32489. var face_vertex_pos = new Array(3);
  32490. var face_vertex_uv = new Array(3);
  32491. var v012;
  32492. for (v012 = 0; v012 < 3; v012++) {
  32493. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  32494. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  32495. }
  32496. // create all with normals
  32497. for (var face = 0; face < 20; face++) {
  32498. // 3 vertex per face
  32499. for (v012 = 0; v012 < 3; v012++) {
  32500. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  32501. var v_id = ico_indices[3 * face + v012];
  32502. // vertex have 3D position (x,y,z)
  32503. 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]);
  32504. // Normalize to get normal, then scale to radius
  32505. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  32506. // uv Coordinates from vertex ID
  32507. 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);
  32508. }
  32509. // Subdivide the face (interpolate pos, norm, uv)
  32510. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  32511. // - norm is linear interpolation of vertex corner normal
  32512. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  32513. // - uv is linear interpolation
  32514. //
  32515. // Topology is as below for sub-divide by 2
  32516. // vertex shown as v0,v1,v2
  32517. // interp index is i1 to progress in range [v0,v1[
  32518. // interp index is i2 to progress in range [v0,v2[
  32519. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  32520. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32521. //
  32522. //
  32523. // i2 v2
  32524. // ^ ^
  32525. // / / \
  32526. // / / \
  32527. // / / \
  32528. // / / (0,1) \
  32529. // / #---------\
  32530. // / / \ (0,0)'/ \
  32531. // / / \ / \
  32532. // / / \ / \
  32533. // / / (0,0) \ / (1,0) \
  32534. // / #---------#---------\
  32535. // v0 v1
  32536. //
  32537. // --------------------> i1
  32538. //
  32539. // interp of (i1,i2):
  32540. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  32541. // along i1 : lerp(x0,x1, i1/(S-i2))
  32542. //
  32543. // centroid of triangle is needed to get help normal computation
  32544. // (c1,c2) are used for centroid location
  32545. var interp_vertex = function (i1, i2, c1, c2) {
  32546. // vertex is interpolated from
  32547. // - face_vertex_pos[0..2]
  32548. // - face_vertex_uv[0..2]
  32549. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  32550. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  32551. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  32552. pos_interp.normalize();
  32553. var vertex_normal;
  32554. if (flat) {
  32555. // in flat mode, recalculate normal as face centroid normal
  32556. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  32557. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  32558. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  32559. }
  32560. else {
  32561. // in smooth mode, recalculate normal from each single vertex position
  32562. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  32563. }
  32564. // Vertex normal need correction due to X,Y,Z radius scaling
  32565. vertex_normal.x /= radiusX;
  32566. vertex_normal.y /= radiusY;
  32567. vertex_normal.z /= radiusZ;
  32568. vertex_normal.normalize();
  32569. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  32570. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  32571. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  32572. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  32573. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  32574. uvs.push(uv_interp.x, uv_interp.y);
  32575. // push each vertex has member of a face
  32576. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  32577. indices.push(current_indice);
  32578. current_indice++;
  32579. };
  32580. for (var i2 = 0; i2 < subdivisions; i2++) {
  32581. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  32582. // face : (i1,i2) for /\ :
  32583. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  32584. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32585. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32586. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  32587. if (i1 + i2 + 1 < subdivisions) {
  32588. // face : (i1,i2)' for \/ :
  32589. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  32590. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32591. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32592. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  32593. }
  32594. }
  32595. }
  32596. }
  32597. // Sides
  32598. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32599. // Result
  32600. var vertexData = new VertexData();
  32601. vertexData.indices = indices;
  32602. vertexData.positions = positions;
  32603. vertexData.normals = normals;
  32604. vertexData.uvs = uvs;
  32605. return vertexData;
  32606. };
  32607. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  32608. VertexData.CreatePolyhedron = function (options) {
  32609. // provided polyhedron types :
  32610. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  32611. // 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)
  32612. var polyhedra = [];
  32613. 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]] };
  32614. 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]] };
  32615. polyhedra[2] = {
  32616. 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]],
  32617. 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]]
  32618. };
  32619. polyhedra[3] = {
  32620. 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]],
  32621. 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]]
  32622. };
  32623. polyhedra[4] = {
  32624. 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]],
  32625. 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]]
  32626. };
  32627. 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]] };
  32628. 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]] };
  32629. 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]] };
  32630. 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]] };
  32631. 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]] };
  32632. 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]] };
  32633. 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]] };
  32634. 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]] };
  32635. 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]] };
  32636. polyhedra[14] = {
  32637. 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]],
  32638. 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]]
  32639. };
  32640. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  32641. var size = options.size;
  32642. var sizeX = options.sizeX || size || 1;
  32643. var sizeY = options.sizeY || size || 1;
  32644. var sizeZ = options.sizeZ || size || 1;
  32645. var data = options.custom || polyhedra[type];
  32646. var nbfaces = data.face.length;
  32647. var faceUV = options.faceUV || new Array(nbfaces);
  32648. var faceColors = options.faceColors;
  32649. var flat = (options.flat === undefined) ? true : options.flat;
  32650. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32651. var positions = [];
  32652. var indices = [];
  32653. var normals = [];
  32654. var uvs = [];
  32655. var colors = [];
  32656. var index = 0;
  32657. var faceIdx = 0; // face cursor in the array "indexes"
  32658. var indexes = [];
  32659. var i = 0;
  32660. var f = 0;
  32661. var u, v, ang, x, y, tmp;
  32662. // default face colors and UV if undefined
  32663. if (flat) {
  32664. for (f = 0; f < nbfaces; f++) {
  32665. if (faceColors && faceColors[f] === undefined) {
  32666. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32667. }
  32668. if (faceUV && faceUV[f] === undefined) {
  32669. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32670. }
  32671. }
  32672. }
  32673. if (!flat) {
  32674. for (i = 0; i < data.vertex.length; i++) {
  32675. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  32676. uvs.push(0, 0);
  32677. }
  32678. for (f = 0; f < nbfaces; f++) {
  32679. for (i = 0; i < data.face[f].length - 2; i++) {
  32680. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  32681. }
  32682. }
  32683. }
  32684. else {
  32685. for (f = 0; f < nbfaces; f++) {
  32686. var fl = data.face[f].length; // number of vertices of the current face
  32687. ang = 2 * Math.PI / fl;
  32688. x = 0.5 * Math.tan(ang / 2);
  32689. y = 0.5;
  32690. // positions, uvs, colors
  32691. for (i = 0; i < fl; i++) {
  32692. // positions
  32693. 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);
  32694. indexes.push(index);
  32695. index++;
  32696. // uvs
  32697. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  32698. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  32699. uvs.push(u, v);
  32700. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  32701. y = x * Math.sin(ang) + y * Math.cos(ang);
  32702. x = tmp;
  32703. // colors
  32704. if (faceColors) {
  32705. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  32706. }
  32707. }
  32708. // indices from indexes
  32709. for (i = 0; i < fl - 2; i++) {
  32710. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  32711. }
  32712. faceIdx += fl;
  32713. }
  32714. }
  32715. VertexData.ComputeNormals(positions, indices, normals);
  32716. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32717. var vertexData = new VertexData();
  32718. vertexData.positions = positions;
  32719. vertexData.indices = indices;
  32720. vertexData.normals = normals;
  32721. vertexData.uvs = uvs;
  32722. if (faceColors && flat) {
  32723. vertexData.colors = colors;
  32724. }
  32725. return vertexData;
  32726. };
  32727. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  32728. VertexData.CreateTorusKnot = function (options) {
  32729. var indices = [];
  32730. var positions = [];
  32731. var normals = [];
  32732. var uvs = [];
  32733. var radius = options.radius || 2;
  32734. var tube = options.tube || 0.5;
  32735. var radialSegments = options.radialSegments || 32;
  32736. var tubularSegments = options.tubularSegments || 32;
  32737. var p = options.p || 2;
  32738. var q = options.q || 3;
  32739. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32740. // Helper
  32741. var getPos = function (angle) {
  32742. var cu = Math.cos(angle);
  32743. var su = Math.sin(angle);
  32744. var quOverP = q / p * angle;
  32745. var cs = Math.cos(quOverP);
  32746. var tx = radius * (2 + cs) * 0.5 * cu;
  32747. var ty = radius * (2 + cs) * su * 0.5;
  32748. var tz = radius * Math.sin(quOverP) * 0.5;
  32749. return new BABYLON.Vector3(tx, ty, tz);
  32750. };
  32751. // Vertices
  32752. var i;
  32753. var j;
  32754. for (i = 0; i <= radialSegments; i++) {
  32755. var modI = i % radialSegments;
  32756. var u = modI / radialSegments * 2 * p * Math.PI;
  32757. var p1 = getPos(u);
  32758. var p2 = getPos(u + 0.01);
  32759. var tang = p2.subtract(p1);
  32760. var n = p2.add(p1);
  32761. var bitan = BABYLON.Vector3.Cross(tang, n);
  32762. n = BABYLON.Vector3.Cross(bitan, tang);
  32763. bitan.normalize();
  32764. n.normalize();
  32765. for (j = 0; j < tubularSegments; j++) {
  32766. var modJ = j % tubularSegments;
  32767. var v = modJ / tubularSegments * 2 * Math.PI;
  32768. var cx = -tube * Math.cos(v);
  32769. var cy = tube * Math.sin(v);
  32770. positions.push(p1.x + cx * n.x + cy * bitan.x);
  32771. positions.push(p1.y + cx * n.y + cy * bitan.y);
  32772. positions.push(p1.z + cx * n.z + cy * bitan.z);
  32773. uvs.push(i / radialSegments);
  32774. uvs.push(j / tubularSegments);
  32775. }
  32776. }
  32777. for (i = 0; i < radialSegments; i++) {
  32778. for (j = 0; j < tubularSegments; j++) {
  32779. var jNext = (j + 1) % tubularSegments;
  32780. var a = i * tubularSegments + j;
  32781. var b = (i + 1) * tubularSegments + j;
  32782. var c = (i + 1) * tubularSegments + jNext;
  32783. var d = i * tubularSegments + jNext;
  32784. indices.push(d);
  32785. indices.push(b);
  32786. indices.push(a);
  32787. indices.push(d);
  32788. indices.push(c);
  32789. indices.push(b);
  32790. }
  32791. }
  32792. // Normals
  32793. VertexData.ComputeNormals(positions, indices, normals);
  32794. // Sides
  32795. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32796. // Result
  32797. var vertexData = new VertexData();
  32798. vertexData.indices = indices;
  32799. vertexData.positions = positions;
  32800. vertexData.normals = normals;
  32801. vertexData.uvs = uvs;
  32802. return vertexData;
  32803. };
  32804. // Tools
  32805. /**
  32806. * @param {any} - positions (number[] or Float32Array)
  32807. * @param {any} - indices (number[] or Uint16Array)
  32808. * @param {any} - normals (number[] or Float32Array)
  32809. */
  32810. VertexData.ComputeNormals = function (positions, indices, normals) {
  32811. var index = 0;
  32812. var p1p2x = 0.0;
  32813. var p1p2y = 0.0;
  32814. var p1p2z = 0.0;
  32815. var p3p2x = 0.0;
  32816. var p3p2y = 0.0;
  32817. var p3p2z = 0.0;
  32818. var faceNormalx = 0.0;
  32819. var faceNormaly = 0.0;
  32820. var faceNormalz = 0.0;
  32821. var length = 0.0;
  32822. var i1 = 0;
  32823. var i2 = 0;
  32824. var i3 = 0;
  32825. for (index = 0; index < positions.length; index++) {
  32826. normals[index] = 0.0;
  32827. }
  32828. // indice triplet = 1 face
  32829. var nbFaces = indices.length / 3;
  32830. for (index = 0; index < nbFaces; index++) {
  32831. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  32832. i2 = indices[index * 3 + 1];
  32833. i3 = indices[index * 3 + 2];
  32834. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  32835. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  32836. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  32837. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  32838. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  32839. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  32840. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  32841. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  32842. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  32843. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32844. length = (length === 0) ? 1.0 : length;
  32845. faceNormalx /= length; // normalize this normal
  32846. faceNormaly /= length;
  32847. faceNormalz /= length;
  32848. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  32849. normals[i1 * 3 + 1] += faceNormaly;
  32850. normals[i1 * 3 + 2] += faceNormalz;
  32851. normals[i2 * 3] += faceNormalx;
  32852. normals[i2 * 3 + 1] += faceNormaly;
  32853. normals[i2 * 3 + 2] += faceNormalz;
  32854. normals[i3 * 3] += faceNormalx;
  32855. normals[i3 * 3 + 1] += faceNormaly;
  32856. normals[i3 * 3 + 2] += faceNormalz;
  32857. }
  32858. // last normalization of each normal
  32859. for (index = 0; index < normals.length / 3; index++) {
  32860. faceNormalx = normals[index * 3];
  32861. faceNormaly = normals[index * 3 + 1];
  32862. faceNormalz = normals[index * 3 + 2];
  32863. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  32864. length = (length === 0) ? 1.0 : length;
  32865. faceNormalx /= length;
  32866. faceNormaly /= length;
  32867. faceNormalz /= length;
  32868. normals[index * 3] = faceNormalx;
  32869. normals[index * 3 + 1] = faceNormaly;
  32870. normals[index * 3 + 2] = faceNormalz;
  32871. }
  32872. };
  32873. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  32874. var li = indices.length;
  32875. var ln = normals.length;
  32876. var i;
  32877. var n;
  32878. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32879. switch (sideOrientation) {
  32880. case BABYLON.Mesh.FRONTSIDE:
  32881. // nothing changed
  32882. break;
  32883. case BABYLON.Mesh.BACKSIDE:
  32884. var tmp;
  32885. // indices
  32886. for (i = 0; i < li; i += 3) {
  32887. tmp = indices[i];
  32888. indices[i] = indices[i + 2];
  32889. indices[i + 2] = tmp;
  32890. }
  32891. // normals
  32892. for (n = 0; n < ln; n++) {
  32893. normals[n] = -normals[n];
  32894. }
  32895. break;
  32896. case BABYLON.Mesh.DOUBLESIDE:
  32897. // positions
  32898. var lp = positions.length;
  32899. var l = lp / 3;
  32900. for (var p = 0; p < lp; p++) {
  32901. positions[lp + p] = positions[p];
  32902. }
  32903. // indices
  32904. for (i = 0; i < li; i += 3) {
  32905. indices[i + li] = indices[i + 2] + l;
  32906. indices[i + 1 + li] = indices[i + 1] + l;
  32907. indices[i + 2 + li] = indices[i] + l;
  32908. }
  32909. // normals
  32910. for (n = 0; n < ln; n++) {
  32911. normals[ln + n] = -normals[n];
  32912. }
  32913. // uvs
  32914. var lu = uvs.length;
  32915. for (var u = 0; u < lu; u++) {
  32916. uvs[u + lu] = uvs[u];
  32917. }
  32918. break;
  32919. }
  32920. };
  32921. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  32922. var vertexData = new VertexData();
  32923. // positions
  32924. var positions = parsedVertexData.positions;
  32925. if (positions) {
  32926. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  32927. }
  32928. // normals
  32929. var normals = parsedVertexData.normals;
  32930. if (normals) {
  32931. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  32932. }
  32933. // uvs
  32934. var uvs = parsedVertexData.uvs;
  32935. if (uvs) {
  32936. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  32937. }
  32938. // uv2s
  32939. var uv2s = parsedVertexData.uv2s;
  32940. if (uv2s) {
  32941. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  32942. }
  32943. // uv3s
  32944. var uv3s = parsedVertexData.uv3s;
  32945. if (uv3s) {
  32946. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  32947. }
  32948. // uv4s
  32949. var uv4s = parsedVertexData.uv4s;
  32950. if (uv4s) {
  32951. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  32952. }
  32953. // uv5s
  32954. var uv5s = parsedVertexData.uv5s;
  32955. if (uv5s) {
  32956. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  32957. }
  32958. // uv6s
  32959. var uv6s = parsedVertexData.uv6s;
  32960. if (uv6s) {
  32961. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  32962. }
  32963. // colors
  32964. var colors = parsedVertexData.colors;
  32965. if (colors) {
  32966. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  32967. }
  32968. // matricesIndices
  32969. var matricesIndices = parsedVertexData.matricesIndices;
  32970. if (matricesIndices) {
  32971. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  32972. }
  32973. // matricesWeights
  32974. var matricesWeights = parsedVertexData.matricesWeights;
  32975. if (matricesWeights) {
  32976. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  32977. }
  32978. // indices
  32979. var indices = parsedVertexData.indices;
  32980. if (indices) {
  32981. vertexData.indices = indices;
  32982. }
  32983. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  32984. };
  32985. return VertexData;
  32986. }());
  32987. BABYLON.VertexData = VertexData;
  32988. })(BABYLON || (BABYLON = {}));
  32989. var BABYLON;
  32990. (function (BABYLON) {
  32991. var Tags = (function () {
  32992. function Tags() {
  32993. }
  32994. Tags.EnableFor = function (obj) {
  32995. obj._tags = obj._tags || {};
  32996. obj.hasTags = function () {
  32997. return Tags.HasTags(obj);
  32998. };
  32999. obj.addTags = function (tagsString) {
  33000. return Tags.AddTagsTo(obj, tagsString);
  33001. };
  33002. obj.removeTags = function (tagsString) {
  33003. return Tags.RemoveTagsFrom(obj, tagsString);
  33004. };
  33005. obj.matchesTagsQuery = function (tagsQuery) {
  33006. return Tags.MatchesQuery(obj, tagsQuery);
  33007. };
  33008. };
  33009. Tags.DisableFor = function (obj) {
  33010. delete obj._tags;
  33011. delete obj.hasTags;
  33012. delete obj.addTags;
  33013. delete obj.removeTags;
  33014. delete obj.matchesTagsQuery;
  33015. };
  33016. Tags.HasTags = function (obj) {
  33017. if (!obj._tags) {
  33018. return false;
  33019. }
  33020. return !BABYLON.Tools.IsEmpty(obj._tags);
  33021. };
  33022. Tags.GetTags = function (obj, asString) {
  33023. if (asString === void 0) { asString = true; }
  33024. if (!obj._tags) {
  33025. return null;
  33026. }
  33027. if (asString) {
  33028. var tagsArray = [];
  33029. for (var tag in obj._tags) {
  33030. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  33031. tagsArray.push(tag);
  33032. }
  33033. }
  33034. return tagsArray.join(" ");
  33035. }
  33036. else {
  33037. return obj._tags;
  33038. }
  33039. };
  33040. // the tags 'true' and 'false' are reserved and cannot be used as tags
  33041. // a tag cannot start with '||', '&&', and '!'
  33042. // it cannot contain whitespaces
  33043. Tags.AddTagsTo = function (obj, tagsString) {
  33044. if (!tagsString) {
  33045. return;
  33046. }
  33047. if (typeof tagsString !== "string") {
  33048. return;
  33049. }
  33050. var tags = tagsString.split(" ");
  33051. tags.forEach(function (tag, index, array) {
  33052. Tags._AddTagTo(obj, tag);
  33053. });
  33054. };
  33055. Tags._AddTagTo = function (obj, tag) {
  33056. tag = tag.trim();
  33057. if (tag === "" || tag === "true" || tag === "false") {
  33058. return;
  33059. }
  33060. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  33061. return;
  33062. }
  33063. Tags.EnableFor(obj);
  33064. obj._tags[tag] = true;
  33065. };
  33066. Tags.RemoveTagsFrom = function (obj, tagsString) {
  33067. if (!Tags.HasTags(obj)) {
  33068. return;
  33069. }
  33070. var tags = tagsString.split(" ");
  33071. for (var t in tags) {
  33072. Tags._RemoveTagFrom(obj, tags[t]);
  33073. }
  33074. };
  33075. Tags._RemoveTagFrom = function (obj, tag) {
  33076. delete obj._tags[tag];
  33077. };
  33078. Tags.MatchesQuery = function (obj, tagsQuery) {
  33079. if (tagsQuery === undefined) {
  33080. return true;
  33081. }
  33082. if (tagsQuery === "") {
  33083. return Tags.HasTags(obj);
  33084. }
  33085. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  33086. };
  33087. return Tags;
  33088. }());
  33089. BABYLON.Tags = Tags;
  33090. })(BABYLON || (BABYLON = {}));
  33091. var BABYLON;
  33092. (function (BABYLON) {
  33093. var Internals;
  33094. (function (Internals) {
  33095. var AndOrNotEvaluator = (function () {
  33096. function AndOrNotEvaluator() {
  33097. }
  33098. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  33099. if (!query.match(/\([^\(\)]*\)/g)) {
  33100. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  33101. }
  33102. else {
  33103. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  33104. // remove parenthesis
  33105. r = r.slice(1, r.length - 1);
  33106. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  33107. });
  33108. }
  33109. if (query === "true") {
  33110. return true;
  33111. }
  33112. if (query === "false") {
  33113. return false;
  33114. }
  33115. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  33116. };
  33117. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  33118. evaluateCallback = evaluateCallback || (function (r) {
  33119. return r === "true" ? true : false;
  33120. });
  33121. var result;
  33122. var or = parenthesisContent.split("||");
  33123. for (var i in or) {
  33124. if (or.hasOwnProperty(i)) {
  33125. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  33126. var and = ori.split("&&");
  33127. if (and.length > 1) {
  33128. for (var j = 0; j < and.length; ++j) {
  33129. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  33130. if (andj !== "true" && andj !== "false") {
  33131. if (andj[0] === "!") {
  33132. result = !evaluateCallback(andj.substring(1));
  33133. }
  33134. else {
  33135. result = evaluateCallback(andj);
  33136. }
  33137. }
  33138. else {
  33139. result = andj === "true" ? true : false;
  33140. }
  33141. if (!result) {
  33142. ori = "false";
  33143. break;
  33144. }
  33145. }
  33146. }
  33147. if (result || ori === "true") {
  33148. result = true;
  33149. break;
  33150. }
  33151. // result equals false (or undefined)
  33152. if (ori !== "true" && ori !== "false") {
  33153. if (ori[0] === "!") {
  33154. result = !evaluateCallback(ori.substring(1));
  33155. }
  33156. else {
  33157. result = evaluateCallback(ori);
  33158. }
  33159. }
  33160. else {
  33161. result = ori === "true" ? true : false;
  33162. }
  33163. }
  33164. }
  33165. // the whole parenthesis scope is replaced by 'true' or 'false'
  33166. return result ? "true" : "false";
  33167. };
  33168. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  33169. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  33170. // remove whitespaces
  33171. r = r.replace(/[\s]/g, function () { return ""; });
  33172. return r.length % 2 ? "!" : "";
  33173. });
  33174. booleanString = booleanString.trim();
  33175. if (booleanString === "!true") {
  33176. booleanString = "false";
  33177. }
  33178. else if (booleanString === "!false") {
  33179. booleanString = "true";
  33180. }
  33181. return booleanString;
  33182. };
  33183. return AndOrNotEvaluator;
  33184. }());
  33185. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  33186. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  33187. })(BABYLON || (BABYLON = {}));
  33188. var BABYLON;
  33189. (function (BABYLON) {
  33190. var PostProcessRenderPass = (function () {
  33191. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  33192. this._enabled = true;
  33193. this._refCount = 0;
  33194. this._name = name;
  33195. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  33196. this.setRenderList(renderList);
  33197. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  33198. this._renderTexture.onAfterRenderObservable.add(afterRender);
  33199. this._scene = scene;
  33200. this._renderList = renderList;
  33201. }
  33202. // private
  33203. PostProcessRenderPass.prototype._incRefCount = function () {
  33204. if (this._refCount === 0) {
  33205. this._scene.customRenderTargets.push(this._renderTexture);
  33206. }
  33207. return ++this._refCount;
  33208. };
  33209. PostProcessRenderPass.prototype._decRefCount = function () {
  33210. this._refCount--;
  33211. if (this._refCount <= 0) {
  33212. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  33213. }
  33214. return this._refCount;
  33215. };
  33216. PostProcessRenderPass.prototype._update = function () {
  33217. this.setRenderList(this._renderList);
  33218. };
  33219. // public
  33220. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  33221. this._renderTexture.renderList = renderList;
  33222. };
  33223. PostProcessRenderPass.prototype.getRenderTexture = function () {
  33224. return this._renderTexture;
  33225. };
  33226. return PostProcessRenderPass;
  33227. }());
  33228. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  33229. })(BABYLON || (BABYLON = {}));
  33230. var BABYLON;
  33231. (function (BABYLON) {
  33232. var PostProcessRenderEffect = (function () {
  33233. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  33234. this._engine = engine;
  33235. this._name = name;
  33236. this._singleInstance = singleInstance || true;
  33237. this._getPostProcess = getPostProcess;
  33238. this._cameras = [];
  33239. this._indicesForCamera = [];
  33240. this._postProcesses = {};
  33241. this._renderPasses = {};
  33242. this._renderEffectAsPasses = {};
  33243. }
  33244. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  33245. get: function () {
  33246. for (var index in this._postProcesses) {
  33247. if (!this._postProcesses[index].isSupported) {
  33248. return false;
  33249. }
  33250. }
  33251. return true;
  33252. },
  33253. enumerable: true,
  33254. configurable: true
  33255. });
  33256. PostProcessRenderEffect.prototype._update = function () {
  33257. for (var renderPassName in this._renderPasses) {
  33258. this._renderPasses[renderPassName]._update();
  33259. }
  33260. };
  33261. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  33262. this._renderPasses[renderPass._name] = renderPass;
  33263. this._linkParameters();
  33264. };
  33265. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  33266. delete this._renderPasses[renderPass._name];
  33267. this._linkParameters();
  33268. };
  33269. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  33270. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  33271. this._linkParameters();
  33272. };
  33273. PostProcessRenderEffect.prototype.getPass = function (passName) {
  33274. for (var renderPassName in this._renderPasses) {
  33275. if (renderPassName === passName) {
  33276. return this._renderPasses[passName];
  33277. }
  33278. }
  33279. };
  33280. PostProcessRenderEffect.prototype.emptyPasses = function () {
  33281. this._renderPasses = {};
  33282. this._linkParameters();
  33283. };
  33284. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  33285. var cameraKey;
  33286. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33287. for (var i = 0; i < _cam.length; i++) {
  33288. var camera = _cam[i];
  33289. var cameraName = camera.name;
  33290. if (this._singleInstance) {
  33291. cameraKey = 0;
  33292. }
  33293. else {
  33294. cameraKey = cameraName;
  33295. }
  33296. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  33297. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  33298. if (!this._indicesForCamera[cameraName]) {
  33299. this._indicesForCamera[cameraName] = [];
  33300. }
  33301. this._indicesForCamera[cameraName].push(index);
  33302. if (this._cameras.indexOf(camera) === -1) {
  33303. this._cameras[cameraName] = camera;
  33304. }
  33305. for (var passName in this._renderPasses) {
  33306. this._renderPasses[passName]._incRefCount();
  33307. }
  33308. }
  33309. this._linkParameters();
  33310. };
  33311. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  33312. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33313. for (var i = 0; i < _cam.length; i++) {
  33314. var camera = _cam[i];
  33315. var cameraName = camera.name;
  33316. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  33317. var index = this._cameras.indexOf(cameraName);
  33318. this._indicesForCamera.splice(index, 1);
  33319. this._cameras.splice(index, 1);
  33320. for (var passName in this._renderPasses) {
  33321. this._renderPasses[passName]._decRefCount();
  33322. }
  33323. }
  33324. };
  33325. PostProcessRenderEffect.prototype._enable = function (cameras) {
  33326. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33327. for (var i = 0; i < _cam.length; i++) {
  33328. var camera = _cam[i];
  33329. var cameraName = camera.name;
  33330. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  33331. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  33332. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  33333. }
  33334. }
  33335. for (var passName in this._renderPasses) {
  33336. this._renderPasses[passName]._incRefCount();
  33337. }
  33338. }
  33339. };
  33340. PostProcessRenderEffect.prototype._disable = function (cameras) {
  33341. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33342. for (var i = 0; i < _cam.length; i++) {
  33343. var camera = _cam[i];
  33344. var cameraName = camera.Name;
  33345. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  33346. for (var passName in this._renderPasses) {
  33347. this._renderPasses[passName]._decRefCount();
  33348. }
  33349. }
  33350. };
  33351. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  33352. if (this._singleInstance) {
  33353. return this._postProcesses[0];
  33354. }
  33355. else {
  33356. return this._postProcesses[camera.name];
  33357. }
  33358. };
  33359. PostProcessRenderEffect.prototype._linkParameters = function () {
  33360. var _this = this;
  33361. for (var index in this._postProcesses) {
  33362. if (this.applyParameters) {
  33363. this.applyParameters(this._postProcesses[index]);
  33364. }
  33365. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  33366. _this._linkTextures(effect);
  33367. });
  33368. }
  33369. };
  33370. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  33371. for (var renderPassName in this._renderPasses) {
  33372. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  33373. }
  33374. for (var renderEffectName in this._renderEffectAsPasses) {
  33375. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  33376. }
  33377. };
  33378. return PostProcessRenderEffect;
  33379. }());
  33380. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  33381. })(BABYLON || (BABYLON = {}));
  33382. var BABYLON;
  33383. (function (BABYLON) {
  33384. var PostProcessRenderPipeline = (function () {
  33385. function PostProcessRenderPipeline(engine, name) {
  33386. this._engine = engine;
  33387. this._name = name;
  33388. this._renderEffects = {};
  33389. this._renderEffectsForIsolatedPass = {};
  33390. this._cameras = [];
  33391. }
  33392. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  33393. get: function () {
  33394. for (var renderEffectName in this._renderEffects) {
  33395. if (!this._renderEffects[renderEffectName].isSupported) {
  33396. return false;
  33397. }
  33398. }
  33399. return true;
  33400. },
  33401. enumerable: true,
  33402. configurable: true
  33403. });
  33404. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  33405. this._renderEffects[renderEffect._name] = renderEffect;
  33406. };
  33407. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  33408. var renderEffects = this._renderEffects[renderEffectName];
  33409. if (!renderEffects) {
  33410. return;
  33411. }
  33412. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  33413. };
  33414. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  33415. var renderEffects = this._renderEffects[renderEffectName];
  33416. if (!renderEffects) {
  33417. return;
  33418. }
  33419. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  33420. };
  33421. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  33422. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33423. var indicesToDelete = [];
  33424. var i;
  33425. for (i = 0; i < _cam.length; i++) {
  33426. var camera = _cam[i];
  33427. var cameraName = camera.name;
  33428. if (this._cameras.indexOf(camera) === -1) {
  33429. this._cameras[cameraName] = camera;
  33430. }
  33431. else if (unique) {
  33432. indicesToDelete.push(i);
  33433. }
  33434. }
  33435. for (i = 0; i < indicesToDelete.length; i++) {
  33436. cameras.splice(indicesToDelete[i], 1);
  33437. }
  33438. for (var renderEffectName in this._renderEffects) {
  33439. this._renderEffects[renderEffectName]._attachCameras(_cam);
  33440. }
  33441. };
  33442. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  33443. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33444. for (var renderEffectName in this._renderEffects) {
  33445. this._renderEffects[renderEffectName]._detachCameras(_cam);
  33446. }
  33447. for (var i = 0; i < _cam.length; i++) {
  33448. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  33449. }
  33450. };
  33451. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  33452. var _this = this;
  33453. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33454. var pass = null;
  33455. var renderEffectName;
  33456. for (renderEffectName in this._renderEffects) {
  33457. pass = this._renderEffects[renderEffectName].getPass(passName);
  33458. if (pass != null) {
  33459. break;
  33460. }
  33461. }
  33462. if (pass === null) {
  33463. return;
  33464. }
  33465. for (renderEffectName in this._renderEffects) {
  33466. this._renderEffects[renderEffectName]._disable(_cam);
  33467. }
  33468. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  33469. for (var i = 0; i < _cam.length; i++) {
  33470. var camera = _cam[i];
  33471. var cameraName = camera.name;
  33472. 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); });
  33473. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  33474. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  33475. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  33476. }
  33477. };
  33478. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  33479. var _this = this;
  33480. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  33481. for (var i = 0; i < _cam.length; i++) {
  33482. var camera = _cam[i];
  33483. var cameraName = camera.name;
  33484. 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); });
  33485. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  33486. }
  33487. for (var renderEffectName in this._renderEffects) {
  33488. this._renderEffects[renderEffectName]._enable(_cam);
  33489. }
  33490. };
  33491. PostProcessRenderPipeline.prototype._update = function () {
  33492. for (var renderEffectName in this._renderEffects) {
  33493. this._renderEffects[renderEffectName]._update();
  33494. }
  33495. for (var i = 0; i < this._cameras.length; i++) {
  33496. var cameraName = this._cameras[i].name;
  33497. if (this._renderEffectsForIsolatedPass[cameraName]) {
  33498. this._renderEffectsForIsolatedPass[cameraName]._update();
  33499. }
  33500. }
  33501. };
  33502. PostProcessRenderPipeline.prototype.dispose = function () {
  33503. // Must be implemented by children
  33504. };
  33505. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  33506. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  33507. return PostProcessRenderPipeline;
  33508. }());
  33509. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  33510. })(BABYLON || (BABYLON = {}));
  33511. var BABYLON;
  33512. (function (BABYLON) {
  33513. var PostProcessRenderPipelineManager = (function () {
  33514. function PostProcessRenderPipelineManager() {
  33515. this._renderPipelines = {};
  33516. }
  33517. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  33518. this._renderPipelines[renderPipeline._name] = renderPipeline;
  33519. };
  33520. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  33521. var renderPipeline = this._renderPipelines[renderPipelineName];
  33522. if (!renderPipeline) {
  33523. return;
  33524. }
  33525. renderPipeline._attachCameras(cameras, unique);
  33526. };
  33527. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  33528. var renderPipeline = this._renderPipelines[renderPipelineName];
  33529. if (!renderPipeline) {
  33530. return;
  33531. }
  33532. renderPipeline._detachCameras(cameras);
  33533. };
  33534. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33535. var renderPipeline = this._renderPipelines[renderPipelineName];
  33536. if (!renderPipeline) {
  33537. return;
  33538. }
  33539. renderPipeline._enableEffect(renderEffectName, cameras);
  33540. };
  33541. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  33542. var renderPipeline = this._renderPipelines[renderPipelineName];
  33543. if (!renderPipeline) {
  33544. return;
  33545. }
  33546. renderPipeline._disableEffect(renderEffectName, cameras);
  33547. };
  33548. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  33549. var renderPipeline = this._renderPipelines[renderPipelineName];
  33550. if (!renderPipeline) {
  33551. return;
  33552. }
  33553. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  33554. };
  33555. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  33556. var renderPipeline = this._renderPipelines[renderPipelineName];
  33557. if (!renderPipeline) {
  33558. return;
  33559. }
  33560. renderPipeline._disableDisplayOnlyPass(cameras);
  33561. };
  33562. PostProcessRenderPipelineManager.prototype.update = function () {
  33563. for (var renderPipelineName in this._renderPipelines) {
  33564. var pipeline = this._renderPipelines[renderPipelineName];
  33565. if (!pipeline.isSupported) {
  33566. pipeline.dispose();
  33567. delete this._renderPipelines[renderPipelineName];
  33568. }
  33569. else {
  33570. pipeline._update();
  33571. }
  33572. }
  33573. };
  33574. return PostProcessRenderPipelineManager;
  33575. }());
  33576. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  33577. })(BABYLON || (BABYLON = {}));
  33578. var BABYLON;
  33579. (function (BABYLON) {
  33580. var BoundingBoxRenderer = (function () {
  33581. function BoundingBoxRenderer(scene) {
  33582. this.frontColor = new BABYLON.Color3(1, 1, 1);
  33583. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  33584. this.showBackLines = true;
  33585. this.renderList = new BABYLON.SmartArray(32);
  33586. this._vertexBuffers = {};
  33587. this._scene = scene;
  33588. }
  33589. BoundingBoxRenderer.prototype._prepareRessources = function () {
  33590. if (this._colorShader) {
  33591. return;
  33592. }
  33593. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  33594. attributes: [BABYLON.VertexBuffer.PositionKind],
  33595. uniforms: ["worldViewProjection", "color"]
  33596. });
  33597. var engine = this._scene.getEngine();
  33598. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  33599. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  33600. 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]);
  33601. };
  33602. BoundingBoxRenderer.prototype.reset = function () {
  33603. this.renderList.reset();
  33604. };
  33605. BoundingBoxRenderer.prototype.render = function () {
  33606. if (this.renderList.length === 0) {
  33607. return;
  33608. }
  33609. this._prepareRessources();
  33610. if (!this._colorShader.isReady()) {
  33611. return;
  33612. }
  33613. var engine = this._scene.getEngine();
  33614. engine.setDepthWrite(false);
  33615. this._colorShader._preBind();
  33616. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  33617. var boundingBox = this.renderList.data[boundingBoxIndex];
  33618. var min = boundingBox.minimum;
  33619. var max = boundingBox.maximum;
  33620. var diff = max.subtract(min);
  33621. var median = min.add(diff.scale(0.5));
  33622. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  33623. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  33624. .multiply(boundingBox.getWorldMatrix());
  33625. // VBOs
  33626. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  33627. if (this.showBackLines) {
  33628. // Back
  33629. engine.setDepthFunctionToGreaterOrEqual();
  33630. this._scene.resetCachedMaterial();
  33631. this._colorShader.setColor4("color", this.backColor.toColor4());
  33632. this._colorShader.bind(worldMatrix);
  33633. // Draw order
  33634. engine.draw(false, 0, 24);
  33635. }
  33636. // Front
  33637. engine.setDepthFunctionToLess();
  33638. this._scene.resetCachedMaterial();
  33639. this._colorShader.setColor4("color", this.frontColor.toColor4());
  33640. this._colorShader.bind(worldMatrix);
  33641. // Draw order
  33642. engine.draw(false, 0, 24);
  33643. }
  33644. this._colorShader.unbind();
  33645. engine.setDepthFunctionToLessOrEqual();
  33646. engine.setDepthWrite(true);
  33647. };
  33648. BoundingBoxRenderer.prototype.dispose = function () {
  33649. if (!this._colorShader) {
  33650. return;
  33651. }
  33652. this._colorShader.dispose();
  33653. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  33654. if (buffer) {
  33655. buffer.dispose();
  33656. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  33657. }
  33658. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  33659. };
  33660. return BoundingBoxRenderer;
  33661. }());
  33662. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  33663. })(BABYLON || (BABYLON = {}));
  33664. var BABYLON;
  33665. (function (BABYLON) {
  33666. var Condition = (function () {
  33667. function Condition(actionManager) {
  33668. this._actionManager = actionManager;
  33669. }
  33670. Condition.prototype.isValid = function () {
  33671. return true;
  33672. };
  33673. Condition.prototype._getProperty = function (propertyPath) {
  33674. return this._actionManager._getProperty(propertyPath);
  33675. };
  33676. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  33677. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33678. };
  33679. Condition.prototype.serialize = function () {
  33680. };
  33681. Condition.prototype._serialize = function (serializedCondition) {
  33682. return {
  33683. type: 2,
  33684. children: [],
  33685. name: serializedCondition.name,
  33686. properties: serializedCondition.properties
  33687. };
  33688. };
  33689. return Condition;
  33690. }());
  33691. BABYLON.Condition = Condition;
  33692. var ValueCondition = (function (_super) {
  33693. __extends(ValueCondition, _super);
  33694. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  33695. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  33696. _super.call(this, actionManager);
  33697. this.propertyPath = propertyPath;
  33698. this.value = value;
  33699. this.operator = operator;
  33700. this._target = target;
  33701. this._effectiveTarget = this._getEffectiveTarget(target, this.propertyPath);
  33702. this._property = this._getProperty(this.propertyPath);
  33703. }
  33704. Object.defineProperty(ValueCondition, "IsEqual", {
  33705. get: function () {
  33706. return ValueCondition._IsEqual;
  33707. },
  33708. enumerable: true,
  33709. configurable: true
  33710. });
  33711. Object.defineProperty(ValueCondition, "IsDifferent", {
  33712. get: function () {
  33713. return ValueCondition._IsDifferent;
  33714. },
  33715. enumerable: true,
  33716. configurable: true
  33717. });
  33718. Object.defineProperty(ValueCondition, "IsGreater", {
  33719. get: function () {
  33720. return ValueCondition._IsGreater;
  33721. },
  33722. enumerable: true,
  33723. configurable: true
  33724. });
  33725. Object.defineProperty(ValueCondition, "IsLesser", {
  33726. get: function () {
  33727. return ValueCondition._IsLesser;
  33728. },
  33729. enumerable: true,
  33730. configurable: true
  33731. });
  33732. // Methods
  33733. ValueCondition.prototype.isValid = function () {
  33734. switch (this.operator) {
  33735. case ValueCondition.IsGreater:
  33736. return this._effectiveTarget[this._property] > this.value;
  33737. case ValueCondition.IsLesser:
  33738. return this._effectiveTarget[this._property] < this.value;
  33739. case ValueCondition.IsEqual:
  33740. case ValueCondition.IsDifferent:
  33741. var check;
  33742. if (this.value.equals) {
  33743. check = this.value.equals(this._effectiveTarget[this._property]);
  33744. }
  33745. else {
  33746. check = this.value === this._effectiveTarget[this._property];
  33747. }
  33748. return this.operator === ValueCondition.IsEqual ? check : !check;
  33749. }
  33750. return false;
  33751. };
  33752. ValueCondition.prototype.serialize = function () {
  33753. return this._serialize({
  33754. name: "ValueCondition",
  33755. properties: [
  33756. BABYLON.Action._GetTargetProperty(this._target),
  33757. { name: "propertyPath", value: this.propertyPath },
  33758. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  33759. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  33760. ]
  33761. });
  33762. };
  33763. ValueCondition.GetOperatorName = function (operator) {
  33764. switch (operator) {
  33765. case ValueCondition._IsEqual: return "IsEqual";
  33766. case ValueCondition._IsDifferent: return "IsDifferent";
  33767. case ValueCondition._IsGreater: return "IsGreater";
  33768. case ValueCondition._IsLesser: return "IsLesser";
  33769. default: return "";
  33770. }
  33771. };
  33772. // Statics
  33773. ValueCondition._IsEqual = 0;
  33774. ValueCondition._IsDifferent = 1;
  33775. ValueCondition._IsGreater = 2;
  33776. ValueCondition._IsLesser = 3;
  33777. return ValueCondition;
  33778. }(Condition));
  33779. BABYLON.ValueCondition = ValueCondition;
  33780. var PredicateCondition = (function (_super) {
  33781. __extends(PredicateCondition, _super);
  33782. function PredicateCondition(actionManager, predicate) {
  33783. _super.call(this, actionManager);
  33784. this.predicate = predicate;
  33785. }
  33786. PredicateCondition.prototype.isValid = function () {
  33787. return this.predicate();
  33788. };
  33789. return PredicateCondition;
  33790. }(Condition));
  33791. BABYLON.PredicateCondition = PredicateCondition;
  33792. var StateCondition = (function (_super) {
  33793. __extends(StateCondition, _super);
  33794. function StateCondition(actionManager, target, value) {
  33795. _super.call(this, actionManager);
  33796. this.value = value;
  33797. this._target = target;
  33798. }
  33799. // Methods
  33800. StateCondition.prototype.isValid = function () {
  33801. return this._target.state === this.value;
  33802. };
  33803. StateCondition.prototype.serialize = function () {
  33804. return this._serialize({
  33805. name: "StateCondition",
  33806. properties: [
  33807. BABYLON.Action._GetTargetProperty(this._target),
  33808. { name: "value", value: this.value }
  33809. ]
  33810. });
  33811. };
  33812. return StateCondition;
  33813. }(Condition));
  33814. BABYLON.StateCondition = StateCondition;
  33815. })(BABYLON || (BABYLON = {}));
  33816. var BABYLON;
  33817. (function (BABYLON) {
  33818. var Action = (function () {
  33819. function Action(triggerOptions, condition) {
  33820. this.triggerOptions = triggerOptions;
  33821. if (triggerOptions.parameter) {
  33822. this.trigger = triggerOptions.trigger;
  33823. this._triggerParameter = triggerOptions.parameter;
  33824. }
  33825. else {
  33826. this.trigger = triggerOptions;
  33827. }
  33828. this._nextActiveAction = this;
  33829. this._condition = condition;
  33830. }
  33831. // Methods
  33832. Action.prototype._prepare = function () {
  33833. };
  33834. Action.prototype.getTriggerParameter = function () {
  33835. return this._triggerParameter;
  33836. };
  33837. Action.prototype._executeCurrent = function (evt) {
  33838. if (this._nextActiveAction._condition) {
  33839. var condition = this._nextActiveAction._condition;
  33840. var currentRenderId = this._actionManager.getScene().getRenderId();
  33841. // We cache the current evaluation for the current frame
  33842. if (condition._evaluationId === currentRenderId) {
  33843. if (!condition._currentResult) {
  33844. return;
  33845. }
  33846. }
  33847. else {
  33848. condition._evaluationId = currentRenderId;
  33849. if (!condition.isValid()) {
  33850. condition._currentResult = false;
  33851. return;
  33852. }
  33853. condition._currentResult = true;
  33854. }
  33855. }
  33856. this._nextActiveAction.execute(evt);
  33857. this.skipToNextActiveAction();
  33858. };
  33859. Action.prototype.execute = function (evt) {
  33860. };
  33861. Action.prototype.skipToNextActiveAction = function () {
  33862. if (this._nextActiveAction._child) {
  33863. if (!this._nextActiveAction._child._actionManager) {
  33864. this._nextActiveAction._child._actionManager = this._actionManager;
  33865. }
  33866. this._nextActiveAction = this._nextActiveAction._child;
  33867. }
  33868. else {
  33869. this._nextActiveAction = this;
  33870. }
  33871. };
  33872. Action.prototype.then = function (action) {
  33873. this._child = action;
  33874. action._actionManager = this._actionManager;
  33875. action._prepare();
  33876. return action;
  33877. };
  33878. Action.prototype._getProperty = function (propertyPath) {
  33879. return this._actionManager._getProperty(propertyPath);
  33880. };
  33881. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  33882. return this._actionManager._getEffectiveTarget(target, propertyPath);
  33883. };
  33884. Action.prototype.serialize = function (parent) {
  33885. };
  33886. // Called by BABYLON.Action objects in serialize(...). Internal use
  33887. Action.prototype._serialize = function (serializedAction, parent) {
  33888. var serializationObject = {
  33889. type: 1,
  33890. children: [],
  33891. name: serializedAction.name,
  33892. properties: serializedAction.properties || []
  33893. };
  33894. // Serialize child
  33895. if (this._child) {
  33896. this._child.serialize(serializationObject);
  33897. }
  33898. // Check if "this" has a condition
  33899. if (this._condition) {
  33900. var serializedCondition = this._condition.serialize();
  33901. serializedCondition.children.push(serializationObject);
  33902. if (parent) {
  33903. parent.children.push(serializedCondition);
  33904. }
  33905. return serializedCondition;
  33906. }
  33907. if (parent) {
  33908. parent.children.push(serializationObject);
  33909. }
  33910. return serializationObject;
  33911. };
  33912. Action._SerializeValueAsString = function (value) {
  33913. if (typeof value === "number") {
  33914. return value.toString();
  33915. }
  33916. if (typeof value === "boolean") {
  33917. return value ? "true" : "false";
  33918. }
  33919. if (value instanceof BABYLON.Vector2) {
  33920. return value.x + ", " + value.y;
  33921. }
  33922. if (value instanceof BABYLON.Vector3) {
  33923. return value.x + ", " + value.y + ", " + value.z;
  33924. }
  33925. if (value instanceof BABYLON.Color3) {
  33926. return value.r + ", " + value.g + ", " + value.b;
  33927. }
  33928. if (value instanceof BABYLON.Color4) {
  33929. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  33930. }
  33931. return value; // string
  33932. };
  33933. Action._GetTargetProperty = function (target) {
  33934. return {
  33935. name: "target",
  33936. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  33937. : target instanceof BABYLON.Light ? "LightProperties"
  33938. : target instanceof BABYLON.Camera ? "CameraProperties"
  33939. : "SceneProperties",
  33940. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  33941. };
  33942. };
  33943. return Action;
  33944. }());
  33945. BABYLON.Action = Action;
  33946. })(BABYLON || (BABYLON = {}));
  33947. var BABYLON;
  33948. (function (BABYLON) {
  33949. /**
  33950. * ActionEvent is the event beint sent when an action is triggered.
  33951. */
  33952. var ActionEvent = (function () {
  33953. /**
  33954. * @constructor
  33955. * @param source The mesh or sprite that triggered the action.
  33956. * @param pointerX The X mouse cursor position at the time of the event
  33957. * @param pointerY The Y mouse cursor position at the time of the event
  33958. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  33959. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  33960. */
  33961. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  33962. this.source = source;
  33963. this.pointerX = pointerX;
  33964. this.pointerY = pointerY;
  33965. this.meshUnderPointer = meshUnderPointer;
  33966. this.sourceEvent = sourceEvent;
  33967. this.additionalData = additionalData;
  33968. }
  33969. /**
  33970. * Helper function to auto-create an ActionEvent from a source mesh.
  33971. * @param source The source mesh that triggered the event
  33972. * @param evt {Event} The original (browser) event
  33973. */
  33974. ActionEvent.CreateNew = function (source, evt, additionalData) {
  33975. var scene = source.getScene();
  33976. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33977. };
  33978. /**
  33979. * Helper function to auto-create an ActionEvent from a source mesh.
  33980. * @param source The source sprite that triggered the event
  33981. * @param scene Scene associated with the sprite
  33982. * @param evt {Event} The original (browser) event
  33983. */
  33984. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  33985. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  33986. };
  33987. /**
  33988. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  33989. * @param scene the scene where the event occurred
  33990. * @param evt {Event} The original (browser) event
  33991. */
  33992. ActionEvent.CreateNewFromScene = function (scene, evt) {
  33993. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  33994. };
  33995. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  33996. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  33997. };
  33998. return ActionEvent;
  33999. }());
  34000. BABYLON.ActionEvent = ActionEvent;
  34001. /**
  34002. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  34003. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  34004. */
  34005. var ActionManager = (function () {
  34006. function ActionManager(scene) {
  34007. // Members
  34008. this.actions = new Array();
  34009. this._scene = scene;
  34010. scene._actionManagers.push(this);
  34011. }
  34012. Object.defineProperty(ActionManager, "NothingTrigger", {
  34013. get: function () {
  34014. return ActionManager._NothingTrigger;
  34015. },
  34016. enumerable: true,
  34017. configurable: true
  34018. });
  34019. Object.defineProperty(ActionManager, "OnPickTrigger", {
  34020. get: function () {
  34021. return ActionManager._OnPickTrigger;
  34022. },
  34023. enumerable: true,
  34024. configurable: true
  34025. });
  34026. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  34027. get: function () {
  34028. return ActionManager._OnLeftPickTrigger;
  34029. },
  34030. enumerable: true,
  34031. configurable: true
  34032. });
  34033. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  34034. get: function () {
  34035. return ActionManager._OnRightPickTrigger;
  34036. },
  34037. enumerable: true,
  34038. configurable: true
  34039. });
  34040. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  34041. get: function () {
  34042. return ActionManager._OnCenterPickTrigger;
  34043. },
  34044. enumerable: true,
  34045. configurable: true
  34046. });
  34047. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  34048. get: function () {
  34049. return ActionManager._OnPickDownTrigger;
  34050. },
  34051. enumerable: true,
  34052. configurable: true
  34053. });
  34054. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  34055. get: function () {
  34056. return ActionManager._OnPickUpTrigger;
  34057. },
  34058. enumerable: true,
  34059. configurable: true
  34060. });
  34061. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  34062. /// This trigger will only be raised if you also declared a OnPickDown
  34063. get: function () {
  34064. return ActionManager._OnPickOutTrigger;
  34065. },
  34066. enumerable: true,
  34067. configurable: true
  34068. });
  34069. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  34070. get: function () {
  34071. return ActionManager._OnLongPressTrigger;
  34072. },
  34073. enumerable: true,
  34074. configurable: true
  34075. });
  34076. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  34077. get: function () {
  34078. return ActionManager._OnPointerOverTrigger;
  34079. },
  34080. enumerable: true,
  34081. configurable: true
  34082. });
  34083. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  34084. get: function () {
  34085. return ActionManager._OnPointerOutTrigger;
  34086. },
  34087. enumerable: true,
  34088. configurable: true
  34089. });
  34090. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  34091. get: function () {
  34092. return ActionManager._OnEveryFrameTrigger;
  34093. },
  34094. enumerable: true,
  34095. configurable: true
  34096. });
  34097. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  34098. get: function () {
  34099. return ActionManager._OnIntersectionEnterTrigger;
  34100. },
  34101. enumerable: true,
  34102. configurable: true
  34103. });
  34104. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  34105. get: function () {
  34106. return ActionManager._OnIntersectionExitTrigger;
  34107. },
  34108. enumerable: true,
  34109. configurable: true
  34110. });
  34111. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  34112. get: function () {
  34113. return ActionManager._OnKeyDownTrigger;
  34114. },
  34115. enumerable: true,
  34116. configurable: true
  34117. });
  34118. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  34119. get: function () {
  34120. return ActionManager._OnKeyUpTrigger;
  34121. },
  34122. enumerable: true,
  34123. configurable: true
  34124. });
  34125. // Methods
  34126. ActionManager.prototype.dispose = function () {
  34127. var index = this._scene._actionManagers.indexOf(this);
  34128. if (index > -1) {
  34129. this._scene._actionManagers.splice(index, 1);
  34130. }
  34131. };
  34132. ActionManager.prototype.getScene = function () {
  34133. return this._scene;
  34134. };
  34135. /**
  34136. * Does this action manager handles actions of any of the given triggers
  34137. * @param {number[]} triggers - the triggers to be tested
  34138. * @return {boolean} whether one (or more) of the triggers is handeled
  34139. */
  34140. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  34141. for (var index = 0; index < this.actions.length; index++) {
  34142. var action = this.actions[index];
  34143. if (triggers.indexOf(action.trigger) > -1) {
  34144. return true;
  34145. }
  34146. }
  34147. return false;
  34148. };
  34149. /**
  34150. * Does this action manager handles actions of a given trigger
  34151. * @param {number} trigger - the trigger to be tested
  34152. * @return {boolean} whether the trigger is handeled
  34153. */
  34154. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  34155. for (var index = 0; index < this.actions.length; index++) {
  34156. var action = this.actions[index];
  34157. if (action.trigger === trigger) {
  34158. return true;
  34159. }
  34160. }
  34161. return false;
  34162. };
  34163. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  34164. /**
  34165. * Does this action manager has pointer triggers
  34166. * @return {boolean} whether or not it has pointer triggers
  34167. */
  34168. get: function () {
  34169. for (var index = 0; index < this.actions.length; index++) {
  34170. var action = this.actions[index];
  34171. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  34172. return true;
  34173. }
  34174. }
  34175. return false;
  34176. },
  34177. enumerable: true,
  34178. configurable: true
  34179. });
  34180. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  34181. /**
  34182. * Does this action manager has pick triggers
  34183. * @return {boolean} whether or not it has pick triggers
  34184. */
  34185. get: function () {
  34186. for (var index = 0; index < this.actions.length; index++) {
  34187. var action = this.actions[index];
  34188. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  34189. return true;
  34190. }
  34191. }
  34192. return false;
  34193. },
  34194. enumerable: true,
  34195. configurable: true
  34196. });
  34197. /**
  34198. * Registers an action to this action manager
  34199. * @param {BABYLON.Action} action - the action to be registered
  34200. * @return {BABYLON.Action} the action amended (prepared) after registration
  34201. */
  34202. ActionManager.prototype.registerAction = function (action) {
  34203. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  34204. if (this.getScene().actionManager !== this) {
  34205. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  34206. return null;
  34207. }
  34208. }
  34209. this.actions.push(action);
  34210. action._actionManager = this;
  34211. action._prepare();
  34212. return action;
  34213. };
  34214. /**
  34215. * Process a specific trigger
  34216. * @param {number} trigger - the trigger to process
  34217. * @param evt {BABYLON.ActionEvent} the event details to be processed
  34218. */
  34219. ActionManager.prototype.processTrigger = function (trigger, evt) {
  34220. for (var index = 0; index < this.actions.length; index++) {
  34221. var action = this.actions[index];
  34222. if (action.trigger === trigger) {
  34223. if (trigger === ActionManager.OnKeyUpTrigger
  34224. || trigger === ActionManager.OnKeyDownTrigger) {
  34225. var parameter = action.getTriggerParameter();
  34226. if (parameter) {
  34227. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  34228. var actualkey = String.fromCharCode(unicode).toLowerCase();
  34229. if (actualkey !== parameter.toLowerCase()) {
  34230. continue;
  34231. }
  34232. }
  34233. }
  34234. action._executeCurrent(evt);
  34235. }
  34236. }
  34237. };
  34238. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  34239. var properties = propertyPath.split(".");
  34240. for (var index = 0; index < properties.length - 1; index++) {
  34241. target = target[properties[index]];
  34242. }
  34243. return target;
  34244. };
  34245. ActionManager.prototype._getProperty = function (propertyPath) {
  34246. var properties = propertyPath.split(".");
  34247. return properties[properties.length - 1];
  34248. };
  34249. ActionManager.prototype.serialize = function (name) {
  34250. var root = {
  34251. children: [],
  34252. name: name,
  34253. type: 3,
  34254. properties: [] // Empty for root but required
  34255. };
  34256. for (var i = 0; i < this.actions.length; i++) {
  34257. var triggerObject = {
  34258. type: 0,
  34259. children: [],
  34260. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  34261. properties: []
  34262. };
  34263. var triggerOptions = this.actions[i].triggerOptions;
  34264. if (triggerOptions && typeof triggerOptions !== "number") {
  34265. if (triggerOptions.parameter instanceof BABYLON.Node) {
  34266. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  34267. }
  34268. else {
  34269. triggerObject.properties.push({ name: "parameter", targetType: null, value: triggerOptions.parameter });
  34270. }
  34271. }
  34272. // Serialize child action, recursively
  34273. this.actions[i].serialize(triggerObject);
  34274. // Add serialized trigger
  34275. root.children.push(triggerObject);
  34276. }
  34277. return root;
  34278. };
  34279. ActionManager.Parse = function (parsedActions, object, scene) {
  34280. var actionManager = new BABYLON.ActionManager(scene);
  34281. if (object === null)
  34282. scene.actionManager = actionManager;
  34283. else
  34284. object.actionManager = actionManager;
  34285. // instanciate a new object
  34286. var instanciate = function (name, params) {
  34287. var newInstance = Object.create(BABYLON[name].prototype);
  34288. newInstance.constructor.apply(newInstance, params);
  34289. return newInstance;
  34290. };
  34291. var parseParameter = function (name, value, target, propertyPath) {
  34292. if (propertyPath === null) {
  34293. // String, boolean or float
  34294. var floatValue = parseFloat(value);
  34295. if (value === "true" || value === "false")
  34296. return value === "true";
  34297. else
  34298. return isNaN(floatValue) ? value : floatValue;
  34299. }
  34300. var effectiveTarget = propertyPath.split(".");
  34301. var values = value.split(",");
  34302. // Get effective Target
  34303. for (var i = 0; i < effectiveTarget.length; i++) {
  34304. target = target[effectiveTarget[i]];
  34305. }
  34306. // Return appropriate value with its type
  34307. if (typeof (target) === "boolean")
  34308. return values[0] === "true";
  34309. if (typeof (target) === "string")
  34310. return values[0];
  34311. // Parameters with multiple values such as Vector3 etc.
  34312. var split = new Array();
  34313. for (var i = 0; i < values.length; i++)
  34314. split.push(parseFloat(values[i]));
  34315. if (target instanceof BABYLON.Vector3)
  34316. return BABYLON.Vector3.FromArray(split);
  34317. if (target instanceof BABYLON.Vector4)
  34318. return BABYLON.Vector4.FromArray(split);
  34319. if (target instanceof BABYLON.Color3)
  34320. return BABYLON.Color3.FromArray(split);
  34321. if (target instanceof BABYLON.Color4)
  34322. return BABYLON.Color4.FromArray(split);
  34323. return parseFloat(values[0]);
  34324. };
  34325. // traverse graph per trigger
  34326. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  34327. if (combineArray === void 0) { combineArray = null; }
  34328. if (parsedAction.detached)
  34329. return;
  34330. var parameters = new Array();
  34331. var target = null;
  34332. var propertyPath = null;
  34333. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  34334. // Parameters
  34335. if (parsedAction.type === 2)
  34336. parameters.push(actionManager);
  34337. else
  34338. parameters.push(trigger);
  34339. if (combine) {
  34340. var actions = new Array();
  34341. for (var j = 0; j < parsedAction.combine.length; j++) {
  34342. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  34343. }
  34344. parameters.push(actions);
  34345. }
  34346. else {
  34347. for (var i = 0; i < parsedAction.properties.length; i++) {
  34348. var value = parsedAction.properties[i].value;
  34349. var name = parsedAction.properties[i].name;
  34350. var targetType = parsedAction.properties[i].targetType;
  34351. if (name === "target")
  34352. if (targetType !== null && targetType === "SceneProperties")
  34353. value = target = scene;
  34354. else
  34355. value = target = scene.getNodeByName(value);
  34356. else if (name === "parent")
  34357. value = scene.getNodeByName(value);
  34358. else if (name === "sound")
  34359. value = scene.getSoundByName(value);
  34360. else if (name !== "propertyPath") {
  34361. if (parsedAction.type === 2 && name === "operator")
  34362. value = BABYLON.ValueCondition[value];
  34363. else
  34364. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  34365. }
  34366. else {
  34367. propertyPath = value;
  34368. }
  34369. parameters.push(value);
  34370. }
  34371. }
  34372. if (combineArray === null) {
  34373. parameters.push(condition);
  34374. }
  34375. else {
  34376. parameters.push(null);
  34377. }
  34378. // If interpolate value action
  34379. if (parsedAction.name === "InterpolateValueAction") {
  34380. var param = parameters[parameters.length - 2];
  34381. parameters[parameters.length - 1] = param;
  34382. parameters[parameters.length - 2] = condition;
  34383. }
  34384. // Action or condition(s) and not CombineAction
  34385. var newAction = instanciate(parsedAction.name, parameters);
  34386. if (newAction instanceof BABYLON.Condition && condition !== null) {
  34387. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  34388. if (action)
  34389. action.then(nothing);
  34390. else
  34391. actionManager.registerAction(nothing);
  34392. action = nothing;
  34393. }
  34394. if (combineArray === null) {
  34395. if (newAction instanceof BABYLON.Condition) {
  34396. condition = newAction;
  34397. newAction = action;
  34398. }
  34399. else {
  34400. condition = null;
  34401. if (action)
  34402. action.then(newAction);
  34403. else
  34404. actionManager.registerAction(newAction);
  34405. }
  34406. }
  34407. else {
  34408. combineArray.push(newAction);
  34409. }
  34410. for (var i = 0; i < parsedAction.children.length; i++)
  34411. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  34412. };
  34413. // triggers
  34414. for (var i = 0; i < parsedActions.children.length; i++) {
  34415. var triggerParams;
  34416. var trigger = parsedActions.children[i];
  34417. if (trigger.properties.length > 0) {
  34418. var param = trigger.properties[0].value;
  34419. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  34420. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  34421. }
  34422. else
  34423. triggerParams = BABYLON.ActionManager[trigger.name];
  34424. for (var j = 0; j < trigger.children.length; j++) {
  34425. if (!trigger.detached)
  34426. traverse(trigger.children[j], triggerParams, null, null);
  34427. }
  34428. }
  34429. };
  34430. ActionManager.GetTriggerName = function (trigger) {
  34431. switch (trigger) {
  34432. case 0: return "NothingTrigger";
  34433. case 1: return "OnPickTrigger";
  34434. case 2: return "OnLeftPickTrigger";
  34435. case 3: return "OnRightPickTrigger";
  34436. case 4: return "OnCenterPickTrigger";
  34437. case 5: return "OnPickDownTrigger";
  34438. case 6: return "OnPickUpTrigger";
  34439. case 7: return "OnLongPressTrigger";
  34440. case 8: return "OnPointerOverTrigger";
  34441. case 9: return "OnPointerOutTrigger";
  34442. case 10: return "OnEveryFrameTrigger";
  34443. case 11: return "OnIntersectionEnterTrigger";
  34444. case 12: return "OnIntersectionExitTrigger";
  34445. case 13: return "OnKeyDownTrigger";
  34446. case 14: return "OnKeyUpTrigger";
  34447. case 15: return "OnPickOutTrigger";
  34448. default: return "";
  34449. }
  34450. };
  34451. // Statics
  34452. ActionManager._NothingTrigger = 0;
  34453. ActionManager._OnPickTrigger = 1;
  34454. ActionManager._OnLeftPickTrigger = 2;
  34455. ActionManager._OnRightPickTrigger = 3;
  34456. ActionManager._OnCenterPickTrigger = 4;
  34457. ActionManager._OnPickDownTrigger = 5;
  34458. ActionManager._OnPickUpTrigger = 6;
  34459. ActionManager._OnLongPressTrigger = 7;
  34460. ActionManager._OnPointerOverTrigger = 8;
  34461. ActionManager._OnPointerOutTrigger = 9;
  34462. ActionManager._OnEveryFrameTrigger = 10;
  34463. ActionManager._OnIntersectionEnterTrigger = 11;
  34464. ActionManager._OnIntersectionExitTrigger = 12;
  34465. ActionManager._OnKeyDownTrigger = 13;
  34466. ActionManager._OnKeyUpTrigger = 14;
  34467. ActionManager._OnPickOutTrigger = 15;
  34468. ActionManager.DragMovementThreshold = 10; // in pixels
  34469. ActionManager.LongPressDelay = 500; // in milliseconds
  34470. return ActionManager;
  34471. }());
  34472. BABYLON.ActionManager = ActionManager;
  34473. })(BABYLON || (BABYLON = {}));
  34474. var BABYLON;
  34475. (function (BABYLON) {
  34476. var InterpolateValueAction = (function (_super) {
  34477. __extends(InterpolateValueAction, _super);
  34478. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  34479. if (duration === void 0) { duration = 1000; }
  34480. _super.call(this, triggerOptions, condition);
  34481. this.propertyPath = propertyPath;
  34482. this.value = value;
  34483. this.duration = duration;
  34484. this.stopOtherAnimations = stopOtherAnimations;
  34485. this.onInterpolationDone = onInterpolationDone;
  34486. this._target = this._effectiveTarget = target;
  34487. }
  34488. InterpolateValueAction.prototype._prepare = function () {
  34489. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34490. this._property = this._getProperty(this.propertyPath);
  34491. };
  34492. InterpolateValueAction.prototype.execute = function () {
  34493. var scene = this._actionManager.getScene();
  34494. var keys = [
  34495. {
  34496. frame: 0,
  34497. value: this._effectiveTarget[this._property]
  34498. }, {
  34499. frame: 100,
  34500. value: this.value
  34501. }
  34502. ];
  34503. var dataType;
  34504. if (typeof this.value === "number") {
  34505. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  34506. }
  34507. else if (this.value instanceof BABYLON.Color3) {
  34508. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  34509. }
  34510. else if (this.value instanceof BABYLON.Vector3) {
  34511. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  34512. }
  34513. else if (this.value instanceof BABYLON.Matrix) {
  34514. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  34515. }
  34516. else if (this.value instanceof BABYLON.Quaternion) {
  34517. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  34518. }
  34519. else {
  34520. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  34521. return;
  34522. }
  34523. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  34524. animation.setKeys(keys);
  34525. if (this.stopOtherAnimations) {
  34526. scene.stopAnimation(this._effectiveTarget);
  34527. }
  34528. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  34529. };
  34530. InterpolateValueAction.prototype.serialize = function (parent) {
  34531. return _super.prototype._serialize.call(this, {
  34532. name: "InterpolateValueAction",
  34533. properties: [
  34534. BABYLON.Action._GetTargetProperty(this._target),
  34535. { name: "propertyPath", value: this.propertyPath },
  34536. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  34537. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  34538. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  34539. ]
  34540. }, parent);
  34541. };
  34542. return InterpolateValueAction;
  34543. }(BABYLON.Action));
  34544. BABYLON.InterpolateValueAction = InterpolateValueAction;
  34545. })(BABYLON || (BABYLON = {}));
  34546. var BABYLON;
  34547. (function (BABYLON) {
  34548. var SwitchBooleanAction = (function (_super) {
  34549. __extends(SwitchBooleanAction, _super);
  34550. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  34551. _super.call(this, triggerOptions, condition);
  34552. this.propertyPath = propertyPath;
  34553. this._target = this._effectiveTarget = target;
  34554. }
  34555. SwitchBooleanAction.prototype._prepare = function () {
  34556. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34557. this._property = this._getProperty(this.propertyPath);
  34558. };
  34559. SwitchBooleanAction.prototype.execute = function () {
  34560. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  34561. };
  34562. SwitchBooleanAction.prototype.serialize = function (parent) {
  34563. return _super.prototype._serialize.call(this, {
  34564. name: "SwitchBooleanAction",
  34565. properties: [
  34566. BABYLON.Action._GetTargetProperty(this._target),
  34567. { name: "propertyPath", value: this.propertyPath }
  34568. ]
  34569. }, parent);
  34570. };
  34571. return SwitchBooleanAction;
  34572. }(BABYLON.Action));
  34573. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  34574. var SetStateAction = (function (_super) {
  34575. __extends(SetStateAction, _super);
  34576. function SetStateAction(triggerOptions, target, value, condition) {
  34577. _super.call(this, triggerOptions, condition);
  34578. this.value = value;
  34579. this._target = target;
  34580. }
  34581. SetStateAction.prototype.execute = function () {
  34582. this._target.state = this.value;
  34583. };
  34584. SetStateAction.prototype.serialize = function (parent) {
  34585. return _super.prototype._serialize.call(this, {
  34586. name: "SetStateAction",
  34587. properties: [
  34588. BABYLON.Action._GetTargetProperty(this._target),
  34589. { name: "value", value: this.value }
  34590. ]
  34591. }, parent);
  34592. };
  34593. return SetStateAction;
  34594. }(BABYLON.Action));
  34595. BABYLON.SetStateAction = SetStateAction;
  34596. var SetValueAction = (function (_super) {
  34597. __extends(SetValueAction, _super);
  34598. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  34599. _super.call(this, triggerOptions, condition);
  34600. this.propertyPath = propertyPath;
  34601. this.value = value;
  34602. this._target = this._effectiveTarget = target;
  34603. }
  34604. SetValueAction.prototype._prepare = function () {
  34605. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34606. this._property = this._getProperty(this.propertyPath);
  34607. };
  34608. SetValueAction.prototype.execute = function () {
  34609. this._effectiveTarget[this._property] = this.value;
  34610. if (this._target.markAsDirty) {
  34611. this._target.markAsDirty(this._property);
  34612. }
  34613. };
  34614. SetValueAction.prototype.serialize = function (parent) {
  34615. return _super.prototype._serialize.call(this, {
  34616. name: "SetValueAction",
  34617. properties: [
  34618. BABYLON.Action._GetTargetProperty(this._target),
  34619. { name: "propertyPath", value: this.propertyPath },
  34620. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34621. ]
  34622. }, parent);
  34623. };
  34624. return SetValueAction;
  34625. }(BABYLON.Action));
  34626. BABYLON.SetValueAction = SetValueAction;
  34627. var IncrementValueAction = (function (_super) {
  34628. __extends(IncrementValueAction, _super);
  34629. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  34630. _super.call(this, triggerOptions, condition);
  34631. this.propertyPath = propertyPath;
  34632. this.value = value;
  34633. this._target = this._effectiveTarget = target;
  34634. }
  34635. IncrementValueAction.prototype._prepare = function () {
  34636. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  34637. this._property = this._getProperty(this.propertyPath);
  34638. if (typeof this._effectiveTarget[this._property] !== "number") {
  34639. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  34640. }
  34641. };
  34642. IncrementValueAction.prototype.execute = function () {
  34643. this._effectiveTarget[this._property] += this.value;
  34644. if (this._target.markAsDirty) {
  34645. this._target.markAsDirty(this._property);
  34646. }
  34647. };
  34648. IncrementValueAction.prototype.serialize = function (parent) {
  34649. return _super.prototype._serialize.call(this, {
  34650. name: "IncrementValueAction",
  34651. properties: [
  34652. BABYLON.Action._GetTargetProperty(this._target),
  34653. { name: "propertyPath", value: this.propertyPath },
  34654. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  34655. ]
  34656. }, parent);
  34657. };
  34658. return IncrementValueAction;
  34659. }(BABYLON.Action));
  34660. BABYLON.IncrementValueAction = IncrementValueAction;
  34661. var PlayAnimationAction = (function (_super) {
  34662. __extends(PlayAnimationAction, _super);
  34663. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  34664. _super.call(this, triggerOptions, condition);
  34665. this.from = from;
  34666. this.to = to;
  34667. this.loop = loop;
  34668. this._target = target;
  34669. }
  34670. PlayAnimationAction.prototype._prepare = function () {
  34671. };
  34672. PlayAnimationAction.prototype.execute = function () {
  34673. var scene = this._actionManager.getScene();
  34674. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  34675. };
  34676. PlayAnimationAction.prototype.serialize = function (parent) {
  34677. return _super.prototype._serialize.call(this, {
  34678. name: "PlayAnimationAction",
  34679. properties: [
  34680. BABYLON.Action._GetTargetProperty(this._target),
  34681. { name: "from", value: String(this.from) },
  34682. { name: "to", value: String(this.to) },
  34683. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  34684. ]
  34685. }, parent);
  34686. };
  34687. return PlayAnimationAction;
  34688. }(BABYLON.Action));
  34689. BABYLON.PlayAnimationAction = PlayAnimationAction;
  34690. var StopAnimationAction = (function (_super) {
  34691. __extends(StopAnimationAction, _super);
  34692. function StopAnimationAction(triggerOptions, target, condition) {
  34693. _super.call(this, triggerOptions, condition);
  34694. this._target = target;
  34695. }
  34696. StopAnimationAction.prototype._prepare = function () {
  34697. };
  34698. StopAnimationAction.prototype.execute = function () {
  34699. var scene = this._actionManager.getScene();
  34700. scene.stopAnimation(this._target);
  34701. };
  34702. StopAnimationAction.prototype.serialize = function (parent) {
  34703. return _super.prototype._serialize.call(this, {
  34704. name: "StopAnimationAction",
  34705. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  34706. }, parent);
  34707. };
  34708. return StopAnimationAction;
  34709. }(BABYLON.Action));
  34710. BABYLON.StopAnimationAction = StopAnimationAction;
  34711. var DoNothingAction = (function (_super) {
  34712. __extends(DoNothingAction, _super);
  34713. function DoNothingAction(triggerOptions, condition) {
  34714. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  34715. _super.call(this, triggerOptions, condition);
  34716. }
  34717. DoNothingAction.prototype.execute = function () {
  34718. };
  34719. DoNothingAction.prototype.serialize = function (parent) {
  34720. return _super.prototype._serialize.call(this, {
  34721. name: "DoNothingAction",
  34722. properties: []
  34723. }, parent);
  34724. };
  34725. return DoNothingAction;
  34726. }(BABYLON.Action));
  34727. BABYLON.DoNothingAction = DoNothingAction;
  34728. var CombineAction = (function (_super) {
  34729. __extends(CombineAction, _super);
  34730. function CombineAction(triggerOptions, children, condition) {
  34731. _super.call(this, triggerOptions, condition);
  34732. this.children = children;
  34733. }
  34734. CombineAction.prototype._prepare = function () {
  34735. for (var index = 0; index < this.children.length; index++) {
  34736. this.children[index]._actionManager = this._actionManager;
  34737. this.children[index]._prepare();
  34738. }
  34739. };
  34740. CombineAction.prototype.execute = function (evt) {
  34741. for (var index = 0; index < this.children.length; index++) {
  34742. this.children[index].execute(evt);
  34743. }
  34744. };
  34745. CombineAction.prototype.serialize = function (parent) {
  34746. var serializationObject = _super.prototype._serialize.call(this, {
  34747. name: "CombineAction",
  34748. properties: [],
  34749. combine: []
  34750. }, parent);
  34751. for (var i = 0; i < this.children.length; i++) {
  34752. serializationObject.combine.push(this.children[i].serialize(null));
  34753. }
  34754. return serializationObject;
  34755. };
  34756. return CombineAction;
  34757. }(BABYLON.Action));
  34758. BABYLON.CombineAction = CombineAction;
  34759. var ExecuteCodeAction = (function (_super) {
  34760. __extends(ExecuteCodeAction, _super);
  34761. function ExecuteCodeAction(triggerOptions, func, condition) {
  34762. _super.call(this, triggerOptions, condition);
  34763. this.func = func;
  34764. }
  34765. ExecuteCodeAction.prototype.execute = function (evt) {
  34766. this.func(evt);
  34767. };
  34768. return ExecuteCodeAction;
  34769. }(BABYLON.Action));
  34770. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  34771. var SetParentAction = (function (_super) {
  34772. __extends(SetParentAction, _super);
  34773. function SetParentAction(triggerOptions, target, parent, condition) {
  34774. _super.call(this, triggerOptions, condition);
  34775. this._target = target;
  34776. this._parent = parent;
  34777. }
  34778. SetParentAction.prototype._prepare = function () {
  34779. };
  34780. SetParentAction.prototype.execute = function () {
  34781. if (this._target.parent === this._parent) {
  34782. return;
  34783. }
  34784. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  34785. invertParentWorldMatrix.invert();
  34786. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  34787. this._target.parent = this._parent;
  34788. };
  34789. SetParentAction.prototype.serialize = function (parent) {
  34790. return _super.prototype._serialize.call(this, {
  34791. name: "SetParentAction",
  34792. properties: [
  34793. BABYLON.Action._GetTargetProperty(this._target),
  34794. BABYLON.Action._GetTargetProperty(this._parent),
  34795. ]
  34796. }, parent);
  34797. };
  34798. return SetParentAction;
  34799. }(BABYLON.Action));
  34800. BABYLON.SetParentAction = SetParentAction;
  34801. var PlaySoundAction = (function (_super) {
  34802. __extends(PlaySoundAction, _super);
  34803. function PlaySoundAction(triggerOptions, sound, condition) {
  34804. _super.call(this, triggerOptions, condition);
  34805. this._sound = sound;
  34806. }
  34807. PlaySoundAction.prototype._prepare = function () {
  34808. };
  34809. PlaySoundAction.prototype.execute = function () {
  34810. if (this._sound !== undefined)
  34811. this._sound.play();
  34812. };
  34813. PlaySoundAction.prototype.serialize = function (parent) {
  34814. return _super.prototype._serialize.call(this, {
  34815. name: "PlaySoundAction",
  34816. properties: [{ name: "sound", value: this._sound.name }]
  34817. }, parent);
  34818. };
  34819. return PlaySoundAction;
  34820. }(BABYLON.Action));
  34821. BABYLON.PlaySoundAction = PlaySoundAction;
  34822. var StopSoundAction = (function (_super) {
  34823. __extends(StopSoundAction, _super);
  34824. function StopSoundAction(triggerOptions, sound, condition) {
  34825. _super.call(this, triggerOptions, condition);
  34826. this._sound = sound;
  34827. }
  34828. StopSoundAction.prototype._prepare = function () {
  34829. };
  34830. StopSoundAction.prototype.execute = function () {
  34831. if (this._sound !== undefined)
  34832. this._sound.stop();
  34833. };
  34834. StopSoundAction.prototype.serialize = function (parent) {
  34835. return _super.prototype._serialize.call(this, {
  34836. name: "StopSoundAction",
  34837. properties: [{ name: "sound", value: this._sound.name }]
  34838. }, parent);
  34839. };
  34840. return StopSoundAction;
  34841. }(BABYLON.Action));
  34842. BABYLON.StopSoundAction = StopSoundAction;
  34843. })(BABYLON || (BABYLON = {}));
  34844. var BABYLON;
  34845. (function (BABYLON) {
  34846. var Geometry = (function () {
  34847. function Geometry(id, scene, vertexData, updatable, mesh) {
  34848. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  34849. this._totalVertices = 0;
  34850. this._isDisposed = false;
  34851. this.id = id;
  34852. this._engine = scene.getEngine();
  34853. this._meshes = [];
  34854. this._scene = scene;
  34855. //Init vertex buffer cache
  34856. this._vertexBuffers = {};
  34857. this._indices = [];
  34858. // vertexData
  34859. if (vertexData) {
  34860. this.setAllVerticesData(vertexData, updatable);
  34861. }
  34862. else {
  34863. this._totalVertices = 0;
  34864. this._indices = [];
  34865. }
  34866. // applyToMesh
  34867. if (mesh) {
  34868. if (mesh instanceof BABYLON.LinesMesh) {
  34869. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  34870. this.updateExtend();
  34871. }
  34872. this.applyToMesh(mesh);
  34873. mesh.computeWorldMatrix(true);
  34874. }
  34875. }
  34876. Object.defineProperty(Geometry.prototype, "boundingBias", {
  34877. /**
  34878. * 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
  34879. * @returns The Bias Vector
  34880. */
  34881. get: function () {
  34882. return this._boundingBias;
  34883. },
  34884. set: function (value) {
  34885. if (this._boundingBias && this._boundingBias.equals(value)) {
  34886. return;
  34887. }
  34888. this._boundingBias = value.clone();
  34889. this.updateBoundingInfo(true, null);
  34890. },
  34891. enumerable: true,
  34892. configurable: true
  34893. });
  34894. Object.defineProperty(Geometry.prototype, "extend", {
  34895. get: function () {
  34896. return this._extend;
  34897. },
  34898. enumerable: true,
  34899. configurable: true
  34900. });
  34901. Geometry.prototype.getScene = function () {
  34902. return this._scene;
  34903. };
  34904. Geometry.prototype.getEngine = function () {
  34905. return this._engine;
  34906. };
  34907. Geometry.prototype.isReady = function () {
  34908. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  34909. };
  34910. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  34911. vertexData.applyToGeometry(this, updatable);
  34912. this.notifyUpdate();
  34913. };
  34914. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  34915. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  34916. this.setVerticesBuffer(buffer);
  34917. };
  34918. Geometry.prototype.setVerticesBuffer = function (buffer) {
  34919. var kind = buffer.getKind();
  34920. if (this._vertexBuffers[kind]) {
  34921. this._vertexBuffers[kind].dispose();
  34922. }
  34923. this._vertexBuffers[kind] = buffer;
  34924. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34925. var data = buffer.getData();
  34926. var stride = buffer.getStrideSize();
  34927. this._totalVertices = data.length / stride;
  34928. this.updateExtend(data, stride);
  34929. var meshes = this._meshes;
  34930. var numOfMeshes = meshes.length;
  34931. for (var index = 0; index < numOfMeshes; index++) {
  34932. var mesh = meshes[index];
  34933. mesh._resetPointsArrayCache();
  34934. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34935. mesh._createGlobalSubMesh();
  34936. mesh.computeWorldMatrix(true);
  34937. }
  34938. }
  34939. this.notifyUpdate(kind);
  34940. };
  34941. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  34942. var vertexBuffer = this.getVertexBuffer(kind);
  34943. if (!vertexBuffer) {
  34944. return;
  34945. }
  34946. vertexBuffer.updateDirectly(data, offset);
  34947. this.notifyUpdate(kind);
  34948. };
  34949. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  34950. var vertexBuffer = this.getVertexBuffer(kind);
  34951. if (!vertexBuffer) {
  34952. return;
  34953. }
  34954. vertexBuffer.update(data);
  34955. if (kind === BABYLON.VertexBuffer.PositionKind) {
  34956. var stride = vertexBuffer.getStrideSize();
  34957. this._totalVertices = data.length / stride;
  34958. this.updateBoundingInfo(updateExtends, data);
  34959. }
  34960. this.notifyUpdate(kind);
  34961. };
  34962. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  34963. if (updateExtends) {
  34964. this.updateExtend(data);
  34965. }
  34966. var meshes = this._meshes;
  34967. var numOfMeshes = meshes.length;
  34968. for (var index = 0; index < numOfMeshes; index++) {
  34969. var mesh = meshes[index];
  34970. mesh._resetPointsArrayCache();
  34971. if (updateExtends) {
  34972. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  34973. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  34974. var subMesh = mesh.subMeshes[subIndex];
  34975. subMesh.refreshBoundingInfo();
  34976. }
  34977. }
  34978. }
  34979. };
  34980. Geometry.prototype.getTotalVertices = function () {
  34981. if (!this.isReady()) {
  34982. return 0;
  34983. }
  34984. return this._totalVertices;
  34985. };
  34986. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  34987. var vertexBuffer = this.getVertexBuffer(kind);
  34988. if (!vertexBuffer) {
  34989. return null;
  34990. }
  34991. var orig = vertexBuffer.getData();
  34992. if (!copyWhenShared || this._meshes.length === 1) {
  34993. return orig;
  34994. }
  34995. else {
  34996. var len = orig.length;
  34997. var copy = [];
  34998. for (var i = 0; i < len; i++) {
  34999. copy.push(orig[i]);
  35000. }
  35001. return copy;
  35002. }
  35003. };
  35004. Geometry.prototype.getVertexBuffer = function (kind) {
  35005. if (!this.isReady()) {
  35006. return null;
  35007. }
  35008. return this._vertexBuffers[kind];
  35009. };
  35010. Geometry.prototype.getVertexBuffers = function () {
  35011. if (!this.isReady()) {
  35012. return null;
  35013. }
  35014. return this._vertexBuffers;
  35015. };
  35016. Geometry.prototype.isVerticesDataPresent = function (kind) {
  35017. if (!this._vertexBuffers) {
  35018. if (this._delayInfo) {
  35019. return this._delayInfo.indexOf(kind) !== -1;
  35020. }
  35021. return false;
  35022. }
  35023. return this._vertexBuffers[kind] !== undefined;
  35024. };
  35025. Geometry.prototype.getVerticesDataKinds = function () {
  35026. var result = [];
  35027. var kind;
  35028. if (!this._vertexBuffers && this._delayInfo) {
  35029. for (kind in this._delayInfo) {
  35030. result.push(kind);
  35031. }
  35032. }
  35033. else {
  35034. for (kind in this._vertexBuffers) {
  35035. result.push(kind);
  35036. }
  35037. }
  35038. return result;
  35039. };
  35040. Geometry.prototype.setIndices = function (indices, totalVertices) {
  35041. if (this._indexBuffer) {
  35042. this._engine._releaseBuffer(this._indexBuffer);
  35043. }
  35044. this._indices = indices;
  35045. if (this._meshes.length !== 0 && this._indices) {
  35046. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35047. }
  35048. if (totalVertices !== undefined) {
  35049. this._totalVertices = totalVertices;
  35050. }
  35051. var meshes = this._meshes;
  35052. var numOfMeshes = meshes.length;
  35053. for (var index = 0; index < numOfMeshes; index++) {
  35054. meshes[index]._createGlobalSubMesh();
  35055. }
  35056. this.notifyUpdate();
  35057. };
  35058. Geometry.prototype.getTotalIndices = function () {
  35059. if (!this.isReady()) {
  35060. return 0;
  35061. }
  35062. return this._indices.length;
  35063. };
  35064. Geometry.prototype.getIndices = function (copyWhenShared) {
  35065. if (!this.isReady()) {
  35066. return null;
  35067. }
  35068. var orig = this._indices;
  35069. if (!copyWhenShared || this._meshes.length === 1) {
  35070. return orig;
  35071. }
  35072. else {
  35073. var len = orig.length;
  35074. var copy = [];
  35075. for (var i = 0; i < len; i++) {
  35076. copy.push(orig[i]);
  35077. }
  35078. return copy;
  35079. }
  35080. };
  35081. Geometry.prototype.getIndexBuffer = function () {
  35082. if (!this.isReady()) {
  35083. return null;
  35084. }
  35085. return this._indexBuffer;
  35086. };
  35087. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  35088. var meshes = this._meshes;
  35089. var index = meshes.indexOf(mesh);
  35090. if (index === -1) {
  35091. return;
  35092. }
  35093. for (var kind in this._vertexBuffers) {
  35094. this._vertexBuffers[kind].dispose();
  35095. }
  35096. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  35097. this._indexBuffer = null;
  35098. }
  35099. meshes.splice(index, 1);
  35100. mesh._geometry = null;
  35101. if (meshes.length === 0 && shouldDispose) {
  35102. this.dispose();
  35103. }
  35104. };
  35105. Geometry.prototype.applyToMesh = function (mesh) {
  35106. if (mesh._geometry === this) {
  35107. return;
  35108. }
  35109. var previousGeometry = mesh._geometry;
  35110. if (previousGeometry) {
  35111. previousGeometry.releaseForMesh(mesh);
  35112. }
  35113. var meshes = this._meshes;
  35114. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  35115. mesh._geometry = this;
  35116. this._scene.pushGeometry(this);
  35117. meshes.push(mesh);
  35118. if (this.isReady()) {
  35119. this._applyToMesh(mesh);
  35120. }
  35121. else {
  35122. mesh._boundingInfo = this._boundingInfo;
  35123. }
  35124. };
  35125. Geometry.prototype.updateExtend = function (data, stride) {
  35126. if (data === void 0) { data = null; }
  35127. if (!data) {
  35128. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  35129. }
  35130. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  35131. };
  35132. Geometry.prototype._applyToMesh = function (mesh) {
  35133. var numOfMeshes = this._meshes.length;
  35134. // vertexBuffers
  35135. for (var kind in this._vertexBuffers) {
  35136. if (numOfMeshes === 1) {
  35137. this._vertexBuffers[kind].create();
  35138. }
  35139. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  35140. if (kind === BABYLON.VertexBuffer.PositionKind) {
  35141. mesh._resetPointsArrayCache();
  35142. if (!this._extend) {
  35143. this.updateExtend(this._vertexBuffers[kind].getData());
  35144. }
  35145. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35146. mesh._createGlobalSubMesh();
  35147. //bounding info was just created again, world matrix should be applied again.
  35148. mesh._updateBoundingInfo();
  35149. }
  35150. }
  35151. // indexBuffer
  35152. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  35153. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  35154. }
  35155. if (this._indexBuffer) {
  35156. this._indexBuffer.references = numOfMeshes;
  35157. }
  35158. };
  35159. Geometry.prototype.notifyUpdate = function (kind) {
  35160. if (this.onGeometryUpdated) {
  35161. this.onGeometryUpdated(this, kind);
  35162. }
  35163. };
  35164. Geometry.prototype.load = function (scene, onLoaded) {
  35165. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  35166. return;
  35167. }
  35168. if (this.isReady()) {
  35169. if (onLoaded) {
  35170. onLoaded();
  35171. }
  35172. return;
  35173. }
  35174. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  35175. this._queueLoad(scene, onLoaded);
  35176. };
  35177. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  35178. var _this = this;
  35179. scene._addPendingData(this);
  35180. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  35181. _this._delayLoadingFunction(JSON.parse(data), _this);
  35182. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  35183. _this._delayInfo = [];
  35184. scene._removePendingData(_this);
  35185. var meshes = _this._meshes;
  35186. var numOfMeshes = meshes.length;
  35187. for (var index = 0; index < numOfMeshes; index++) {
  35188. _this._applyToMesh(meshes[index]);
  35189. }
  35190. if (onLoaded) {
  35191. onLoaded();
  35192. }
  35193. }, function () { }, scene.database);
  35194. };
  35195. /**
  35196. * Invert the geometry to move from a right handed system to a left handed one.
  35197. */
  35198. Geometry.prototype.toLeftHanded = function () {
  35199. // Flip faces
  35200. var tIndices = this.getIndices(false);
  35201. if (tIndices != null && tIndices.length > 0) {
  35202. for (var i = 0; i < tIndices.length; i += 3) {
  35203. var tTemp = tIndices[i + 0];
  35204. tIndices[i + 0] = tIndices[i + 2];
  35205. tIndices[i + 2] = tTemp;
  35206. }
  35207. this.setIndices(tIndices);
  35208. }
  35209. // Negate position.z
  35210. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  35211. if (tPositions != null && tPositions.length > 0) {
  35212. for (var i = 0; i < tPositions.length; i += 3) {
  35213. tPositions[i + 2] = -tPositions[i + 2];
  35214. }
  35215. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  35216. }
  35217. // Negate normal.z
  35218. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  35219. if (tNormals != null && tNormals.length > 0) {
  35220. for (var i = 0; i < tNormals.length; i += 3) {
  35221. tNormals[i + 2] = -tNormals[i + 2];
  35222. }
  35223. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  35224. }
  35225. };
  35226. Geometry.prototype.isDisposed = function () {
  35227. return this._isDisposed;
  35228. };
  35229. Geometry.prototype.dispose = function () {
  35230. var meshes = this._meshes;
  35231. var numOfMeshes = meshes.length;
  35232. var index;
  35233. for (index = 0; index < numOfMeshes; index++) {
  35234. this.releaseForMesh(meshes[index]);
  35235. }
  35236. this._meshes = [];
  35237. for (var kind in this._vertexBuffers) {
  35238. this._vertexBuffers[kind].dispose();
  35239. }
  35240. this._vertexBuffers = {};
  35241. this._totalVertices = 0;
  35242. if (this._indexBuffer) {
  35243. this._engine._releaseBuffer(this._indexBuffer);
  35244. }
  35245. this._indexBuffer = null;
  35246. this._indices = [];
  35247. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  35248. this.delayLoadingFile = null;
  35249. this._delayLoadingFunction = null;
  35250. this._delayInfo = [];
  35251. this._boundingInfo = null;
  35252. this._scene.removeGeometry(this);
  35253. this._isDisposed = true;
  35254. };
  35255. Geometry.prototype.copy = function (id) {
  35256. var vertexData = new BABYLON.VertexData();
  35257. vertexData.indices = [];
  35258. var indices = this.getIndices();
  35259. for (var index = 0; index < indices.length; index++) {
  35260. vertexData.indices.push(indices[index]);
  35261. }
  35262. var updatable = false;
  35263. var stopChecking = false;
  35264. var kind;
  35265. for (kind in this._vertexBuffers) {
  35266. // using slice() to make a copy of the array and not just reference it
  35267. var data = this.getVerticesData(kind);
  35268. if (data instanceof Float32Array) {
  35269. vertexData.set(new Float32Array(data), kind);
  35270. }
  35271. else {
  35272. vertexData.set(data.slice(0), kind);
  35273. }
  35274. if (!stopChecking) {
  35275. updatable = this.getVertexBuffer(kind).isUpdatable();
  35276. stopChecking = !updatable;
  35277. }
  35278. }
  35279. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  35280. geometry.delayLoadState = this.delayLoadState;
  35281. geometry.delayLoadingFile = this.delayLoadingFile;
  35282. geometry._delayLoadingFunction = this._delayLoadingFunction;
  35283. for (kind in this._delayInfo) {
  35284. geometry._delayInfo = geometry._delayInfo || [];
  35285. geometry._delayInfo.push(kind);
  35286. }
  35287. // Bounding info
  35288. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  35289. return geometry;
  35290. };
  35291. Geometry.prototype.serialize = function () {
  35292. var serializationObject = {};
  35293. serializationObject.id = this.id;
  35294. if (BABYLON.Tags.HasTags(this)) {
  35295. serializationObject.tags = BABYLON.Tags.GetTags(this);
  35296. }
  35297. return serializationObject;
  35298. };
  35299. Geometry.prototype.serializeVerticeData = function () {
  35300. var serializationObject = this.serialize();
  35301. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35302. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35303. }
  35304. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35305. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35306. }
  35307. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  35308. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  35309. }
  35310. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  35311. serializationObject.uvs2 = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  35312. }
  35313. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  35314. serializationObject.uvs3 = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  35315. }
  35316. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  35317. serializationObject.uvs4 = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  35318. }
  35319. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  35320. serializationObject.uvs5 = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  35321. }
  35322. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  35323. serializationObject.uvs6 = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  35324. }
  35325. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  35326. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  35327. }
  35328. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35329. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35330. serializationObject.matricesIndices._isExpanded = true;
  35331. }
  35332. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35333. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35334. }
  35335. serializationObject.indices = this.getIndices();
  35336. return serializationObject;
  35337. };
  35338. // Statics
  35339. Geometry.ExtractFromMesh = function (mesh, id) {
  35340. var geometry = mesh._geometry;
  35341. if (!geometry) {
  35342. return null;
  35343. }
  35344. return geometry.copy(id);
  35345. };
  35346. /**
  35347. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  35348. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  35349. * Be aware Math.random() could cause collisions, but:
  35350. * "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"
  35351. */
  35352. Geometry.RandomId = function () {
  35353. return BABYLON.Tools.RandomId();
  35354. };
  35355. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  35356. var scene = mesh.getScene();
  35357. // Geometry
  35358. var geometryId = parsedGeometry.geometryId;
  35359. if (geometryId) {
  35360. var geometry = scene.getGeometryByID(geometryId);
  35361. if (geometry) {
  35362. geometry.applyToMesh(mesh);
  35363. }
  35364. }
  35365. else if (parsedGeometry instanceof ArrayBuffer) {
  35366. var binaryInfo = mesh._binaryInfo;
  35367. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  35368. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  35369. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  35370. }
  35371. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  35372. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  35373. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  35374. }
  35375. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  35376. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  35377. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  35378. }
  35379. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  35380. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  35381. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  35382. }
  35383. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  35384. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  35385. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  35386. }
  35387. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  35388. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  35389. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  35390. }
  35391. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  35392. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  35393. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  35394. }
  35395. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  35396. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  35397. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  35398. }
  35399. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  35400. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  35401. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  35402. }
  35403. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  35404. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  35405. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  35406. }
  35407. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  35408. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  35409. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  35410. }
  35411. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  35412. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  35413. mesh.setIndices(indicesData);
  35414. }
  35415. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  35416. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  35417. mesh.subMeshes = [];
  35418. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  35419. var materialIndex = subMeshesData[(i * 5) + 0];
  35420. var verticesStart = subMeshesData[(i * 5) + 1];
  35421. var verticesCount = subMeshesData[(i * 5) + 2];
  35422. var indexStart = subMeshesData[(i * 5) + 3];
  35423. var indexCount = subMeshesData[(i * 5) + 4];
  35424. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  35425. }
  35426. }
  35427. }
  35428. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  35429. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  35430. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  35431. if (parsedGeometry.uvs) {
  35432. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  35433. }
  35434. if (parsedGeometry.uvs2) {
  35435. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  35436. }
  35437. if (parsedGeometry.uvs3) {
  35438. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  35439. }
  35440. if (parsedGeometry.uvs4) {
  35441. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  35442. }
  35443. if (parsedGeometry.uvs5) {
  35444. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  35445. }
  35446. if (parsedGeometry.uvs6) {
  35447. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  35448. }
  35449. if (parsedGeometry.colors) {
  35450. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  35451. }
  35452. if (parsedGeometry.matricesIndices) {
  35453. if (!parsedGeometry.matricesIndices._isExpanded) {
  35454. var floatIndices = [];
  35455. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  35456. var matricesIndex = parsedGeometry.matricesIndices[i];
  35457. floatIndices.push(matricesIndex & 0x000000FF);
  35458. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35459. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35460. floatIndices.push(matricesIndex >> 24);
  35461. }
  35462. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  35463. }
  35464. else {
  35465. delete parsedGeometry.matricesIndices._isExpanded;
  35466. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  35467. }
  35468. }
  35469. if (parsedGeometry.matricesIndicesExtra) {
  35470. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  35471. var floatIndices = [];
  35472. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  35473. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  35474. floatIndices.push(matricesIndex & 0x000000FF);
  35475. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  35476. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  35477. floatIndices.push(matricesIndex >> 24);
  35478. }
  35479. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  35480. }
  35481. else {
  35482. delete parsedGeometry.matricesIndices._isExpanded;
  35483. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  35484. }
  35485. }
  35486. if (parsedGeometry.matricesWeights) {
  35487. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  35488. }
  35489. if (parsedGeometry.matricesWeightsExtra) {
  35490. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  35491. }
  35492. mesh.setIndices(parsedGeometry.indices);
  35493. }
  35494. // SubMeshes
  35495. if (parsedGeometry.subMeshes) {
  35496. mesh.subMeshes = [];
  35497. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  35498. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  35499. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  35500. }
  35501. }
  35502. // Flat shading
  35503. if (mesh._shouldGenerateFlatShading) {
  35504. mesh.convertToFlatShadedMesh();
  35505. delete mesh._shouldGenerateFlatShading;
  35506. }
  35507. // Update
  35508. mesh.computeWorldMatrix(true);
  35509. // Octree
  35510. if (scene['_selectionOctree']) {
  35511. scene['_selectionOctree'].addMesh(mesh);
  35512. }
  35513. };
  35514. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  35515. if (scene.getGeometryByID(parsedVertexData.id)) {
  35516. return null; // null since geometry could be something else than a box...
  35517. }
  35518. var geometry = new Geometry(parsedVertexData.id, scene);
  35519. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  35520. if (parsedVertexData.delayLoadingFile) {
  35521. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  35522. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  35523. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  35524. geometry._delayInfo = [];
  35525. if (parsedVertexData.hasUVs) {
  35526. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  35527. }
  35528. if (parsedVertexData.hasUVs2) {
  35529. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  35530. }
  35531. if (parsedVertexData.hasUVs3) {
  35532. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  35533. }
  35534. if (parsedVertexData.hasUVs4) {
  35535. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  35536. }
  35537. if (parsedVertexData.hasUVs5) {
  35538. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  35539. }
  35540. if (parsedVertexData.hasUVs6) {
  35541. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  35542. }
  35543. if (parsedVertexData.hasColors) {
  35544. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  35545. }
  35546. if (parsedVertexData.hasMatricesIndices) {
  35547. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  35548. }
  35549. if (parsedVertexData.hasMatricesWeights) {
  35550. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  35551. }
  35552. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  35553. }
  35554. else {
  35555. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  35556. }
  35557. scene.pushGeometry(geometry, true);
  35558. return geometry;
  35559. };
  35560. return Geometry;
  35561. }());
  35562. BABYLON.Geometry = Geometry;
  35563. /////// Primitives //////////////////////////////////////////////
  35564. var Geometry;
  35565. (function (Geometry) {
  35566. var Primitives;
  35567. (function (Primitives) {
  35568. /// Abstract class
  35569. var _Primitive = (function (_super) {
  35570. __extends(_Primitive, _super);
  35571. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  35572. _super.call(this, id, scene, null, false, mesh); // updatable = false to be sure not to update vertices
  35573. this._canBeRegenerated = _canBeRegenerated;
  35574. this._beingRegenerated = true;
  35575. this.regenerate();
  35576. this._beingRegenerated = false;
  35577. }
  35578. _Primitive.prototype.canBeRegenerated = function () {
  35579. return this._canBeRegenerated;
  35580. };
  35581. _Primitive.prototype.regenerate = function () {
  35582. if (!this._canBeRegenerated) {
  35583. return;
  35584. }
  35585. this._beingRegenerated = true;
  35586. this.setAllVerticesData(this._regenerateVertexData(), false);
  35587. this._beingRegenerated = false;
  35588. };
  35589. _Primitive.prototype.asNewGeometry = function (id) {
  35590. return _super.prototype.copy.call(this, id);
  35591. };
  35592. // overrides
  35593. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  35594. if (!this._beingRegenerated) {
  35595. return;
  35596. }
  35597. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  35598. };
  35599. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  35600. if (!this._beingRegenerated) {
  35601. return;
  35602. }
  35603. _super.prototype.setVerticesData.call(this, kind, data, false);
  35604. };
  35605. // to override
  35606. // protected
  35607. _Primitive.prototype._regenerateVertexData = function () {
  35608. throw new Error("Abstract method");
  35609. };
  35610. _Primitive.prototype.copy = function (id) {
  35611. throw new Error("Must be overriden in sub-classes.");
  35612. };
  35613. _Primitive.prototype.serialize = function () {
  35614. var serializationObject = _super.prototype.serialize.call(this);
  35615. serializationObject.canBeRegenerated = this.canBeRegenerated();
  35616. return serializationObject;
  35617. };
  35618. return _Primitive;
  35619. }(Geometry));
  35620. Primitives._Primitive = _Primitive;
  35621. var Ribbon = (function (_super) {
  35622. __extends(Ribbon, _super);
  35623. // Members
  35624. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  35625. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35626. _super.call(this, id, scene, canBeRegenerated, mesh);
  35627. this.pathArray = pathArray;
  35628. this.closeArray = closeArray;
  35629. this.closePath = closePath;
  35630. this.offset = offset;
  35631. this.side = side;
  35632. }
  35633. Ribbon.prototype._regenerateVertexData = function () {
  35634. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  35635. };
  35636. Ribbon.prototype.copy = function (id) {
  35637. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  35638. };
  35639. return Ribbon;
  35640. }(_Primitive));
  35641. Primitives.Ribbon = Ribbon;
  35642. var Box = (function (_super) {
  35643. __extends(Box, _super);
  35644. // Members
  35645. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  35646. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35647. _super.call(this, id, scene, canBeRegenerated, mesh);
  35648. this.size = size;
  35649. this.side = side;
  35650. }
  35651. Box.prototype._regenerateVertexData = function () {
  35652. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  35653. };
  35654. Box.prototype.copy = function (id) {
  35655. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35656. };
  35657. Box.prototype.serialize = function () {
  35658. var serializationObject = _super.prototype.serialize.call(this);
  35659. serializationObject.size = this.size;
  35660. return serializationObject;
  35661. };
  35662. Box.Parse = function (parsedBox, scene) {
  35663. if (scene.getGeometryByID(parsedBox.id)) {
  35664. return null; // null since geometry could be something else than a box...
  35665. }
  35666. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  35667. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  35668. scene.pushGeometry(box, true);
  35669. return box;
  35670. };
  35671. return Box;
  35672. }(_Primitive));
  35673. Primitives.Box = Box;
  35674. var Sphere = (function (_super) {
  35675. __extends(Sphere, _super);
  35676. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  35677. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35678. _super.call(this, id, scene, canBeRegenerated, mesh);
  35679. this.segments = segments;
  35680. this.diameter = diameter;
  35681. this.side = side;
  35682. }
  35683. Sphere.prototype._regenerateVertexData = function () {
  35684. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  35685. };
  35686. Sphere.prototype.copy = function (id) {
  35687. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  35688. };
  35689. Sphere.prototype.serialize = function () {
  35690. var serializationObject = _super.prototype.serialize.call(this);
  35691. serializationObject.segments = this.segments;
  35692. serializationObject.diameter = this.diameter;
  35693. return serializationObject;
  35694. };
  35695. Sphere.Parse = function (parsedSphere, scene) {
  35696. if (scene.getGeometryByID(parsedSphere.id)) {
  35697. return null; // null since geometry could be something else than a sphere...
  35698. }
  35699. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  35700. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  35701. scene.pushGeometry(sphere, true);
  35702. return sphere;
  35703. };
  35704. return Sphere;
  35705. }(_Primitive));
  35706. Primitives.Sphere = Sphere;
  35707. var Disc = (function (_super) {
  35708. __extends(Disc, _super);
  35709. // Members
  35710. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  35711. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35712. _super.call(this, id, scene, canBeRegenerated, mesh);
  35713. this.radius = radius;
  35714. this.tessellation = tessellation;
  35715. this.side = side;
  35716. }
  35717. Disc.prototype._regenerateVertexData = function () {
  35718. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  35719. };
  35720. Disc.prototype.copy = function (id) {
  35721. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  35722. };
  35723. return Disc;
  35724. }(_Primitive));
  35725. Primitives.Disc = Disc;
  35726. var Cylinder = (function (_super) {
  35727. __extends(Cylinder, _super);
  35728. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  35729. if (subdivisions === void 0) { subdivisions = 1; }
  35730. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35731. _super.call(this, id, scene, canBeRegenerated, mesh);
  35732. this.height = height;
  35733. this.diameterTop = diameterTop;
  35734. this.diameterBottom = diameterBottom;
  35735. this.tessellation = tessellation;
  35736. this.subdivisions = subdivisions;
  35737. this.side = side;
  35738. }
  35739. Cylinder.prototype._regenerateVertexData = function () {
  35740. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  35741. };
  35742. Cylinder.prototype.copy = function (id) {
  35743. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  35744. };
  35745. Cylinder.prototype.serialize = function () {
  35746. var serializationObject = _super.prototype.serialize.call(this);
  35747. serializationObject.height = this.height;
  35748. serializationObject.diameterTop = this.diameterTop;
  35749. serializationObject.diameterBottom = this.diameterBottom;
  35750. serializationObject.tessellation = this.tessellation;
  35751. return serializationObject;
  35752. };
  35753. Cylinder.Parse = function (parsedCylinder, scene) {
  35754. if (scene.getGeometryByID(parsedCylinder.id)) {
  35755. return null; // null since geometry could be something else than a cylinder...
  35756. }
  35757. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  35758. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  35759. scene.pushGeometry(cylinder, true);
  35760. return cylinder;
  35761. };
  35762. return Cylinder;
  35763. }(_Primitive));
  35764. Primitives.Cylinder = Cylinder;
  35765. var Torus = (function (_super) {
  35766. __extends(Torus, _super);
  35767. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  35768. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35769. _super.call(this, id, scene, canBeRegenerated, mesh);
  35770. this.diameter = diameter;
  35771. this.thickness = thickness;
  35772. this.tessellation = tessellation;
  35773. this.side = side;
  35774. }
  35775. Torus.prototype._regenerateVertexData = function () {
  35776. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  35777. };
  35778. Torus.prototype.copy = function (id) {
  35779. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  35780. };
  35781. Torus.prototype.serialize = function () {
  35782. var serializationObject = _super.prototype.serialize.call(this);
  35783. serializationObject.diameter = this.diameter;
  35784. serializationObject.thickness = this.thickness;
  35785. serializationObject.tessellation = this.tessellation;
  35786. return serializationObject;
  35787. };
  35788. Torus.Parse = function (parsedTorus, scene) {
  35789. if (scene.getGeometryByID(parsedTorus.id)) {
  35790. return null; // null since geometry could be something else than a torus...
  35791. }
  35792. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  35793. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  35794. scene.pushGeometry(torus, true);
  35795. return torus;
  35796. };
  35797. return Torus;
  35798. }(_Primitive));
  35799. Primitives.Torus = Torus;
  35800. var Ground = (function (_super) {
  35801. __extends(Ground, _super);
  35802. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  35803. _super.call(this, id, scene, canBeRegenerated, mesh);
  35804. this.width = width;
  35805. this.height = height;
  35806. this.subdivisions = subdivisions;
  35807. }
  35808. Ground.prototype._regenerateVertexData = function () {
  35809. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  35810. };
  35811. Ground.prototype.copy = function (id) {
  35812. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  35813. };
  35814. Ground.prototype.serialize = function () {
  35815. var serializationObject = _super.prototype.serialize.call(this);
  35816. serializationObject.width = this.width;
  35817. serializationObject.height = this.height;
  35818. serializationObject.subdivisions = this.subdivisions;
  35819. return serializationObject;
  35820. };
  35821. Ground.Parse = function (parsedGround, scene) {
  35822. if (scene.getGeometryByID(parsedGround.id)) {
  35823. return null; // null since geometry could be something else than a ground...
  35824. }
  35825. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  35826. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  35827. scene.pushGeometry(ground, true);
  35828. return ground;
  35829. };
  35830. return Ground;
  35831. }(_Primitive));
  35832. Primitives.Ground = Ground;
  35833. var TiledGround = (function (_super) {
  35834. __extends(TiledGround, _super);
  35835. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  35836. _super.call(this, id, scene, canBeRegenerated, mesh);
  35837. this.xmin = xmin;
  35838. this.zmin = zmin;
  35839. this.xmax = xmax;
  35840. this.zmax = zmax;
  35841. this.subdivisions = subdivisions;
  35842. this.precision = precision;
  35843. }
  35844. TiledGround.prototype._regenerateVertexData = function () {
  35845. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  35846. };
  35847. TiledGround.prototype.copy = function (id) {
  35848. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  35849. };
  35850. return TiledGround;
  35851. }(_Primitive));
  35852. Primitives.TiledGround = TiledGround;
  35853. var Plane = (function (_super) {
  35854. __extends(Plane, _super);
  35855. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  35856. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35857. _super.call(this, id, scene, canBeRegenerated, mesh);
  35858. this.size = size;
  35859. this.side = side;
  35860. }
  35861. Plane.prototype._regenerateVertexData = function () {
  35862. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  35863. };
  35864. Plane.prototype.copy = function (id) {
  35865. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  35866. };
  35867. Plane.prototype.serialize = function () {
  35868. var serializationObject = _super.prototype.serialize.call(this);
  35869. serializationObject.size = this.size;
  35870. return serializationObject;
  35871. };
  35872. Plane.Parse = function (parsedPlane, scene) {
  35873. if (scene.getGeometryByID(parsedPlane.id)) {
  35874. return null; // null since geometry could be something else than a ground...
  35875. }
  35876. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  35877. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  35878. scene.pushGeometry(plane, true);
  35879. return plane;
  35880. };
  35881. return Plane;
  35882. }(_Primitive));
  35883. Primitives.Plane = Plane;
  35884. var TorusKnot = (function (_super) {
  35885. __extends(TorusKnot, _super);
  35886. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  35887. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  35888. _super.call(this, id, scene, canBeRegenerated, mesh);
  35889. this.radius = radius;
  35890. this.tube = tube;
  35891. this.radialSegments = radialSegments;
  35892. this.tubularSegments = tubularSegments;
  35893. this.p = p;
  35894. this.q = q;
  35895. this.side = side;
  35896. }
  35897. TorusKnot.prototype._regenerateVertexData = function () {
  35898. 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 });
  35899. };
  35900. TorusKnot.prototype.copy = function (id) {
  35901. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  35902. };
  35903. TorusKnot.prototype.serialize = function () {
  35904. var serializationObject = _super.prototype.serialize.call(this);
  35905. serializationObject.radius = this.radius;
  35906. serializationObject.tube = this.tube;
  35907. serializationObject.radialSegments = this.radialSegments;
  35908. serializationObject.tubularSegments = this.tubularSegments;
  35909. serializationObject.p = this.p;
  35910. serializationObject.q = this.q;
  35911. return serializationObject;
  35912. };
  35913. ;
  35914. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  35915. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  35916. return null; // null since geometry could be something else than a ground...
  35917. }
  35918. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  35919. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  35920. scene.pushGeometry(torusKnot, true);
  35921. return torusKnot;
  35922. };
  35923. return TorusKnot;
  35924. }(_Primitive));
  35925. Primitives.TorusKnot = TorusKnot;
  35926. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  35927. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  35928. })(BABYLON || (BABYLON = {}));
  35929. var BABYLON;
  35930. (function (BABYLON) {
  35931. var GroundMesh = (function (_super) {
  35932. __extends(GroundMesh, _super);
  35933. function GroundMesh(name, scene) {
  35934. _super.call(this, name, scene);
  35935. this.generateOctree = false;
  35936. this._worldInverse = new BABYLON.Matrix();
  35937. }
  35938. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  35939. get: function () {
  35940. return Math.min(this._subdivisionsX, this._subdivisionsY);
  35941. },
  35942. enumerable: true,
  35943. configurable: true
  35944. });
  35945. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  35946. get: function () {
  35947. return this._subdivisionsX;
  35948. },
  35949. enumerable: true,
  35950. configurable: true
  35951. });
  35952. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  35953. get: function () {
  35954. return this._subdivisionsY;
  35955. },
  35956. enumerable: true,
  35957. configurable: true
  35958. });
  35959. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  35960. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  35961. this._subdivisionsX = chunksCount;
  35962. this._subdivisionsY = chunksCount;
  35963. this.subdivide(chunksCount);
  35964. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  35965. };
  35966. /**
  35967. * Returns a height (y) value in the Worl system :
  35968. * the ground altitude at the coordinates (x, z) expressed in the World system.
  35969. * Returns the ground y position if (x, z) are outside the ground surface.
  35970. * Not pertinent if the ground is rotated.
  35971. */
  35972. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  35973. // express x and y in the ground local system
  35974. x -= this.position.x;
  35975. z -= this.position.z;
  35976. x /= this.scaling.x;
  35977. z /= this.scaling.z;
  35978. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  35979. return this.position.y;
  35980. }
  35981. if (!this._heightQuads || this._heightQuads.length == 0) {
  35982. this._initHeightQuads();
  35983. this._computeHeightQuads();
  35984. }
  35985. var facet = this._getFacetAt(x, z);
  35986. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  35987. // return y in the World system
  35988. return y * this.scaling.y + this.position.y;
  35989. };
  35990. /**
  35991. * Returns a normalized vector (Vector3) orthogonal to the ground
  35992. * at the ground coordinates (x, z) expressed in the World system.
  35993. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  35994. * Not pertinent if the ground is rotated.
  35995. */
  35996. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  35997. var normal = new BABYLON.Vector3(0, 1, 0);
  35998. this.getNormalAtCoordinatesToRef(x, z, normal);
  35999. return normal;
  36000. };
  36001. /**
  36002. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  36003. * at the ground coordinates (x, z) expressed in the World system.
  36004. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  36005. * Not pertinent if the ground is rotated.
  36006. */
  36007. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  36008. // express x and y in the ground local system
  36009. x -= this.position.x;
  36010. z -= this.position.z;
  36011. x /= this.scaling.x;
  36012. z /= this.scaling.z;
  36013. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  36014. return;
  36015. }
  36016. if (!this._heightQuads || this._heightQuads.length == 0) {
  36017. this._initHeightQuads();
  36018. this._computeHeightQuads();
  36019. }
  36020. var facet = this._getFacetAt(x, z);
  36021. ref.x = facet.x;
  36022. ref.y = facet.y;
  36023. ref.z = facet.z;
  36024. };
  36025. /**
  36026. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  36027. * if the ground has been updated.
  36028. * This can be used in the render loop
  36029. */
  36030. GroundMesh.prototype.updateCoordinateHeights = function () {
  36031. if (!this._heightQuads || this._heightQuads.length == 0) {
  36032. this._initHeightQuads();
  36033. }
  36034. this._computeHeightQuads();
  36035. };
  36036. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  36037. GroundMesh.prototype._getFacetAt = function (x, z) {
  36038. // retrieve col and row from x, z coordinates in the ground local system
  36039. var subdivisionsX = this._subdivisionsX;
  36040. var subdivisionsY = this._subdivisionsY;
  36041. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  36042. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  36043. var quad = this._heightQuads[row * this._subdivisionsX + col];
  36044. var facet;
  36045. if (z < quad.slope.x * x + quad.slope.y) {
  36046. facet = quad.facet1;
  36047. }
  36048. else {
  36049. facet = quad.facet2;
  36050. }
  36051. return facet;
  36052. };
  36053. // Creates and populates the heightMap array with "facet" elements :
  36054. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  36055. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36056. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36057. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36058. GroundMesh.prototype._initHeightQuads = function () {
  36059. var subdivisionsX = this._subdivisionsX;
  36060. var subdivisionsY = this._subdivisionsY;
  36061. this._heightQuads = new Array();
  36062. for (var row = 0; row < subdivisionsY; row++) {
  36063. for (var col = 0; col < subdivisionsX; col++) {
  36064. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  36065. this._heightQuads[row * subdivisionsX + col] = quad;
  36066. }
  36067. }
  36068. };
  36069. // Compute each quad element values and update the the heightMap array :
  36070. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  36071. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  36072. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  36073. GroundMesh.prototype._computeHeightQuads = function () {
  36074. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36075. var v1 = BABYLON.Tmp.Vector3[3];
  36076. var v2 = BABYLON.Tmp.Vector3[2];
  36077. var v3 = BABYLON.Tmp.Vector3[1];
  36078. var v4 = BABYLON.Tmp.Vector3[0];
  36079. var v1v2 = BABYLON.Tmp.Vector3[4];
  36080. var v1v3 = BABYLON.Tmp.Vector3[5];
  36081. var v1v4 = BABYLON.Tmp.Vector3[6];
  36082. var norm1 = BABYLON.Tmp.Vector3[7];
  36083. var norm2 = BABYLON.Tmp.Vector3[8];
  36084. var i = 0;
  36085. var j = 0;
  36086. var k = 0;
  36087. var cd = 0; // 2D slope coefficient : z = cd * x + h
  36088. var h = 0;
  36089. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  36090. var d2 = 0;
  36091. var subdivisionsX = this._subdivisionsX;
  36092. var subdivisionsY = this._subdivisionsY;
  36093. for (var row = 0; row < subdivisionsY; row++) {
  36094. for (var col = 0; col < subdivisionsX; col++) {
  36095. i = col * 3;
  36096. j = row * (subdivisionsX + 1) * 3;
  36097. k = (row + 1) * (subdivisionsX + 1) * 3;
  36098. v1.x = positions[j + i];
  36099. v1.y = positions[j + i + 1];
  36100. v1.z = positions[j + i + 2];
  36101. v2.x = positions[j + i + 3];
  36102. v2.y = positions[j + i + 4];
  36103. v2.z = positions[j + i + 5];
  36104. v3.x = positions[k + i];
  36105. v3.y = positions[k + i + 1];
  36106. v3.z = positions[k + i + 2];
  36107. v4.x = positions[k + i + 3];
  36108. v4.y = positions[k + i + 4];
  36109. v4.z = positions[k + i + 5];
  36110. // 2D slope V1V4
  36111. cd = (v4.z - v1.z) / (v4.x - v1.x);
  36112. h = v1.z - cd * v1.x; // v1 belongs to the slope
  36113. // facet equations :
  36114. // we compute each facet normal vector
  36115. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  36116. // we compute the value d by applying the equation to v1 which belongs to the plane
  36117. // then we store the facet equation in a Vector4
  36118. v2.subtractToRef(v1, v1v2);
  36119. v3.subtractToRef(v1, v1v3);
  36120. v4.subtractToRef(v1, v1v4);
  36121. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  36122. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  36123. norm1.normalize();
  36124. norm2.normalize();
  36125. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  36126. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  36127. var quad = this._heightQuads[row * subdivisionsX + col];
  36128. quad.slope.copyFromFloats(cd, h);
  36129. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  36130. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  36131. }
  36132. }
  36133. };
  36134. return GroundMesh;
  36135. }(BABYLON.Mesh));
  36136. BABYLON.GroundMesh = GroundMesh;
  36137. })(BABYLON || (BABYLON = {}));
  36138. var BABYLON;
  36139. (function (BABYLON) {
  36140. var LinesMesh = (function (_super) {
  36141. __extends(LinesMesh, _super);
  36142. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  36143. if (parent === void 0) { parent = null; }
  36144. _super.call(this, name, scene, parent, source, doNotCloneChildren);
  36145. this.color = new BABYLON.Color3(1, 1, 1);
  36146. this.alpha = 1;
  36147. this._positionBuffer = {};
  36148. if (source) {
  36149. this.color = source.color.clone();
  36150. this.alpha = source.alpha;
  36151. }
  36152. this._intersectionThreshold = 0.1;
  36153. this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  36154. attributes: [BABYLON.VertexBuffer.PositionKind],
  36155. uniforms: ["worldViewProjection", "color"],
  36156. needAlphaBlending: true
  36157. });
  36158. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  36159. }
  36160. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  36161. /**
  36162. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  36163. * This margin is expressed in world space coordinates, so its value may vary.
  36164. * Default value is 0.1
  36165. * @returns the intersection Threshold value.
  36166. */
  36167. get: function () {
  36168. return this._intersectionThreshold;
  36169. },
  36170. /**
  36171. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  36172. * This margin is expressed in world space coordinates, so its value may vary.
  36173. * @param value the new threshold to apply
  36174. */
  36175. set: function (value) {
  36176. if (this._intersectionThreshold === value) {
  36177. return;
  36178. }
  36179. this._intersectionThreshold = value;
  36180. if (this.geometry) {
  36181. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  36182. }
  36183. },
  36184. enumerable: true,
  36185. configurable: true
  36186. });
  36187. Object.defineProperty(LinesMesh.prototype, "material", {
  36188. get: function () {
  36189. return this._colorShader;
  36190. },
  36191. enumerable: true,
  36192. configurable: true
  36193. });
  36194. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  36195. get: function () {
  36196. return false;
  36197. },
  36198. enumerable: true,
  36199. configurable: true
  36200. });
  36201. LinesMesh.prototype.createInstance = function (name) {
  36202. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  36203. return null;
  36204. };
  36205. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  36206. var engine = this.getScene().getEngine();
  36207. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  36208. // VBOs
  36209. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  36210. // Color
  36211. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  36212. };
  36213. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  36214. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  36215. return;
  36216. }
  36217. var engine = this.getScene().getEngine();
  36218. // Draw order
  36219. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  36220. };
  36221. LinesMesh.prototype.dispose = function (doNotRecurse) {
  36222. this._colorShader.dispose();
  36223. _super.prototype.dispose.call(this, doNotRecurse);
  36224. };
  36225. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  36226. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  36227. };
  36228. return LinesMesh;
  36229. }(BABYLON.Mesh));
  36230. BABYLON.LinesMesh = LinesMesh;
  36231. })(BABYLON || (BABYLON = {}));
  36232. var BABYLON;
  36233. (function (BABYLON) {
  36234. var DefaultLoadingScreen = (function () {
  36235. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  36236. var _this = this;
  36237. if (_loadingText === void 0) { _loadingText = ""; }
  36238. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  36239. this._renderingCanvas = _renderingCanvas;
  36240. this._loadingText = _loadingText;
  36241. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  36242. // Resize
  36243. this._resizeLoadingUI = function () {
  36244. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  36245. _this._loadingDiv.style.position = "absolute";
  36246. _this._loadingDiv.style.left = canvasRect.left + "px";
  36247. _this._loadingDiv.style.top = canvasRect.top + "px";
  36248. _this._loadingDiv.style.width = canvasRect.width + "px";
  36249. _this._loadingDiv.style.height = canvasRect.height + "px";
  36250. };
  36251. }
  36252. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  36253. var _this = this;
  36254. if (this._loadingDiv) {
  36255. // Do not add a loading screen if there is already one
  36256. return;
  36257. }
  36258. this._loadingDiv = document.createElement("div");
  36259. this._loadingDiv.id = "babylonjsLoadingDiv";
  36260. this._loadingDiv.style.opacity = "0";
  36261. this._loadingDiv.style.transition = "opacity 1.5s ease";
  36262. // Loading text
  36263. this._loadingTextDiv = document.createElement("div");
  36264. this._loadingTextDiv.style.position = "absolute";
  36265. this._loadingTextDiv.style.left = "0";
  36266. this._loadingTextDiv.style.top = "50%";
  36267. this._loadingTextDiv.style.marginTop = "80px";
  36268. this._loadingTextDiv.style.width = "100%";
  36269. this._loadingTextDiv.style.height = "20px";
  36270. this._loadingTextDiv.style.fontFamily = "Arial";
  36271. this._loadingTextDiv.style.fontSize = "14px";
  36272. this._loadingTextDiv.style.color = "white";
  36273. this._loadingTextDiv.style.textAlign = "center";
  36274. this._loadingTextDiv.innerHTML = "Loading";
  36275. this._loadingDiv.appendChild(this._loadingTextDiv);
  36276. //set the predefined text
  36277. this._loadingTextDiv.innerHTML = this._loadingText;
  36278. // Loading img
  36279. var imgBack = new Image();
  36280. 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==";
  36281. imgBack.style.position = "absolute";
  36282. imgBack.style.left = "50%";
  36283. imgBack.style.top = "50%";
  36284. imgBack.style.marginLeft = "-50px";
  36285. imgBack.style.marginTop = "-50px";
  36286. imgBack.style.transition = "transform 1.0s ease";
  36287. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  36288. var deg = 360;
  36289. var onTransitionEnd = function () {
  36290. deg += 360;
  36291. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  36292. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  36293. };
  36294. imgBack.addEventListener("transitionend", onTransitionEnd);
  36295. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  36296. this._loadingDiv.appendChild(imgBack);
  36297. // front image
  36298. var imgFront = new Image();
  36299. 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=";
  36300. imgFront.style.position = "absolute";
  36301. imgFront.style.left = "50%";
  36302. imgFront.style.top = "50%";
  36303. imgFront.style.marginLeft = "-50px";
  36304. imgFront.style.marginTop = "-50px";
  36305. this._loadingDiv.appendChild(imgFront);
  36306. this._resizeLoadingUI();
  36307. window.addEventListener("resize", this._resizeLoadingUI);
  36308. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  36309. document.body.appendChild(this._loadingDiv);
  36310. setTimeout(function () {
  36311. _this._loadingDiv.style.opacity = "1";
  36312. imgBack.style.transform = "rotateZ(360deg)";
  36313. imgBack.style.webkitTransform = "rotateZ(360deg)";
  36314. }, 0);
  36315. };
  36316. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  36317. var _this = this;
  36318. if (!this._loadingDiv) {
  36319. return;
  36320. }
  36321. var onTransitionEnd = function () {
  36322. if (!_this._loadingDiv) {
  36323. return;
  36324. }
  36325. document.body.removeChild(_this._loadingDiv);
  36326. window.removeEventListener("resize", _this._resizeLoadingUI);
  36327. _this._loadingDiv = null;
  36328. };
  36329. this._loadingDiv.style.opacity = "0";
  36330. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  36331. };
  36332. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  36333. set: function (text) {
  36334. this._loadingText = text;
  36335. if (this._loadingTextDiv) {
  36336. this._loadingTextDiv.innerHTML = this._loadingText;
  36337. }
  36338. },
  36339. enumerable: true,
  36340. configurable: true
  36341. });
  36342. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  36343. get: function () {
  36344. return this._loadingDivBackgroundColor;
  36345. },
  36346. set: function (color) {
  36347. this._loadingDivBackgroundColor = color;
  36348. if (!this._loadingDiv) {
  36349. return;
  36350. }
  36351. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  36352. },
  36353. enumerable: true,
  36354. configurable: true
  36355. });
  36356. return DefaultLoadingScreen;
  36357. }());
  36358. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  36359. })(BABYLON || (BABYLON = {}));
  36360. var BABYLON;
  36361. (function (BABYLON) {
  36362. var AudioEngine = (function () {
  36363. function AudioEngine() {
  36364. this._audioContext = null;
  36365. this._audioContextInitialized = false;
  36366. this.canUseWebAudio = false;
  36367. this.WarnedWebAudioUnsupported = false;
  36368. this.unlocked = false;
  36369. this.isMP3supported = false;
  36370. this.isOGGsupported = false;
  36371. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  36372. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  36373. this.canUseWebAudio = true;
  36374. }
  36375. var audioElem = document.createElement('audio');
  36376. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  36377. this.isMP3supported = true;
  36378. }
  36379. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  36380. this.isOGGsupported = true;
  36381. }
  36382. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  36383. this._unlockiOSaudio();
  36384. }
  36385. else {
  36386. this.unlocked = true;
  36387. }
  36388. }
  36389. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  36390. get: function () {
  36391. if (!this._audioContextInitialized) {
  36392. this._initializeAudioContext();
  36393. }
  36394. return this._audioContext;
  36395. },
  36396. enumerable: true,
  36397. configurable: true
  36398. });
  36399. AudioEngine.prototype._unlockiOSaudio = function () {
  36400. var _this = this;
  36401. var unlockaudio = function () {
  36402. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  36403. var source = _this.audioContext.createBufferSource();
  36404. source.buffer = buffer;
  36405. source.connect(_this.audioContext.destination);
  36406. source.start(0);
  36407. setTimeout(function () {
  36408. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  36409. _this.unlocked = true;
  36410. window.removeEventListener('touchend', unlockaudio, false);
  36411. if (_this.onAudioUnlocked) {
  36412. _this.onAudioUnlocked();
  36413. }
  36414. }
  36415. }, 0);
  36416. };
  36417. window.addEventListener('touchend', unlockaudio, false);
  36418. };
  36419. AudioEngine.prototype._initializeAudioContext = function () {
  36420. try {
  36421. if (this.canUseWebAudio) {
  36422. this._audioContext = new AudioContext();
  36423. // create a global volume gain node
  36424. this.masterGain = this._audioContext.createGain();
  36425. this.masterGain.gain.value = 1;
  36426. this.masterGain.connect(this._audioContext.destination);
  36427. this._audioContextInitialized = true;
  36428. }
  36429. }
  36430. catch (e) {
  36431. this.canUseWebAudio = false;
  36432. BABYLON.Tools.Error("Web Audio: " + e.message);
  36433. }
  36434. };
  36435. AudioEngine.prototype.dispose = function () {
  36436. if (this.canUseWebAudio && this._audioContextInitialized) {
  36437. if (this._connectedAnalyser) {
  36438. this._connectedAnalyser.stopDebugCanvas();
  36439. this._connectedAnalyser.dispose();
  36440. this.masterGain.disconnect();
  36441. this.masterGain.connect(this._audioContext.destination);
  36442. this._connectedAnalyser = null;
  36443. }
  36444. this.masterGain.gain.value = 1;
  36445. }
  36446. this.WarnedWebAudioUnsupported = false;
  36447. };
  36448. AudioEngine.prototype.getGlobalVolume = function () {
  36449. if (this.canUseWebAudio && this._audioContextInitialized) {
  36450. return this.masterGain.gain.value;
  36451. }
  36452. else {
  36453. return -1;
  36454. }
  36455. };
  36456. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  36457. if (this.canUseWebAudio && this._audioContextInitialized) {
  36458. this.masterGain.gain.value = newVolume;
  36459. }
  36460. };
  36461. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  36462. if (this._connectedAnalyser) {
  36463. this._connectedAnalyser.stopDebugCanvas();
  36464. }
  36465. if (this.canUseWebAudio && this._audioContextInitialized) {
  36466. this._connectedAnalyser = analyser;
  36467. this.masterGain.disconnect();
  36468. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  36469. }
  36470. };
  36471. return AudioEngine;
  36472. }());
  36473. BABYLON.AudioEngine = AudioEngine;
  36474. })(BABYLON || (BABYLON = {}));
  36475. var BABYLON;
  36476. (function (BABYLON) {
  36477. var Sound = (function () {
  36478. /**
  36479. * Create a sound and attach it to a scene
  36480. * @param name Name of your sound
  36481. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  36482. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  36483. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  36484. */
  36485. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  36486. var _this = this;
  36487. this.autoplay = false;
  36488. this.loop = false;
  36489. this.useCustomAttenuation = false;
  36490. this.spatialSound = false;
  36491. this.refDistance = 1;
  36492. this.rolloffFactor = 1;
  36493. this.maxDistance = 100;
  36494. this.distanceModel = "linear";
  36495. this._panningModel = "equalpower";
  36496. this._playbackRate = 1;
  36497. this._streaming = false;
  36498. this._startTime = 0;
  36499. this._startOffset = 0;
  36500. this._position = BABYLON.Vector3.Zero();
  36501. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  36502. this._volume = 1;
  36503. this._isLoaded = false;
  36504. this._isReadyToPlay = false;
  36505. this.isPlaying = false;
  36506. this.isPaused = false;
  36507. this._isDirectional = false;
  36508. // Used if you'd like to create a directional sound.
  36509. // If not set, the sound will be omnidirectional
  36510. this._coneInnerAngle = 360;
  36511. this._coneOuterAngle = 360;
  36512. this._coneOuterGain = 0;
  36513. this._isOutputConnected = false;
  36514. this._urlType = "Unknown";
  36515. this.name = name;
  36516. this._scene = scene;
  36517. this._readyToPlayCallback = readyToPlayCallback;
  36518. // Default custom attenuation function is a linear attenuation
  36519. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  36520. if (currentDistance < maxDistance) {
  36521. return currentVolume * (1 - currentDistance / maxDistance);
  36522. }
  36523. else {
  36524. return 0;
  36525. }
  36526. };
  36527. if (options) {
  36528. this.autoplay = options.autoplay || false;
  36529. this.loop = options.loop || false;
  36530. // if volume === 0, we need another way to check this option
  36531. if (options.volume !== undefined) {
  36532. this._volume = options.volume;
  36533. }
  36534. this.spatialSound = options.spatialSound || false;
  36535. this.maxDistance = options.maxDistance || 100;
  36536. this.useCustomAttenuation = options.useCustomAttenuation || false;
  36537. this.rolloffFactor = options.rolloffFactor || 1;
  36538. this.refDistance = options.refDistance || 1;
  36539. this.distanceModel = options.distanceModel || "linear";
  36540. this._playbackRate = options.playbackRate || 1;
  36541. this._streaming = options.streaming || false;
  36542. }
  36543. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36544. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  36545. this._soundGain.gain.value = this._volume;
  36546. this._inputAudioNode = this._soundGain;
  36547. this._ouputAudioNode = this._soundGain;
  36548. if (this.spatialSound) {
  36549. this._createSpatialParameters();
  36550. }
  36551. this._scene.mainSoundTrack.AddSound(this);
  36552. var validParameter = true;
  36553. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  36554. if (urlOrArrayBuffer) {
  36555. if (typeof (urlOrArrayBuffer) === "string")
  36556. this._urlType = "String";
  36557. if (Array.isArray(urlOrArrayBuffer))
  36558. this._urlType = "Array";
  36559. if (urlOrArrayBuffer instanceof ArrayBuffer)
  36560. this._urlType = "ArrayBuffer";
  36561. var urls = [];
  36562. var codecSupportedFound = false;
  36563. switch (this._urlType) {
  36564. case "ArrayBuffer":
  36565. if (urlOrArrayBuffer.byteLength > 0) {
  36566. codecSupportedFound = true;
  36567. this._soundLoaded(urlOrArrayBuffer);
  36568. }
  36569. break;
  36570. case "String":
  36571. urls.push(urlOrArrayBuffer);
  36572. case "Array":
  36573. if (urls.length === 0)
  36574. urls = urlOrArrayBuffer;
  36575. // If we found a supported format, we load it immediately and stop the loop
  36576. for (var i = 0; i < urls.length; i++) {
  36577. var url = urls[i];
  36578. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  36579. codecSupportedFound = true;
  36580. }
  36581. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  36582. codecSupportedFound = true;
  36583. }
  36584. if (url.indexOf(".wav", url.length - 4) !== -1) {
  36585. codecSupportedFound = true;
  36586. }
  36587. if (codecSupportedFound) {
  36588. // Loading sound using XHR2
  36589. if (!this._streaming) {
  36590. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  36591. }
  36592. else {
  36593. this._htmlAudioElement = new Audio(url);
  36594. this._htmlAudioElement.controls = false;
  36595. this._htmlAudioElement.loop = this.loop;
  36596. this._htmlAudioElement.crossOrigin = "anonymous";
  36597. this._htmlAudioElement.preload = "auto";
  36598. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  36599. _this._isReadyToPlay = true;
  36600. if (_this.autoplay) {
  36601. _this.play();
  36602. }
  36603. if (_this._readyToPlayCallback) {
  36604. _this._readyToPlayCallback();
  36605. }
  36606. });
  36607. document.body.appendChild(this._htmlAudioElement);
  36608. }
  36609. break;
  36610. }
  36611. }
  36612. break;
  36613. default:
  36614. validParameter = false;
  36615. break;
  36616. }
  36617. if (!validParameter) {
  36618. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  36619. }
  36620. else {
  36621. if (!codecSupportedFound) {
  36622. this._isReadyToPlay = true;
  36623. // Simulating a ready to play event to avoid breaking code path
  36624. if (this._readyToPlayCallback) {
  36625. window.setTimeout(function () {
  36626. _this._readyToPlayCallback();
  36627. }, 1000);
  36628. }
  36629. }
  36630. }
  36631. }
  36632. }
  36633. else {
  36634. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  36635. this._scene.mainSoundTrack.AddSound(this);
  36636. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  36637. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  36638. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  36639. }
  36640. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  36641. if (this._readyToPlayCallback) {
  36642. window.setTimeout(function () {
  36643. _this._readyToPlayCallback();
  36644. }, 1000);
  36645. }
  36646. }
  36647. }
  36648. Sound.prototype.dispose = function () {
  36649. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  36650. if (this.isPlaying) {
  36651. this.stop();
  36652. }
  36653. this._isReadyToPlay = false;
  36654. if (this.soundTrackId === -1) {
  36655. this._scene.mainSoundTrack.RemoveSound(this);
  36656. }
  36657. else {
  36658. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  36659. }
  36660. if (this._soundGain) {
  36661. this._soundGain.disconnect();
  36662. this._soundGain = null;
  36663. }
  36664. if (this._soundPanner) {
  36665. this._soundPanner.disconnect();
  36666. this._soundPanner = null;
  36667. }
  36668. if (this._soundSource) {
  36669. this._soundSource.disconnect();
  36670. this._soundSource = null;
  36671. }
  36672. this._audioBuffer = null;
  36673. if (this._htmlAudioElement) {
  36674. this._htmlAudioElement.pause();
  36675. this._htmlAudioElement.src = "";
  36676. document.body.removeChild(this._htmlAudioElement);
  36677. }
  36678. if (this._connectedMesh) {
  36679. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36680. this._connectedMesh = null;
  36681. }
  36682. }
  36683. };
  36684. Sound.prototype._soundLoaded = function (audioData) {
  36685. var _this = this;
  36686. this._isLoaded = true;
  36687. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  36688. _this._audioBuffer = buffer;
  36689. _this._isReadyToPlay = true;
  36690. if (_this.autoplay) {
  36691. _this.play();
  36692. }
  36693. if (_this._readyToPlayCallback) {
  36694. _this._readyToPlayCallback();
  36695. }
  36696. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  36697. };
  36698. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  36699. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36700. this._audioBuffer = audioBuffer;
  36701. this._isReadyToPlay = true;
  36702. }
  36703. };
  36704. Sound.prototype.updateOptions = function (options) {
  36705. if (options) {
  36706. this.loop = options.loop || this.loop;
  36707. this.maxDistance = options.maxDistance || this.maxDistance;
  36708. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  36709. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  36710. this.refDistance = options.refDistance || this.refDistance;
  36711. this.distanceModel = options.distanceModel || this.distanceModel;
  36712. this._playbackRate = options.playbackRate || this._playbackRate;
  36713. this._updateSpatialParameters();
  36714. if (this.isPlaying) {
  36715. if (this._streaming) {
  36716. this._htmlAudioElement.playbackRate = this._playbackRate;
  36717. }
  36718. else {
  36719. this._soundSource.playbackRate.value = this._playbackRate;
  36720. }
  36721. }
  36722. }
  36723. };
  36724. Sound.prototype._createSpatialParameters = function () {
  36725. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36726. if (this._scene.headphone) {
  36727. this._panningModel = "HRTF";
  36728. }
  36729. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  36730. this._updateSpatialParameters();
  36731. this._soundPanner.connect(this._ouputAudioNode);
  36732. this._inputAudioNode = this._soundPanner;
  36733. }
  36734. };
  36735. Sound.prototype._updateSpatialParameters = function () {
  36736. if (this.spatialSound) {
  36737. if (this.useCustomAttenuation) {
  36738. // Tricks to disable in a way embedded Web Audio attenuation
  36739. this._soundPanner.distanceModel = "linear";
  36740. this._soundPanner.maxDistance = Number.MAX_VALUE;
  36741. this._soundPanner.refDistance = 1;
  36742. this._soundPanner.rolloffFactor = 1;
  36743. this._soundPanner.panningModel = this._panningModel;
  36744. }
  36745. else {
  36746. this._soundPanner.distanceModel = this.distanceModel;
  36747. this._soundPanner.maxDistance = this.maxDistance;
  36748. this._soundPanner.refDistance = this.refDistance;
  36749. this._soundPanner.rolloffFactor = this.rolloffFactor;
  36750. this._soundPanner.panningModel = this._panningModel;
  36751. }
  36752. }
  36753. };
  36754. Sound.prototype.switchPanningModelToHRTF = function () {
  36755. this._panningModel = "HRTF";
  36756. this._switchPanningModel();
  36757. };
  36758. Sound.prototype.switchPanningModelToEqualPower = function () {
  36759. this._panningModel = "equalpower";
  36760. this._switchPanningModel();
  36761. };
  36762. Sound.prototype._switchPanningModel = function () {
  36763. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36764. this._soundPanner.panningModel = this._panningModel;
  36765. }
  36766. };
  36767. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  36768. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36769. if (this._isOutputConnected) {
  36770. this._ouputAudioNode.disconnect();
  36771. }
  36772. this._ouputAudioNode.connect(soundTrackAudioNode);
  36773. this._isOutputConnected = true;
  36774. }
  36775. };
  36776. /**
  36777. * Transform this sound into a directional source
  36778. * @param coneInnerAngle Size of the inner cone in degree
  36779. * @param coneOuterAngle Size of the outer cone in degree
  36780. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  36781. */
  36782. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  36783. if (coneOuterAngle < coneInnerAngle) {
  36784. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  36785. return;
  36786. }
  36787. this._coneInnerAngle = coneInnerAngle;
  36788. this._coneOuterAngle = coneOuterAngle;
  36789. this._coneOuterGain = coneOuterGain;
  36790. this._isDirectional = true;
  36791. if (this.isPlaying && this.loop) {
  36792. this.stop();
  36793. this.play();
  36794. }
  36795. };
  36796. Sound.prototype.setPosition = function (newPosition) {
  36797. this._position = newPosition;
  36798. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  36799. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36800. }
  36801. };
  36802. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  36803. this._localDirection = newLocalDirection;
  36804. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  36805. this._updateDirection();
  36806. }
  36807. };
  36808. Sound.prototype._updateDirection = function () {
  36809. var mat = this._connectedMesh.getWorldMatrix();
  36810. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  36811. direction.normalize();
  36812. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  36813. };
  36814. Sound.prototype.updateDistanceFromListener = function () {
  36815. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  36816. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  36817. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  36818. }
  36819. };
  36820. Sound.prototype.setAttenuationFunction = function (callback) {
  36821. this._customAttenuationFunction = callback;
  36822. };
  36823. /**
  36824. * Play the sound
  36825. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  36826. * @param offset (optional) Start the sound setting it at a specific time
  36827. */
  36828. Sound.prototype.play = function (time, offset) {
  36829. var _this = this;
  36830. if (this._isReadyToPlay && this._scene.audioEnabled) {
  36831. try {
  36832. if (this._startOffset < 0) {
  36833. time = -this._startOffset;
  36834. this._startOffset = 0;
  36835. }
  36836. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36837. if (!this._soundSource || !this._streamingSource) {
  36838. if (this.spatialSound) {
  36839. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  36840. if (this._isDirectional) {
  36841. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  36842. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  36843. this._soundPanner.coneOuterGain = this._coneOuterGain;
  36844. if (this._connectedMesh) {
  36845. this._updateDirection();
  36846. }
  36847. else {
  36848. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  36849. }
  36850. }
  36851. }
  36852. }
  36853. if (this._streaming) {
  36854. if (!this._streamingSource) {
  36855. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  36856. this._htmlAudioElement.onended = function () { _this._onended(); };
  36857. this._htmlAudioElement.playbackRate = this._playbackRate;
  36858. }
  36859. this._streamingSource.disconnect();
  36860. this._streamingSource.connect(this._inputAudioNode);
  36861. this._htmlAudioElement.play();
  36862. }
  36863. else {
  36864. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  36865. this._soundSource.buffer = this._audioBuffer;
  36866. this._soundSource.connect(this._inputAudioNode);
  36867. this._soundSource.loop = this.loop;
  36868. this._soundSource.playbackRate.value = this._playbackRate;
  36869. this._soundSource.onended = function () { _this._onended(); };
  36870. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  36871. }
  36872. this._startTime = startTime;
  36873. this.isPlaying = true;
  36874. this.isPaused = false;
  36875. }
  36876. catch (ex) {
  36877. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  36878. }
  36879. }
  36880. };
  36881. Sound.prototype._onended = function () {
  36882. this.isPlaying = false;
  36883. if (this.onended) {
  36884. this.onended();
  36885. }
  36886. };
  36887. /**
  36888. * Stop the sound
  36889. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  36890. */
  36891. Sound.prototype.stop = function (time) {
  36892. if (this.isPlaying) {
  36893. if (this._streaming) {
  36894. this._htmlAudioElement.pause();
  36895. // Test needed for Firefox or it will generate an Invalid State Error
  36896. if (this._htmlAudioElement.currentTime > 0) {
  36897. this._htmlAudioElement.currentTime = 0;
  36898. }
  36899. }
  36900. else {
  36901. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  36902. this._soundSource.stop(stopTime);
  36903. this._soundSource.onended = null;
  36904. if (!this.isPaused) {
  36905. this._startOffset = 0;
  36906. }
  36907. }
  36908. this.isPlaying = false;
  36909. }
  36910. };
  36911. Sound.prototype.pause = function () {
  36912. if (this.isPlaying) {
  36913. this.isPaused = true;
  36914. if (this._streaming) {
  36915. this._htmlAudioElement.pause();
  36916. }
  36917. else {
  36918. this.stop(0);
  36919. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  36920. }
  36921. }
  36922. };
  36923. Sound.prototype.setVolume = function (newVolume, time) {
  36924. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  36925. if (time) {
  36926. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  36927. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  36928. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  36929. }
  36930. else {
  36931. this._soundGain.gain.value = newVolume;
  36932. }
  36933. }
  36934. this._volume = newVolume;
  36935. };
  36936. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  36937. this._playbackRate = newPlaybackRate;
  36938. if (this.isPlaying) {
  36939. if (this._streaming) {
  36940. this._htmlAudioElement.playbackRate = this._playbackRate;
  36941. }
  36942. else {
  36943. this._soundSource.playbackRate.value = this._playbackRate;
  36944. }
  36945. }
  36946. };
  36947. Sound.prototype.getVolume = function () {
  36948. return this._volume;
  36949. };
  36950. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  36951. var _this = this;
  36952. if (this._connectedMesh) {
  36953. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36954. this._registerFunc = null;
  36955. }
  36956. this._connectedMesh = meshToConnectTo;
  36957. if (!this.spatialSound) {
  36958. this.spatialSound = true;
  36959. this._createSpatialParameters();
  36960. if (this.isPlaying && this.loop) {
  36961. this.stop();
  36962. this.play();
  36963. }
  36964. }
  36965. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  36966. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  36967. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  36968. };
  36969. Sound.prototype.detachFromMesh = function () {
  36970. if (this._connectedMesh) {
  36971. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  36972. this._registerFunc = null;
  36973. this._connectedMesh = null;
  36974. }
  36975. };
  36976. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  36977. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  36978. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  36979. this._updateDirection();
  36980. }
  36981. };
  36982. Sound.prototype.clone = function () {
  36983. var _this = this;
  36984. if (!this._streaming) {
  36985. var setBufferAndRun = function () {
  36986. if (_this._isReadyToPlay) {
  36987. clonedSound._audioBuffer = _this.getAudioBuffer();
  36988. clonedSound._isReadyToPlay = true;
  36989. if (clonedSound.autoplay) {
  36990. clonedSound.play();
  36991. }
  36992. }
  36993. else {
  36994. window.setTimeout(setBufferAndRun, 300);
  36995. }
  36996. };
  36997. var currentOptions = {
  36998. autoplay: this.autoplay, loop: this.loop,
  36999. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  37000. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  37001. refDistance: this.refDistance, distanceModel: this.distanceModel
  37002. };
  37003. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  37004. if (this.useCustomAttenuation) {
  37005. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  37006. }
  37007. clonedSound.setPosition(this._position);
  37008. clonedSound.setPlaybackRate(this._playbackRate);
  37009. setBufferAndRun();
  37010. return clonedSound;
  37011. }
  37012. else {
  37013. return null;
  37014. }
  37015. };
  37016. Sound.prototype.getAudioBuffer = function () {
  37017. return this._audioBuffer;
  37018. };
  37019. Sound.prototype.serialize = function () {
  37020. var serializationObject = {
  37021. name: this.name,
  37022. url: this.name,
  37023. autoplay: this.autoplay,
  37024. loop: this.loop,
  37025. volume: this._volume,
  37026. spatialSound: this.spatialSound,
  37027. maxDistance: this.maxDistance,
  37028. rolloffFactor: this.rolloffFactor,
  37029. refDistance: this.refDistance,
  37030. distanceModel: this.distanceModel,
  37031. playbackRate: this._playbackRate,
  37032. panningModel: this._panningModel,
  37033. soundTrackId: this.soundTrackId
  37034. };
  37035. if (this.spatialSound) {
  37036. if (this._connectedMesh)
  37037. serializationObject.connectedMeshId = this._connectedMesh.id;
  37038. serializationObject.position = this._position.asArray();
  37039. serializationObject.refDistance = this.refDistance;
  37040. serializationObject.distanceModel = this.distanceModel;
  37041. serializationObject.isDirectional = this._isDirectional;
  37042. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  37043. serializationObject.coneInnerAngle = this._coneInnerAngle;
  37044. serializationObject.coneOuterAngle = this._coneOuterAngle;
  37045. serializationObject.coneOuterGain = this._coneOuterGain;
  37046. }
  37047. return serializationObject;
  37048. };
  37049. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  37050. var soundName = parsedSound.name;
  37051. var soundUrl;
  37052. if (parsedSound.url) {
  37053. soundUrl = rootUrl + parsedSound.url;
  37054. }
  37055. else {
  37056. soundUrl = rootUrl + soundName;
  37057. }
  37058. var options = {
  37059. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  37060. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  37061. rolloffFactor: parsedSound.rolloffFactor,
  37062. refDistance: parsedSound.refDistance,
  37063. distanceModel: parsedSound.distanceModel,
  37064. playbackRate: parsedSound.playbackRate
  37065. };
  37066. var newSound;
  37067. if (!sourceSound) {
  37068. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  37069. scene._addPendingData(newSound);
  37070. }
  37071. else {
  37072. var setBufferAndRun = function () {
  37073. if (sourceSound._isReadyToPlay) {
  37074. newSound._audioBuffer = sourceSound.getAudioBuffer();
  37075. newSound._isReadyToPlay = true;
  37076. if (newSound.autoplay) {
  37077. newSound.play();
  37078. }
  37079. }
  37080. else {
  37081. window.setTimeout(setBufferAndRun, 300);
  37082. }
  37083. };
  37084. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  37085. setBufferAndRun();
  37086. }
  37087. if (parsedSound.position) {
  37088. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  37089. newSound.setPosition(soundPosition);
  37090. }
  37091. if (parsedSound.isDirectional) {
  37092. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  37093. if (parsedSound.localDirectionToMesh) {
  37094. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  37095. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  37096. }
  37097. }
  37098. if (parsedSound.connectedMeshId) {
  37099. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  37100. if (connectedMesh) {
  37101. newSound.attachToMesh(connectedMesh);
  37102. }
  37103. }
  37104. return newSound;
  37105. };
  37106. return Sound;
  37107. }());
  37108. BABYLON.Sound = Sound;
  37109. })(BABYLON || (BABYLON = {}));
  37110. var BABYLON;
  37111. (function (BABYLON) {
  37112. var SoundTrack = (function () {
  37113. function SoundTrack(scene, options) {
  37114. this.id = -1;
  37115. this._isMainTrack = false;
  37116. this._isInitialized = false;
  37117. this._scene = scene;
  37118. this.soundCollection = new Array();
  37119. this._options = options;
  37120. if (!this._isMainTrack) {
  37121. this._scene.soundTracks.push(this);
  37122. this.id = this._scene.soundTracks.length - 1;
  37123. }
  37124. }
  37125. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  37126. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37127. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  37128. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  37129. if (this._options) {
  37130. if (this._options.volume) {
  37131. this._outputAudioNode.gain.value = this._options.volume;
  37132. }
  37133. if (this._options.mainTrack) {
  37134. this._isMainTrack = this._options.mainTrack;
  37135. }
  37136. }
  37137. this._isInitialized = true;
  37138. }
  37139. };
  37140. SoundTrack.prototype.dispose = function () {
  37141. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37142. if (this._connectedAnalyser) {
  37143. this._connectedAnalyser.stopDebugCanvas();
  37144. }
  37145. while (this.soundCollection.length) {
  37146. this.soundCollection[0].dispose();
  37147. }
  37148. if (this._outputAudioNode) {
  37149. this._outputAudioNode.disconnect();
  37150. }
  37151. this._outputAudioNode = null;
  37152. }
  37153. };
  37154. SoundTrack.prototype.AddSound = function (sound) {
  37155. if (!this._isInitialized) {
  37156. this._initializeSoundTrackAudioGraph();
  37157. }
  37158. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37159. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  37160. }
  37161. if (sound.soundTrackId) {
  37162. if (sound.soundTrackId === -1) {
  37163. this._scene.mainSoundTrack.RemoveSound(sound);
  37164. }
  37165. else {
  37166. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  37167. }
  37168. }
  37169. this.soundCollection.push(sound);
  37170. sound.soundTrackId = this.id;
  37171. };
  37172. SoundTrack.prototype.RemoveSound = function (sound) {
  37173. var index = this.soundCollection.indexOf(sound);
  37174. if (index !== -1) {
  37175. this.soundCollection.splice(index, 1);
  37176. }
  37177. };
  37178. SoundTrack.prototype.setVolume = function (newVolume) {
  37179. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37180. this._outputAudioNode.gain.value = newVolume;
  37181. }
  37182. };
  37183. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  37184. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37185. for (var i = 0; i < this.soundCollection.length; i++) {
  37186. this.soundCollection[i].switchPanningModelToHRTF();
  37187. }
  37188. }
  37189. };
  37190. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  37191. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37192. for (var i = 0; i < this.soundCollection.length; i++) {
  37193. this.soundCollection[i].switchPanningModelToEqualPower();
  37194. }
  37195. }
  37196. };
  37197. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  37198. if (this._connectedAnalyser) {
  37199. this._connectedAnalyser.stopDebugCanvas();
  37200. }
  37201. this._connectedAnalyser = analyser;
  37202. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37203. this._outputAudioNode.disconnect();
  37204. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  37205. }
  37206. };
  37207. return SoundTrack;
  37208. }());
  37209. BABYLON.SoundTrack = SoundTrack;
  37210. })(BABYLON || (BABYLON = {}));
  37211. var BABYLON;
  37212. (function (BABYLON) {
  37213. /**
  37214. * Special Glow Blur post process only blurring the alpha channel
  37215. * It enforces keeping the most luminous color in the color channel.
  37216. */
  37217. var GlowBlurPostProcess = (function (_super) {
  37218. __extends(GlowBlurPostProcess, _super);
  37219. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  37220. var _this = this;
  37221. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  37222. _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  37223. this.direction = direction;
  37224. this.blurWidth = blurWidth;
  37225. this.onApplyObservable.add(function (effect) {
  37226. effect.setFloat2("screenSize", _this.width, _this.height);
  37227. effect.setVector2("direction", _this.direction);
  37228. effect.setFloat("blurWidth", _this.blurWidth);
  37229. });
  37230. }
  37231. return GlowBlurPostProcess;
  37232. }(BABYLON.PostProcess));
  37233. /**
  37234. * The highlight layer Helps adding a glow effect around a mesh.
  37235. *
  37236. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  37237. * glowy meshes to your scene.
  37238. *
  37239. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  37240. */
  37241. var HighlightLayer = (function () {
  37242. /**
  37243. * Instantiates a new highlight Layer and references it to the scene..
  37244. * @param name The name of the layer
  37245. * @param scene The scene to use the layer in
  37246. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  37247. */
  37248. function HighlightLayer(name, scene, options) {
  37249. this._vertexBuffers = {};
  37250. this._mainTextureDesiredSize = { width: 0, height: 0 };
  37251. this._meshes = {};
  37252. this._maxSize = 0;
  37253. this._shouldRender = false;
  37254. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  37255. this._excludedMeshes = {};
  37256. /**
  37257. * Specifies whether or not the inner glow is ACTIVE in the layer.
  37258. */
  37259. this.innerGlow = true;
  37260. /**
  37261. * Specifies whether or not the outer glow is ACTIVE in the layer.
  37262. */
  37263. this.outerGlow = true;
  37264. /**
  37265. * An event triggered when the highlight layer has been disposed.
  37266. * @type {BABYLON.Observable}
  37267. */
  37268. this.onDisposeObservable = new BABYLON.Observable();
  37269. /**
  37270. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  37271. * @type {BABYLON.Observable}
  37272. */
  37273. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  37274. /**
  37275. * An event triggered when the highlight layer is being blurred.
  37276. * @type {BABYLON.Observable}
  37277. */
  37278. this.onBeforeBlurObservable = new BABYLON.Observable();
  37279. /**
  37280. * An event triggered when the highlight layer has been blurred.
  37281. * @type {BABYLON.Observable}
  37282. */
  37283. this.onAfterBlurObservable = new BABYLON.Observable();
  37284. /**
  37285. * An event triggered when the glowing blurred texture is being merged in the scene.
  37286. * @type {BABYLON.Observable}
  37287. */
  37288. this.onBeforeComposeObservable = new BABYLON.Observable();
  37289. /**
  37290. * An event triggered when the glowing blurred texture has been merged in the scene.
  37291. * @type {BABYLON.Observable}
  37292. */
  37293. this.onAfterComposeObservable = new BABYLON.Observable();
  37294. /**
  37295. * An event triggered when the highlight layer changes its size.
  37296. * @type {BABYLON.Observable}
  37297. */
  37298. this.onSizeChangedObservable = new BABYLON.Observable();
  37299. this._scene = scene;
  37300. var engine = scene.getEngine();
  37301. this._engine = engine;
  37302. this._maxSize = this._engine.getCaps().maxTextureSize;
  37303. this._scene.highlightLayers.push(this);
  37304. // Warn on stencil.
  37305. if (!this._engine.isStencilEnable) {
  37306. 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 }");
  37307. }
  37308. // Adapt options
  37309. this._options = options || {
  37310. mainTextureRatio: 0.25,
  37311. blurTextureSizeRatio: 0.5,
  37312. blurHorizontalSize: 1,
  37313. blurVerticalSize: 1,
  37314. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  37315. };
  37316. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  37317. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  37318. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  37319. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  37320. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  37321. // VBO
  37322. var vertices = [];
  37323. vertices.push(1, 1);
  37324. vertices.push(-1, 1);
  37325. vertices.push(-1, -1);
  37326. vertices.push(1, -1);
  37327. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  37328. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  37329. // Indices
  37330. var indices = [];
  37331. indices.push(0);
  37332. indices.push(1);
  37333. indices.push(2);
  37334. indices.push(0);
  37335. indices.push(2);
  37336. indices.push(3);
  37337. this._indexBuffer = engine.createIndexBuffer(indices);
  37338. // Effect
  37339. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  37340. // Render target
  37341. this.setMainTextureSize();
  37342. // Create Textures and post processes
  37343. this.createTextureAndPostProcesses();
  37344. }
  37345. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  37346. /**
  37347. * Gets the horizontal size of the blur.
  37348. */
  37349. get: function () {
  37350. return this._horizontalBlurPostprocess.blurWidth;
  37351. },
  37352. /**
  37353. * Specifies the horizontal size of the blur.
  37354. */
  37355. set: function (value) {
  37356. this._horizontalBlurPostprocess.blurWidth = value;
  37357. },
  37358. enumerable: true,
  37359. configurable: true
  37360. });
  37361. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  37362. /**
  37363. * Gets the vertical size of the blur.
  37364. */
  37365. get: function () {
  37366. return this._verticalBlurPostprocess.blurWidth;
  37367. },
  37368. /**
  37369. * Specifies the vertical size of the blur.
  37370. */
  37371. set: function (value) {
  37372. this._verticalBlurPostprocess.blurWidth = value;
  37373. },
  37374. enumerable: true,
  37375. configurable: true
  37376. });
  37377. Object.defineProperty(HighlightLayer.prototype, "camera", {
  37378. /**
  37379. * Gets the camera attached to the layer.
  37380. */
  37381. get: function () {
  37382. return this._options.camera;
  37383. },
  37384. enumerable: true,
  37385. configurable: true
  37386. });
  37387. /**
  37388. * Creates the render target textures and post processes used in the highlight layer.
  37389. */
  37390. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  37391. var _this = this;
  37392. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  37393. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  37394. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  37395. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  37396. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  37397. width: this._mainTextureDesiredSize.width,
  37398. height: this._mainTextureDesiredSize.height
  37399. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  37400. this._mainTexture.activeCamera = this._options.camera;
  37401. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37402. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37403. this._mainTexture.anisotropicFilteringLevel = 1;
  37404. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  37405. this._mainTexture.renderParticles = false;
  37406. this._mainTexture.renderList = null;
  37407. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  37408. width: blurTextureWidth,
  37409. height: blurTextureHeight
  37410. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  37411. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37412. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  37413. this._blurTexture.anisotropicFilteringLevel = 16;
  37414. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  37415. this._blurTexture.renderParticles = false;
  37416. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  37417. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  37418. effect.setTexture("textureSampler", _this._mainTexture);
  37419. });
  37420. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  37421. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  37422. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  37423. });
  37424. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  37425. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  37426. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  37427. });
  37428. this._mainTexture.onAfterUnbindObservable.add(function () {
  37429. _this.onBeforeBlurObservable.notifyObservers(_this);
  37430. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  37431. _this.onAfterBlurObservable.notifyObservers(_this);
  37432. });
  37433. // Custom render function
  37434. var renderSubMesh = function (subMesh) {
  37435. var mesh = subMesh.getRenderingMesh();
  37436. var scene = _this._scene;
  37437. var engine = scene.getEngine();
  37438. // Culling
  37439. engine.setState(subMesh.getMaterial().backFaceCulling);
  37440. // Managing instances
  37441. var batch = mesh._getInstancesRenderList(subMesh._id);
  37442. if (batch.mustReturn) {
  37443. return;
  37444. }
  37445. // Excluded Mesh
  37446. if (_this._excludedMeshes[mesh.id]) {
  37447. return;
  37448. }
  37449. ;
  37450. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  37451. var highlightLayerMesh = _this._meshes[mesh.id];
  37452. var material = subMesh.getMaterial();
  37453. var emissiveTexture = null;
  37454. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  37455. emissiveTexture = material.emissiveTexture;
  37456. }
  37457. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  37458. engine.enableEffect(_this._glowMapGenerationEffect);
  37459. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  37460. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  37461. if (highlightLayerMesh) {
  37462. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  37463. }
  37464. else {
  37465. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  37466. }
  37467. // Alpha test
  37468. if (material && material.needAlphaTesting()) {
  37469. var alphaTexture = material.getAlphaTestTexture();
  37470. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  37471. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  37472. }
  37473. // Glow emissive only
  37474. if (emissiveTexture) {
  37475. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  37476. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  37477. }
  37478. // Bones
  37479. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37480. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  37481. }
  37482. // Draw
  37483. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  37484. }
  37485. else {
  37486. // Need to reset refresh rate of the shadowMap
  37487. _this._mainTexture.resetRefreshCounter();
  37488. }
  37489. };
  37490. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  37491. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  37492. var index;
  37493. for (index = 0; index < opaqueSubMeshes.length; index++) {
  37494. renderSubMesh(opaqueSubMeshes.data[index]);
  37495. }
  37496. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  37497. renderSubMesh(alphaTestSubMeshes.data[index]);
  37498. }
  37499. for (index = 0; index < transparentSubMeshes.length; index++) {
  37500. renderSubMesh(transparentSubMeshes.data[index]);
  37501. }
  37502. };
  37503. this._mainTexture.onClearObservable.add(function (engine) {
  37504. engine.clear(HighlightLayer.neutralColor, true, true, true);
  37505. });
  37506. };
  37507. /**
  37508. * Checks for the readiness of the element composing the layer.
  37509. * @param subMesh the mesh to check for
  37510. * @param useInstances specify wether or not to use instances to render the mesh
  37511. * @param emissiveTexture the associated emissive texture used to generate the glow
  37512. * @return true if ready otherwise, false
  37513. */
  37514. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  37515. if (!subMesh.getMaterial().isReady()) {
  37516. return false;
  37517. }
  37518. var defines = [];
  37519. var attribs = [BABYLON.VertexBuffer.PositionKind];
  37520. var mesh = subMesh.getMesh();
  37521. var material = subMesh.getMaterial();
  37522. var uv1 = false;
  37523. var uv2 = false;
  37524. // Alpha test
  37525. if (material && material.needAlphaTesting()) {
  37526. var alphaTexture = material.getAlphaTestTexture();
  37527. if (alphaTexture) {
  37528. defines.push("#define ALPHATEST");
  37529. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37530. alphaTexture.coordinatesIndex === 1) {
  37531. defines.push("#define DIFFUSEUV2");
  37532. uv2 = true;
  37533. }
  37534. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37535. defines.push("#define DIFFUSEUV1");
  37536. uv1 = true;
  37537. }
  37538. }
  37539. }
  37540. // Emissive
  37541. if (emissiveTexture) {
  37542. defines.push("#define EMISSIVE");
  37543. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  37544. emissiveTexture.coordinatesIndex === 1) {
  37545. defines.push("#define EMISSIVEUV2");
  37546. uv2 = true;
  37547. }
  37548. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37549. defines.push("#define EMISSIVEUV1");
  37550. uv1 = true;
  37551. }
  37552. }
  37553. if (uv1) {
  37554. attribs.push(BABYLON.VertexBuffer.UVKind);
  37555. defines.push("#define UV1");
  37556. }
  37557. if (uv2) {
  37558. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  37559. defines.push("#define UV2");
  37560. }
  37561. // Bones
  37562. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  37563. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  37564. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  37565. if (mesh.numBoneInfluencers > 4) {
  37566. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  37567. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  37568. }
  37569. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  37570. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  37571. }
  37572. else {
  37573. defines.push("#define NUM_BONE_INFLUENCERS 0");
  37574. }
  37575. // Instances
  37576. if (useInstances) {
  37577. defines.push("#define INSTANCES");
  37578. attribs.push("world0");
  37579. attribs.push("world1");
  37580. attribs.push("world2");
  37581. attribs.push("world3");
  37582. }
  37583. // Get correct effect
  37584. var join = defines.join("\n");
  37585. if (this._cachedDefines !== join) {
  37586. this._cachedDefines = join;
  37587. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  37588. }
  37589. return this._glowMapGenerationEffect.isReady();
  37590. };
  37591. /**
  37592. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  37593. */
  37594. HighlightLayer.prototype.render = function () {
  37595. var currentEffect = this._glowMapMergeEffect;
  37596. // Check
  37597. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  37598. return;
  37599. var engine = this._scene.getEngine();
  37600. this.onBeforeComposeObservable.notifyObservers(this);
  37601. // Render
  37602. engine.enableEffect(currentEffect);
  37603. engine.setState(false);
  37604. // Cache
  37605. var previousStencilBuffer = engine.getStencilBuffer();
  37606. var previousStencilFunction = engine.getStencilFunction();
  37607. var previousStencilMask = engine.getStencilMask();
  37608. var previousAlphaMode = engine.getAlphaMode();
  37609. // Texture
  37610. currentEffect.setTexture("textureSampler", this._blurTexture);
  37611. // VBOs
  37612. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  37613. // Draw order
  37614. engine.setAlphaMode(this._options.alphaBlendingMode);
  37615. engine.setStencilMask(0x00);
  37616. engine.setStencilBuffer(true);
  37617. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  37618. if (this.outerGlow) {
  37619. currentEffect.setFloat("offset", 0);
  37620. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  37621. engine.draw(true, 0, 6);
  37622. }
  37623. if (this.innerGlow) {
  37624. currentEffect.setFloat("offset", 1);
  37625. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  37626. engine.draw(true, 0, 6);
  37627. }
  37628. // Restore Cache
  37629. engine.setStencilFunction(previousStencilFunction);
  37630. engine.setStencilMask(previousStencilMask);
  37631. engine.setAlphaMode(previousAlphaMode);
  37632. engine.setStencilBuffer(previousStencilBuffer);
  37633. this.onAfterComposeObservable.notifyObservers(this);
  37634. // Handle size changes.
  37635. var size = this._mainTexture.getSize();
  37636. this.setMainTextureSize();
  37637. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  37638. // Recreate RTT and post processes on size change.
  37639. this.onSizeChangedObservable.notifyObservers(this);
  37640. this.disposeTextureAndPostProcesses();
  37641. this.createTextureAndPostProcesses();
  37642. }
  37643. };
  37644. /**
  37645. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  37646. * @param mesh The mesh to exclude from the highlight layer
  37647. */
  37648. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  37649. var meshExcluded = this._excludedMeshes[mesh.id];
  37650. if (!meshExcluded) {
  37651. this._excludedMeshes[mesh.id] = {
  37652. mesh: mesh,
  37653. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  37654. mesh.getEngine().setStencilBuffer(false);
  37655. }),
  37656. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  37657. mesh.getEngine().setStencilBuffer(true);
  37658. }),
  37659. };
  37660. }
  37661. };
  37662. /**
  37663. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  37664. * @param mesh The mesh to highlight
  37665. */
  37666. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  37667. var meshExcluded = this._excludedMeshes[mesh.id];
  37668. if (meshExcluded) {
  37669. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  37670. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  37671. }
  37672. this._excludedMeshes[mesh.id] = undefined;
  37673. };
  37674. /**
  37675. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  37676. * @param mesh The mesh to highlight
  37677. * @param color The color of the highlight
  37678. * @param glowEmissiveOnly Extract the glow from the emissive texture
  37679. */
  37680. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  37681. var _this = this;
  37682. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  37683. var meshHighlight = this._meshes[mesh.id];
  37684. if (meshHighlight) {
  37685. meshHighlight.color = color;
  37686. }
  37687. else {
  37688. this._meshes[mesh.id] = {
  37689. mesh: mesh,
  37690. color: color,
  37691. // Lambda required for capture due to Observable this context
  37692. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  37693. if (_this._excludedMeshes[mesh.id]) {
  37694. _this.defaultStencilReference(mesh);
  37695. }
  37696. else {
  37697. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  37698. }
  37699. }),
  37700. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  37701. glowEmissiveOnly: glowEmissiveOnly
  37702. };
  37703. }
  37704. this._shouldRender = true;
  37705. };
  37706. /**
  37707. * Remove a mesh from the highlight layer in order to make it stop glowing.
  37708. * @param mesh The mesh to highlight
  37709. */
  37710. HighlightLayer.prototype.removeMesh = function (mesh) {
  37711. var meshHighlight = this._meshes[mesh.id];
  37712. if (meshHighlight) {
  37713. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37714. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37715. }
  37716. this._meshes[mesh.id] = undefined;
  37717. this._shouldRender = false;
  37718. for (var meshHighlightToCheck in this._meshes) {
  37719. if (meshHighlightToCheck) {
  37720. this._shouldRender = true;
  37721. break;
  37722. }
  37723. }
  37724. };
  37725. /**
  37726. * Returns true if the layer contains information to display, otherwise false.
  37727. */
  37728. HighlightLayer.prototype.shouldRender = function () {
  37729. return this._shouldRender;
  37730. };
  37731. /**
  37732. * Sets the main texture desired size which is the closest power of two
  37733. * of the engine canvas size.
  37734. */
  37735. HighlightLayer.prototype.setMainTextureSize = function () {
  37736. if (this._options.mainTextureFixedSize) {
  37737. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  37738. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  37739. }
  37740. else {
  37741. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  37742. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  37743. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  37744. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  37745. }
  37746. };
  37747. /**
  37748. * Force the stencil to the normal expected value for none glowing parts
  37749. */
  37750. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  37751. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  37752. };
  37753. /**
  37754. * Dispose only the render target textures and post process.
  37755. */
  37756. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  37757. this._blurTexture.dispose();
  37758. this._mainTexture.dispose();
  37759. this._downSamplePostprocess.dispose();
  37760. this._horizontalBlurPostprocess.dispose();
  37761. this._verticalBlurPostprocess.dispose();
  37762. };
  37763. /**
  37764. * Dispose the highlight layer and free resources.
  37765. */
  37766. HighlightLayer.prototype.dispose = function () {
  37767. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  37768. if (vertexBuffer) {
  37769. vertexBuffer.dispose();
  37770. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  37771. }
  37772. if (this._indexBuffer) {
  37773. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  37774. this._indexBuffer = null;
  37775. }
  37776. // Clean textures and post processes
  37777. this.disposeTextureAndPostProcesses();
  37778. // Clean mesh references
  37779. for (var id in this._meshes) {
  37780. var meshHighlight = this._meshes[id];
  37781. if (meshHighlight && meshHighlight.mesh) {
  37782. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  37783. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  37784. }
  37785. }
  37786. this._meshes = null;
  37787. for (var id in this._excludedMeshes) {
  37788. var meshHighlight = this._excludedMeshes[id];
  37789. if (meshHighlight) {
  37790. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  37791. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  37792. }
  37793. }
  37794. this._excludedMeshes = null;
  37795. // Remove from scene
  37796. var index = this._scene.highlightLayers.indexOf(this, 0);
  37797. if (index > -1) {
  37798. this._scene.highlightLayers.splice(index, 1);
  37799. }
  37800. // Callback
  37801. this.onDisposeObservable.notifyObservers(this);
  37802. this.onDisposeObservable.clear();
  37803. this.onBeforeRenderMainTextureObservable.clear();
  37804. this.onBeforeBlurObservable.clear();
  37805. this.onBeforeComposeObservable.clear();
  37806. this.onAfterComposeObservable.clear();
  37807. this.onSizeChangedObservable.clear();
  37808. };
  37809. /**
  37810. * The neutral color used during the preparation of the glow effect.
  37811. * This is black by default as the blend operation is a blend operation.
  37812. */
  37813. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  37814. /**
  37815. * Stencil value used for glowing meshes.
  37816. */
  37817. HighlightLayer.glowingMeshStencilReference = 0x02;
  37818. /**
  37819. * Stencil value used for the other meshes in the scene.
  37820. */
  37821. HighlightLayer.normalMeshStencilReference = 0x01;
  37822. return HighlightLayer;
  37823. }());
  37824. BABYLON.HighlightLayer = HighlightLayer;
  37825. })(BABYLON || (BABYLON = {}));
  37826. var BABYLON;
  37827. (function (BABYLON) {
  37828. var SIMDVector3 = (function () {
  37829. function SIMDVector3() {
  37830. }
  37831. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  37832. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  37833. };
  37834. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  37835. var m = transformation.m;
  37836. var m0 = SIMD.Float32x4.load(m, 0);
  37837. var m1 = SIMD.Float32x4.load(m, 4);
  37838. var m2 = SIMD.Float32x4.load(m, 8);
  37839. var m3 = SIMD.Float32x4.load(m, 12);
  37840. 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));
  37841. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  37842. result.x = SIMD.Float32x4.extractLane(r, 0);
  37843. result.y = SIMD.Float32x4.extractLane(r, 1);
  37844. result.z = SIMD.Float32x4.extractLane(r, 2);
  37845. };
  37846. return SIMDVector3;
  37847. }());
  37848. var SIMDMatrix = (function () {
  37849. function SIMDMatrix() {
  37850. }
  37851. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  37852. var tm = this.m;
  37853. var om = other.m;
  37854. var m0 = SIMD.Float32x4.load(om, 0);
  37855. var m1 = SIMD.Float32x4.load(om, 4);
  37856. var m2 = SIMD.Float32x4.load(om, 8);
  37857. var m3 = SIMD.Float32x4.load(om, 12);
  37858. for (var i = 0; i < 16; i += 4) {
  37859. 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)))));
  37860. }
  37861. return this;
  37862. };
  37863. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  37864. var src = this.m;
  37865. var dest = other.m;
  37866. // Load the 4 rows
  37867. var src0 = SIMD.Float32x4.load(src, 0);
  37868. var src1 = SIMD.Float32x4.load(src, 4);
  37869. var src2 = SIMD.Float32x4.load(src, 8);
  37870. var src3 = SIMD.Float32x4.load(src, 12);
  37871. // Transpose the source matrix. Sort of. Not a true transpose operation
  37872. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  37873. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  37874. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  37875. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  37876. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  37877. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  37878. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  37879. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  37880. // This is a true transposition, but it will lead to an incorrect result
  37881. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  37882. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  37883. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37884. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37885. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  37886. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  37887. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  37888. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  37889. // ----
  37890. tmp1 = SIMD.Float32x4.mul(row2, row3);
  37891. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37892. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  37893. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  37894. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37895. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  37896. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  37897. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  37898. // ----
  37899. tmp1 = SIMD.Float32x4.mul(row1, row2);
  37900. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37901. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  37902. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  37903. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37904. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  37905. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  37906. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  37907. // ----
  37908. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  37909. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37910. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  37911. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  37912. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  37913. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37914. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  37915. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  37916. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  37917. // ----
  37918. tmp1 = SIMD.Float32x4.mul(row0, row1);
  37919. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37920. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37921. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  37922. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37923. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  37924. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  37925. // ----
  37926. tmp1 = SIMD.Float32x4.mul(row0, row3);
  37927. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37928. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  37929. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  37930. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37931. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  37932. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  37933. // ----
  37934. tmp1 = SIMD.Float32x4.mul(row0, row2);
  37935. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  37936. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  37937. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  37938. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  37939. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  37940. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  37941. // Compute determinant
  37942. var det = SIMD.Float32x4.mul(row0, minor0);
  37943. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  37944. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  37945. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  37946. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  37947. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  37948. // These shuffles aren't necessary if the faulty transposition is done
  37949. // up at the top of this function.
  37950. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  37951. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  37952. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  37953. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  37954. // Compute final values by multiplying with 1/det
  37955. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  37956. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  37957. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  37958. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  37959. return this;
  37960. };
  37961. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  37962. var out = result.m;
  37963. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  37964. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  37965. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  37966. // cc.kmVec3Subtract(f, pCenter, pEye);
  37967. var f = SIMD.Float32x4.sub(center, eye);
  37968. // cc.kmVec3Normalize(f, f);
  37969. var tmp = SIMD.Float32x4.mul(f, f);
  37970. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37971. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37972. // cc.kmVec3Assign(up, pUp);
  37973. // cc.kmVec3Normalize(up, up);
  37974. tmp = SIMD.Float32x4.mul(up, up);
  37975. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37976. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37977. // cc.kmVec3Cross(s, f, up);
  37978. 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)));
  37979. // cc.kmVec3Normalize(s, s);
  37980. tmp = SIMD.Float32x4.mul(s, s);
  37981. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37982. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37983. // cc.kmVec3Cross(u, s, f);
  37984. 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)));
  37985. // cc.kmVec3Normalize(s, s);
  37986. tmp = SIMD.Float32x4.mul(s, s);
  37987. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  37988. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  37989. var zero = SIMD.Float32x4.splat(0.0);
  37990. s = SIMD.Float32x4.neg(s);
  37991. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  37992. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  37993. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  37994. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  37995. 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);
  37996. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  37997. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  37998. 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)))));
  37999. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  38000. 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)))));
  38001. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  38002. 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)))));
  38003. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  38004. 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)))));
  38005. };
  38006. return SIMDMatrix;
  38007. }());
  38008. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  38009. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  38010. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  38011. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  38012. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  38013. var SIMDHelper = (function () {
  38014. function SIMDHelper() {
  38015. }
  38016. Object.defineProperty(SIMDHelper, "IsEnabled", {
  38017. get: function () {
  38018. return SIMDHelper._isEnabled;
  38019. },
  38020. enumerable: true,
  38021. configurable: true
  38022. });
  38023. SIMDHelper.DisableSIMD = function () {
  38024. // Replace functions
  38025. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  38026. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  38027. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  38028. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  38029. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  38030. SIMDHelper._isEnabled = false;
  38031. };
  38032. SIMDHelper.EnableSIMD = function () {
  38033. if (self.SIMD === undefined) {
  38034. return;
  38035. }
  38036. // check if polyfills needed
  38037. if (!self.Math.fround) {
  38038. self.Math.fround = (function (array) { return function (x) {
  38039. return array[0] = x, array[0];
  38040. }; })(new Float32Array(1));
  38041. }
  38042. if (!self.Math.imul) {
  38043. self.Math.imul = function (a, b) {
  38044. var ah = (a >>> 16) & 0xffff;
  38045. var al = a & 0xffff;
  38046. var bh = (b >>> 16) & 0xffff;
  38047. var bl = b & 0xffff;
  38048. // the shift by 0 fixes the sign on the high part
  38049. // the final |0 converts the unsigned value into a signed value
  38050. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  38051. };
  38052. }
  38053. // Replace functions
  38054. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  38055. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  38056. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  38057. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  38058. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  38059. SIMDHelper._isEnabled = true;
  38060. };
  38061. SIMDHelper._isEnabled = false;
  38062. return SIMDHelper;
  38063. }());
  38064. BABYLON.SIMDHelper = SIMDHelper;
  38065. })(BABYLON || (BABYLON = {}));
  38066. var BABYLON;
  38067. (function (BABYLON) {
  38068. /**
  38069. * This class describe a rectangle that were added to the map.
  38070. * You have access to its coordinates either in pixel or normalized (UV)
  38071. */
  38072. var PackedRect = (function () {
  38073. function PackedRect(root, parent, pos, size) {
  38074. this._pos = pos;
  38075. this._size = size;
  38076. this._root = root;
  38077. this._parent = parent;
  38078. this._contentSize = null;
  38079. this._bottomNode = null;
  38080. this._leftNode = null;
  38081. this._initialSize = null;
  38082. this._rightNode = null;
  38083. }
  38084. Object.defineProperty(PackedRect.prototype, "pos", {
  38085. /**
  38086. * @returns the position of this node into the map
  38087. */
  38088. get: function () {
  38089. return this._pos;
  38090. },
  38091. enumerable: true,
  38092. configurable: true
  38093. });
  38094. Object.defineProperty(PackedRect.prototype, "contentSize", {
  38095. /**
  38096. * @returns the size of the rectangle this node handles
  38097. */
  38098. get: function () {
  38099. return this._contentSize;
  38100. },
  38101. enumerable: true,
  38102. configurable: true
  38103. });
  38104. Object.defineProperty(PackedRect.prototype, "UVs", {
  38105. /**
  38106. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  38107. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  38108. */
  38109. get: function () {
  38110. return this.getUVsForCustomSize(this._root._size);
  38111. },
  38112. enumerable: true,
  38113. configurable: true
  38114. });
  38115. /**
  38116. * 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.
  38117. * This method will return the UVs for this part by given the custom size of what you really use
  38118. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  38119. */
  38120. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  38121. var mainWidth = this._root._size.width;
  38122. var mainHeight = this._root._size.height;
  38123. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  38124. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  38125. var uvs = new Array();
  38126. uvs.push(topLeft);
  38127. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  38128. uvs.push(rightBottom);
  38129. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  38130. return uvs;
  38131. };
  38132. /**
  38133. * Free this rectangle from the map.
  38134. * Call this method when you no longer need the rectangle to be in the map.
  38135. */
  38136. PackedRect.prototype.freeContent = function () {
  38137. if (!this.contentSize) {
  38138. return;
  38139. }
  38140. this._contentSize = null;
  38141. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  38142. this.attemptDefrag();
  38143. };
  38144. Object.defineProperty(PackedRect.prototype, "isUsed", {
  38145. get: function () {
  38146. return this._contentSize != null || this._leftNode != null;
  38147. },
  38148. enumerable: true,
  38149. configurable: true
  38150. });
  38151. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  38152. var node = this.findNode(contentSize);
  38153. // Not enough space...
  38154. if (!node) {
  38155. return null;
  38156. }
  38157. node.splitNode(contentSize);
  38158. return node;
  38159. };
  38160. PackedRect.prototype.findNode = function (size) {
  38161. var resNode = null;
  38162. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  38163. if (this.isUsed) {
  38164. if (this._leftNode) {
  38165. resNode = this._leftNode.findNode(size);
  38166. }
  38167. if (!resNode && this._rightNode) {
  38168. resNode = this._rightNode.findNode(size);
  38169. }
  38170. if (!resNode && this._bottomNode) {
  38171. resNode = this._bottomNode.findNode(size);
  38172. }
  38173. }
  38174. else if (this._initialSize) {
  38175. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  38176. resNode = this;
  38177. }
  38178. else {
  38179. return null;
  38180. }
  38181. }
  38182. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  38183. resNode = this;
  38184. }
  38185. return resNode;
  38186. };
  38187. PackedRect.prototype.splitNode = function (contentSize) {
  38188. // 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)
  38189. if (!this._contentSize && this._initialSize) {
  38190. this._contentSize = contentSize.clone();
  38191. 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));
  38192. return this._leftNode.splitNode(contentSize);
  38193. }
  38194. else {
  38195. this._contentSize = contentSize.clone();
  38196. this._initialSize = contentSize.clone();
  38197. if (contentSize.width !== this._size.width) {
  38198. 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));
  38199. }
  38200. if (contentSize.height !== this._size.height) {
  38201. 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));
  38202. }
  38203. return this;
  38204. }
  38205. };
  38206. PackedRect.prototype.attemptDefrag = function () {
  38207. if (!this.isUsed && this.isRecursiveFree) {
  38208. this.clearNode();
  38209. if (this._parent) {
  38210. this._parent.attemptDefrag();
  38211. }
  38212. }
  38213. };
  38214. PackedRect.prototype.clearNode = function () {
  38215. this._initialSize = null;
  38216. this._rightNode = null;
  38217. this._bottomNode = null;
  38218. };
  38219. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  38220. get: function () {
  38221. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  38222. },
  38223. enumerable: true,
  38224. configurable: true
  38225. });
  38226. PackedRect.prototype.evalFreeSize = function (size) {
  38227. var levelSize = 0;
  38228. if (!this.isUsed) {
  38229. if (this._initialSize) {
  38230. levelSize = this._initialSize.surface;
  38231. }
  38232. else {
  38233. levelSize = this._size.surface;
  38234. }
  38235. }
  38236. if (this._rightNode) {
  38237. levelSize += this._rightNode.evalFreeSize(0);
  38238. }
  38239. if (this._bottomNode) {
  38240. levelSize += this._bottomNode.evalFreeSize(0);
  38241. }
  38242. return levelSize + size;
  38243. };
  38244. return PackedRect;
  38245. }());
  38246. BABYLON.PackedRect = PackedRect;
  38247. /**
  38248. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  38249. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  38250. * 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.
  38251. */
  38252. var RectPackingMap = (function (_super) {
  38253. __extends(RectPackingMap, _super);
  38254. /**
  38255. * Create an instance of the object with a dimension using the given size
  38256. * @param size The dimension of the rectangle that will contain all the sub ones.
  38257. */
  38258. function RectPackingMap(size) {
  38259. _super.call(this, null, null, BABYLON.Vector2.Zero(), size);
  38260. this._root = this;
  38261. }
  38262. /**
  38263. * Add a rectangle, finding the best location to store it into the map
  38264. * @param size the dimension of the rectangle to store
  38265. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  38266. */
  38267. RectPackingMap.prototype.addRect = function (size) {
  38268. var node = this.findAndSplitNode(size);
  38269. return node;
  38270. };
  38271. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  38272. /**
  38273. * Return the current space free normalized between [0;1]
  38274. * @returns {}
  38275. */
  38276. get: function () {
  38277. var freeSize = 0;
  38278. freeSize = this.evalFreeSize(freeSize);
  38279. return freeSize / (this._size.width * this._size.height);
  38280. },
  38281. enumerable: true,
  38282. configurable: true
  38283. });
  38284. return RectPackingMap;
  38285. }(PackedRect));
  38286. BABYLON.RectPackingMap = RectPackingMap;
  38287. })(BABYLON || (BABYLON = {}));
  38288. var BABYLON;
  38289. (function (BABYLON) {
  38290. var DynamicFloatArrayElementInfo = (function () {
  38291. function DynamicFloatArrayElementInfo() {
  38292. }
  38293. return DynamicFloatArrayElementInfo;
  38294. }());
  38295. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  38296. /**
  38297. * 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.
  38298. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  38299. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  38300. * 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.
  38301. * 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.
  38302. * 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".
  38303. */
  38304. var DynamicFloatArray = (function () {
  38305. /**
  38306. * Construct an instance of the dynamic float array
  38307. * @param stride size of one element in float (i.e. not bytes!)
  38308. * @param initialElementCount the number of available entries at construction
  38309. */
  38310. function DynamicFloatArray(stride, initialElementCount) {
  38311. this.compareValueOffset = null;
  38312. this.sortingAscending = true;
  38313. this._stride = stride;
  38314. this.buffer = new Float32Array(stride * initialElementCount);
  38315. this._lastUsed = 0;
  38316. this._firstFree = 0;
  38317. this._allEntries = new Array(initialElementCount);
  38318. this._freeEntries = new Array(initialElementCount);
  38319. for (var i = 0; i < initialElementCount; i++) {
  38320. var element = new DynamicFloatArrayElementInfo();
  38321. element.offset = i * stride;
  38322. this._allEntries[i] = element;
  38323. this._freeEntries[initialElementCount - i - 1] = element;
  38324. }
  38325. }
  38326. /**
  38327. * Allocate an element in the array.
  38328. * @return the element info instance that contains the offset into the main buffer of the element's location.
  38329. * Beware, this offset may change when you call pack()
  38330. */
  38331. DynamicFloatArray.prototype.allocElement = function () {
  38332. if (this._freeEntries.length === 0) {
  38333. this._growBuffer();
  38334. }
  38335. var el = this._freeEntries.pop();
  38336. this._lastUsed = Math.max(el.offset, this._lastUsed);
  38337. if (el.offset === this._firstFree) {
  38338. if (this._freeEntries.length > 0) {
  38339. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  38340. }
  38341. else {
  38342. this._firstFree += this._stride;
  38343. }
  38344. }
  38345. return el;
  38346. };
  38347. /**
  38348. * Free the element corresponding to the given element info
  38349. * @param elInfo the element that describe the allocated element
  38350. */
  38351. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  38352. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  38353. this._freeEntries.push(elInfo);
  38354. };
  38355. /**
  38356. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  38357. * 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().
  38358. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  38359. */
  38360. DynamicFloatArray.prototype.pack = function () {
  38361. // no free slot? no need to pack
  38362. if (this._freeEntries.length === 0) {
  38363. return this.buffer;
  38364. }
  38365. // If the buffer is already packed the last used will always be lower than the first free
  38366. // 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.
  38367. if (this._lastUsed < this._firstFree) {
  38368. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  38369. return elementsBuffer_1;
  38370. }
  38371. var s = this._stride;
  38372. // 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
  38373. var lastFree = new DynamicFloatArrayElementInfo();
  38374. lastFree.offset = this.totalElementCount * s;
  38375. this._freeEntries.push(lastFree);
  38376. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  38377. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  38378. var firstFreeSlotOffset = sortedFree[0].offset;
  38379. var freeZoneSize = 1;
  38380. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  38381. var prevOffset = sortedFree[0].offset;
  38382. for (var i = 1; i < sortedFree.length; i++) {
  38383. // 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
  38384. if (firstFreeSlotOffset >= occupiedZoneSize) {
  38385. break;
  38386. }
  38387. var curFree = sortedFree[i];
  38388. var curOffset = curFree.offset;
  38389. // Compute the distance between this offset and the previous
  38390. var distance = curOffset - prevOffset;
  38391. // If the distance is the stride size, they are adjacent, it good, move to the next
  38392. if (distance === s) {
  38393. // Free zone is one element bigger
  38394. ++freeZoneSize;
  38395. // as we're about to iterate to the next, the cur becomes the previous...
  38396. prevOffset = curOffset;
  38397. continue;
  38398. }
  38399. // Distance is bigger, which means there's x element between the previous free and this one
  38400. var usedRange = (distance / s) - 1;
  38401. // Two cases the free zone is smaller than the data to move or bigger
  38402. // Copy what can fit in the free zone
  38403. var curMoveOffset = curOffset - s;
  38404. var copyCount = Math.min(freeZoneSize, usedRange);
  38405. for (var j = 0; j < copyCount; j++) {
  38406. var freeI = firstFreeSlotOffset / s;
  38407. var curI = curMoveOffset / s;
  38408. var moveEl = sortedAll[curI];
  38409. this._moveElement(moveEl, firstFreeSlotOffset);
  38410. var replacedEl = sortedAll[freeI];
  38411. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  38412. replacedEl.offset = curMoveOffset;
  38413. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  38414. sortedAll[freeI] = moveEl;
  38415. sortedAll[curI] = replacedEl;
  38416. curMoveOffset -= s;
  38417. firstFreeSlotOffset += s;
  38418. }
  38419. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  38420. if (freeZoneSize <= usedRange) {
  38421. firstFreeSlotOffset = curMoveOffset + s;
  38422. freeZoneSize = 1 + copyCount;
  38423. }
  38424. else {
  38425. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  38426. }
  38427. // as we're about to iterate to the next, the cur becomes the previous...
  38428. prevOffset = curOffset;
  38429. }
  38430. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  38431. this._lastUsed = firstFreeSlotOffset - s;
  38432. this._firstFree = firstFreeSlotOffset;
  38433. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  38434. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  38435. this._allEntries = sortedAll;
  38436. return elementsBuffer;
  38437. };
  38438. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  38439. for (var i = 0; i < this._stride; i++) {
  38440. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  38441. }
  38442. element.offset = destOffset;
  38443. };
  38444. DynamicFloatArray.prototype._growBuffer = function () {
  38445. // Allocate the new buffer with 50% more entries, copy the content of the current one
  38446. var newElCount = Math.floor(this.totalElementCount * 1.5);
  38447. var newBuffer = new Float32Array(newElCount * this._stride);
  38448. newBuffer.set(this.buffer);
  38449. var curCount = this.totalElementCount;
  38450. var addedCount = newElCount - this.totalElementCount;
  38451. for (var i = 0; i < addedCount; i++) {
  38452. var element = new DynamicFloatArrayElementInfo();
  38453. element.offset = (curCount + i) * this.stride;
  38454. this._allEntries.push(element);
  38455. this._freeEntries[addedCount - i - 1] = element;
  38456. }
  38457. this._firstFree = curCount * this.stride;
  38458. this.buffer = newBuffer;
  38459. };
  38460. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  38461. /**
  38462. * Get the total count of entries that can fit in the current buffer
  38463. * @returns the elements count
  38464. */
  38465. get: function () {
  38466. return this._allEntries.length;
  38467. },
  38468. enumerable: true,
  38469. configurable: true
  38470. });
  38471. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  38472. /**
  38473. * Get the count of free entries that can still be allocated without resizing the buffer
  38474. * @returns the free elements count
  38475. */
  38476. get: function () {
  38477. return this._freeEntries.length;
  38478. },
  38479. enumerable: true,
  38480. configurable: true
  38481. });
  38482. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  38483. /**
  38484. * Get the count of allocated elements
  38485. * @returns the allocated elements count
  38486. */
  38487. get: function () {
  38488. return this._allEntries.length - this._freeEntries.length;
  38489. },
  38490. enumerable: true,
  38491. configurable: true
  38492. });
  38493. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  38494. /**
  38495. * Return the size of one element in float
  38496. * @returns the size in float
  38497. */
  38498. get: function () {
  38499. return this._stride;
  38500. },
  38501. enumerable: true,
  38502. configurable: true
  38503. });
  38504. DynamicFloatArray.prototype.sort = function () {
  38505. var _this = this;
  38506. if (!this.compareValueOffset) {
  38507. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  38508. }
  38509. var count = this.usedElementCount;
  38510. // Do we have to (re)create the sort table?
  38511. if (!this._sortTable || this._sortTable.length < count) {
  38512. // 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...
  38513. var newCount = Math.min(this.totalElementCount, count * 2);
  38514. this._sortTable = new Array(newCount);
  38515. }
  38516. if (!this._sortedTable || this._sortedTable.length !== count) {
  38517. this._sortedTable = new Array(count);
  38518. }
  38519. // Because, you know...
  38520. this.pack();
  38521. //let stride = this.stride;
  38522. //for (let i = 0; i < count; i++) {
  38523. // let si = this._sortTable[i];
  38524. // if (!si) {
  38525. // si = new SortInfo();
  38526. // this._sortTable[i] = si;
  38527. // }
  38528. // si.entry = this._allEntries[i];
  38529. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  38530. // si.swapedOffset = null;
  38531. // this._sortedTable[i] = si;
  38532. //}
  38533. var curOffset = 0;
  38534. var stride = this.stride;
  38535. for (var i = 0; i < count; i++, curOffset += stride) {
  38536. var si = this._sortTable[i];
  38537. if (!si) {
  38538. si = new SortInfo();
  38539. this._sortTable[i] = si;
  38540. }
  38541. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  38542. si.offset = curOffset;
  38543. si.swapedOffset = null;
  38544. this._sortedTable[i] = si;
  38545. }
  38546. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  38547. if (this.sortingAscending) {
  38548. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  38549. }
  38550. else {
  38551. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  38552. }
  38553. var swapElements = function (src, dst) {
  38554. for (var i = 0; i < stride; i++) {
  38555. var tps = _this.buffer[dst + i];
  38556. _this.buffer[dst + i] = _this.buffer[src + i];
  38557. _this.buffer[src + i] = tps;
  38558. }
  38559. };
  38560. // 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:
  38561. // 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),
  38562. // and I still want something with a good algorithm complexity.
  38563. // 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,
  38564. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  38565. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  38566. // 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
  38567. // until we find a SortInfo object without a swapedOffset which means we got the right location
  38568. // 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
  38569. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  38570. for (var i = 0; i < count; i++) {
  38571. // Get the element to move
  38572. var sourceSI = this._sortedTable[i];
  38573. var destSI = this._sortTable[i];
  38574. var sourceOff = sourceSI.offset;
  38575. // If the source changed location, find the new one
  38576. if (sourceSI.swapedOffset) {
  38577. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  38578. var curSI = sourceSI;
  38579. while (curSI.swapedOffset) {
  38580. curSI = this._sortTable[curSI.swapedOffset / stride];
  38581. }
  38582. // Finally get the right location
  38583. sourceOff = curSI.offset;
  38584. }
  38585. // Tag the element being replaced with its new location
  38586. destSI.swapedOffset = sourceOff;
  38587. // Swap elements (only if needed)
  38588. if (sourceOff !== destSI.offset) {
  38589. swapElements(sourceOff, destSI.offset);
  38590. }
  38591. // Update the offset in the corresponding DFAE
  38592. //sourceSI.entry.offset = destSI.entry.offset;
  38593. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  38594. }
  38595. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  38596. return true;
  38597. };
  38598. return DynamicFloatArray;
  38599. }());
  38600. BABYLON.DynamicFloatArray = DynamicFloatArray;
  38601. var SortInfo = (function () {
  38602. function SortInfo() {
  38603. this.compareData = this.offset = this.swapedOffset = null;
  38604. }
  38605. return SortInfo;
  38606. }());
  38607. })(BABYLON || (BABYLON = {}));
  38608. var BABYLON;
  38609. (function (BABYLON) {
  38610. /**
  38611. * This class given information about a given character.
  38612. */
  38613. var CharInfo = (function () {
  38614. function CharInfo() {
  38615. }
  38616. return CharInfo;
  38617. }());
  38618. BABYLON.CharInfo = CharInfo;
  38619. var FontTexture = (function (_super) {
  38620. __extends(FontTexture, _super);
  38621. /**
  38622. * Create a new instance of the FontTexture class
  38623. * @param name the name of the texture
  38624. * @param font the font to use, use the W3C CSS notation
  38625. * @param scene the scene that owns the texture
  38626. * @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
  38627. * @param samplingMode the texture sampling mode
  38628. * @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.
  38629. */
  38630. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  38631. if (maxCharCount === void 0) { maxCharCount = 200; }
  38632. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38633. if (superSample === void 0) { superSample = false; }
  38634. if (signedDistanceField === void 0) { signedDistanceField = false; }
  38635. _super.call(this, null, scene, true, false, samplingMode);
  38636. this._charInfos = {};
  38637. this._curCharCount = 0;
  38638. this._lastUpdateCharCount = -1;
  38639. this._usedCounter = 1;
  38640. this.name = name;
  38641. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38642. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38643. this._sdfScale = 8;
  38644. this._signedDistanceField = signedDistanceField;
  38645. this._superSample = false;
  38646. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  38647. if (superSample || signedDistanceField) {
  38648. var sfont = this.getSuperSampleFont(font);
  38649. if (sfont) {
  38650. this._superSample = true;
  38651. font = sfont;
  38652. }
  38653. }
  38654. // First canvas creation to determine the size of the texture to create
  38655. this._canvas = document.createElement("canvas");
  38656. this._context = this._canvas.getContext("2d");
  38657. this._context.font = font;
  38658. this._context.fillStyle = "white";
  38659. this._context.textBaseline = "top";
  38660. this._cachedFontId = null;
  38661. var res = this.getFontHeight(font);
  38662. this._lineHeightSuper = res.height + 4;
  38663. this._lineHeight = this._superSample ? (Math.ceil(this._lineHeightSuper / 2)) : this._lineHeightSuper;
  38664. this._offset = res.offset - 1;
  38665. this._xMargin = 1 + Math.ceil(this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  38666. this._yMargin = this._xMargin;
  38667. var maxCharWidth = this._context.measureText("W").width;
  38668. this._spaceWidthSuper = this._context.measureText(" ").width;
  38669. this._spaceWidth = this._superSample ? (this._spaceWidthSuper / 2) : this._spaceWidthSuper;
  38670. // This is an approximate size, but should always be able to fit at least the maxCharCount
  38671. var totalEstSurface = (this._lineHeightSuper + this._yMargin) * (maxCharWidth + this._xMargin) * maxCharCount;
  38672. var edge = Math.sqrt(totalEstSurface);
  38673. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  38674. // Create the texture that will store the font characters
  38675. this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  38676. var textureSize = this.getSize();
  38677. this.hasAlpha = this._signedDistanceField === false;
  38678. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  38679. this._canvas = document.createElement("canvas");
  38680. this._canvas.width = textureSize.width;
  38681. this._canvas.height = textureSize.height;
  38682. this._context = this._canvas.getContext("2d");
  38683. this._context.textBaseline = "top";
  38684. this._context.font = font;
  38685. this._context.fillStyle = "white";
  38686. this._context.imageSmoothingEnabled = false;
  38687. this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  38688. // 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
  38689. // 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)
  38690. // So you can see this context as an intermediate one, because it is.
  38691. if (this._signedDistanceField) {
  38692. var sdfC = document.createElement("canvas");
  38693. var s = this._sdfScale;
  38694. sdfC.width = maxCharWidth * s;
  38695. sdfC.height = this._lineHeightSuper * s;
  38696. var sdfCtx = sdfC.getContext("2d");
  38697. sdfCtx.scale(s, s);
  38698. sdfCtx.textBaseline = "top";
  38699. sdfCtx.font = font;
  38700. sdfCtx.fillStyle = "white";
  38701. sdfCtx.imageSmoothingEnabled = false;
  38702. this._sdfCanvas = sdfC;
  38703. this._sdfContext = sdfCtx;
  38704. }
  38705. this._currentFreePosition = BABYLON.Vector2.Zero();
  38706. // Add the basic ASCII based characters
  38707. for (var i = 0x20; i < 0x7F; i++) {
  38708. var c = String.fromCharCode(i);
  38709. this.getChar(c);
  38710. }
  38711. this.update();
  38712. }
  38713. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  38714. get: function () {
  38715. return this._superSample;
  38716. },
  38717. enumerable: true,
  38718. configurable: true
  38719. });
  38720. Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
  38721. get: function () {
  38722. return this._signedDistanceField;
  38723. },
  38724. enumerable: true,
  38725. configurable: true
  38726. });
  38727. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  38728. get: function () {
  38729. return this._spaceWidth;
  38730. },
  38731. enumerable: true,
  38732. configurable: true
  38733. });
  38734. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  38735. get: function () {
  38736. return this._lineHeight;
  38737. },
  38738. enumerable: true,
  38739. configurable: true
  38740. });
  38741. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  38742. if (supersample === void 0) { supersample = false; }
  38743. if (signedDistanceField === void 0) { signedDistanceField = false; }
  38744. var s = scene;
  38745. if (!s.__fontTextureCache__) {
  38746. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  38747. }
  38748. var dic = s.__fontTextureCache__;
  38749. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  38750. var ft = dic.get(lfn);
  38751. if (ft) {
  38752. ++ft._usedCounter;
  38753. return ft;
  38754. }
  38755. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  38756. ft._cachedFontId = lfn;
  38757. dic.add(lfn, ft);
  38758. return ft;
  38759. };
  38760. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  38761. if (supersample === void 0) { supersample = false; }
  38762. if (signedDistanceField === void 0) { signedDistanceField = false; }
  38763. var s = scene;
  38764. var dic = s.__fontTextureCache__;
  38765. if (!dic) {
  38766. return;
  38767. }
  38768. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  38769. var font = dic.get(lfn);
  38770. if (--font._usedCounter === 0) {
  38771. dic.remove(lfn);
  38772. font.dispose();
  38773. }
  38774. };
  38775. /**
  38776. * Make sure the given char is present in the font map.
  38777. * @param char the character to get or add
  38778. * @return the CharInfo instance corresponding to the given character
  38779. */
  38780. FontTexture.prototype.getChar = function (char) {
  38781. if (char.length !== 1) {
  38782. return null;
  38783. }
  38784. var info = this._charInfos[char];
  38785. if (info) {
  38786. return info;
  38787. }
  38788. info = new CharInfo();
  38789. var measure = this._context.measureText(char);
  38790. var textureSize = this.getSize();
  38791. // we reached the end of the current line?
  38792. var width = Math.round(measure.width);
  38793. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  38794. this._currentFreePosition.x = 0;
  38795. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  38796. // No more room?
  38797. if (this._currentFreePosition.y > textureSize.height) {
  38798. return this.getChar("!");
  38799. }
  38800. }
  38801. // 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)
  38802. if (this._signedDistanceField) {
  38803. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  38804. this._sdfContext.fillText(char, 0, -this._offset);
  38805. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  38806. var res = this._computeSDFChar(data);
  38807. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  38808. }
  38809. else {
  38810. // Draw the character in the HTML canvas
  38811. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  38812. }
  38813. // Fill the CharInfo object
  38814. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  38815. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  38816. if (this._signedDistanceField) {
  38817. var off = 1 / textureSize.width;
  38818. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  38819. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  38820. }
  38821. info.charWidth = this._superSample ? (width / 2) : width;
  38822. // Add the info structure
  38823. this._charInfos[char] = info;
  38824. this._curCharCount++;
  38825. // Set the next position
  38826. this._currentFreePosition.x += width + this._xMargin;
  38827. return info;
  38828. };
  38829. FontTexture.prototype._computeSDFChar = function (source) {
  38830. var scl = this._sdfScale;
  38831. var sw = source.width;
  38832. var sh = source.height;
  38833. var dw = sw / scl;
  38834. var dh = sh / scl;
  38835. var roffx = 0;
  38836. var roffy = 0;
  38837. // We shouldn't look beyond half of the biggest between width and height
  38838. var radius = scl;
  38839. var br = radius - 1;
  38840. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  38841. var sx = dx * scl;
  38842. var sy = dy * scl;
  38843. // Looking out of the area? return true to make the test going on
  38844. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  38845. return true;
  38846. }
  38847. // Get the pixel we want
  38848. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  38849. var res = (val > 0) === lookVis;
  38850. if (!res) {
  38851. roffx = offX;
  38852. roffy = offY;
  38853. }
  38854. return res;
  38855. };
  38856. var lookupArea = function (dx, dy, lookVis) {
  38857. // 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
  38858. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  38859. lookupSrc(dx, dy, 0, -br, lookVis) &&
  38860. lookupSrc(dx, dy, -br, 0, lookVis) &&
  38861. lookupSrc(dx, dy, br, 0, lookVis)) {
  38862. return 0;
  38863. }
  38864. for (var i = 1; i <= radius; i++) {
  38865. // Quick test N, S, W, E
  38866. 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)) {
  38867. return i * i; // Squared Distance is simple to compute in this case
  38868. }
  38869. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  38870. for (var j = 1; j <= i; j++) {
  38871. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  38872. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  38873. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  38874. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  38875. // We found the nearest texel having and opposite state, store the squared length
  38876. var res_1 = (i * i) + (j * j);
  38877. var count = 1;
  38878. // 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
  38879. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  38880. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  38881. ++count;
  38882. }
  38883. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  38884. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  38885. ++count;
  38886. }
  38887. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  38888. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  38889. ++count;
  38890. }
  38891. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  38892. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  38893. ++count;
  38894. }
  38895. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  38896. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  38897. ++count;
  38898. }
  38899. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  38900. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  38901. ++count;
  38902. }
  38903. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  38904. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  38905. ++count;
  38906. }
  38907. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  38908. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  38909. ++count;
  38910. }
  38911. // Compute the average based on the accumulated distance
  38912. return res_1 / count;
  38913. }
  38914. }
  38915. }
  38916. return 0;
  38917. };
  38918. var tmp = new Array(dw * dh);
  38919. for (var y = 0; y < dh; y++) {
  38920. for (var x = 0; x < dw; x++) {
  38921. var curState = lookupSrc(x, y, 0, 0, true);
  38922. var d = lookupArea(x, y, curState);
  38923. if (d === 0) {
  38924. d = radius * radius * 2;
  38925. }
  38926. tmp[(y * dw) + x] = curState ? d : -d;
  38927. }
  38928. }
  38929. var res = this._context.createImageData(dw, dh);
  38930. var size = dw * dh;
  38931. for (var j = 0; j < size; j++) {
  38932. var d = tmp[j];
  38933. var sign = (d < 0) ? -1 : 1;
  38934. d = Math.sqrt(Math.abs(d)) * sign;
  38935. d *= 127.5 / radius;
  38936. d += 127.5;
  38937. if (d < 0) {
  38938. d = 0;
  38939. }
  38940. else if (d > 255) {
  38941. d = 255;
  38942. }
  38943. d += 0.5;
  38944. res.data[j * 4 + 0] = d;
  38945. res.data[j * 4 + 1] = d;
  38946. res.data[j * 4 + 2] = d;
  38947. res.data[j * 4 + 3] = 255;
  38948. }
  38949. return res;
  38950. };
  38951. FontTexture.prototype.measureText = function (text, tabulationSize) {
  38952. if (tabulationSize === void 0) { tabulationSize = 4; }
  38953. var maxWidth = 0;
  38954. var curWidth = 0;
  38955. var lineCount = 1;
  38956. var charxpos = 0;
  38957. // Parse each char of the string
  38958. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  38959. var char = text_1[_i];
  38960. // Next line feed?
  38961. if (char === "\n") {
  38962. maxWidth = Math.max(maxWidth, curWidth);
  38963. charxpos = 0;
  38964. curWidth = 0;
  38965. ++lineCount;
  38966. continue;
  38967. }
  38968. // Tabulation ?
  38969. if (char === "\t") {
  38970. var nextPos = charxpos + tabulationSize;
  38971. nextPos = nextPos - (nextPos % tabulationSize);
  38972. curWidth += (nextPos - charxpos) * this.spaceWidth;
  38973. charxpos = nextPos;
  38974. continue;
  38975. }
  38976. if (char < " ") {
  38977. continue;
  38978. }
  38979. curWidth += this.getChar(char).charWidth;
  38980. ++charxpos;
  38981. }
  38982. maxWidth = Math.max(maxWidth, curWidth);
  38983. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  38984. };
  38985. FontTexture.prototype.getSuperSampleFont = function (font) {
  38986. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  38987. 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*$/;
  38988. var res = font.toLocaleLowerCase().match(regex);
  38989. if (res == null) {
  38990. return null;
  38991. }
  38992. var size = parseInt(res[4]);
  38993. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  38994. var newFont = "";
  38995. for (var j = 1; j < res.length; j++) {
  38996. if (res[j] != null) {
  38997. newFont += res[j] + " ";
  38998. }
  38999. }
  39000. return newFont;
  39001. };
  39002. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  39003. FontTexture.prototype.getFontHeight = function (font) {
  39004. var fontDraw = document.createElement("canvas");
  39005. var ctx = fontDraw.getContext('2d');
  39006. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  39007. ctx.textBaseline = 'top';
  39008. ctx.fillStyle = 'white';
  39009. ctx.font = font;
  39010. ctx.fillText('jH|', 0, 0);
  39011. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  39012. var start = -1;
  39013. var end = -1;
  39014. for (var row = 0; row < fontDraw.height; row++) {
  39015. for (var column = 0; column < fontDraw.width; column++) {
  39016. var index = (row * fontDraw.width + column) * 4;
  39017. if (pixels[index] === 0) {
  39018. if (column === fontDraw.width - 1 && start !== -1) {
  39019. end = row;
  39020. row = fontDraw.height;
  39021. break;
  39022. }
  39023. continue;
  39024. }
  39025. else {
  39026. if (start === -1) {
  39027. start = row;
  39028. }
  39029. break;
  39030. }
  39031. }
  39032. }
  39033. return { height: (end - start) + 1, offset: start - 1 };
  39034. };
  39035. Object.defineProperty(FontTexture.prototype, "canRescale", {
  39036. get: function () {
  39037. return false;
  39038. },
  39039. enumerable: true,
  39040. configurable: true
  39041. });
  39042. FontTexture.prototype.getContext = function () {
  39043. return this._context;
  39044. };
  39045. /**
  39046. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  39047. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  39048. */
  39049. FontTexture.prototype.update = function () {
  39050. // Update only if there's new char added since the previous update
  39051. if (this._lastUpdateCharCount < this._curCharCount) {
  39052. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  39053. this._lastUpdateCharCount = this._curCharCount;
  39054. }
  39055. };
  39056. // cloning should be prohibited, there's no point to duplicate this texture at all
  39057. FontTexture.prototype.clone = function () {
  39058. return null;
  39059. };
  39060. /**
  39061. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  39062. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  39063. */
  39064. FontTexture.prototype.incCachedFontTextureCounter = function () {
  39065. ++this._usedCounter;
  39066. };
  39067. /**
  39068. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  39069. */
  39070. FontTexture.prototype.decCachedFontTextureCounter = function () {
  39071. var s = this.getScene();
  39072. var dic = s.__fontTextureCache__;
  39073. if (!dic) {
  39074. return;
  39075. }
  39076. if (--this._usedCounter === 0) {
  39077. dic.remove(this._cachedFontId);
  39078. this.dispose();
  39079. }
  39080. };
  39081. return FontTexture;
  39082. }(BABYLON.Texture));
  39083. BABYLON.FontTexture = FontTexture;
  39084. })(BABYLON || (BABYLON = {}));
  39085. var BABYLON;
  39086. (function (BABYLON) {
  39087. var MapTexture = (function (_super) {
  39088. __extends(MapTexture, _super);
  39089. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  39090. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  39091. if (useMipMap === void 0) { useMipMap = false; }
  39092. _super.call(this, null, scene, !useMipMap, false, samplingMode);
  39093. this.name = name;
  39094. this._size = size;
  39095. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39096. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39097. // Create the rectPackMap that will allocate portion of the texture
  39098. this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  39099. // Create the texture that will store the content
  39100. this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  39101. }
  39102. /**
  39103. * Allocate a rectangle of a given size in the texture map
  39104. * @param size the size of the rectangle to allocation
  39105. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  39106. */
  39107. MapTexture.prototype.allocateRect = function (size) {
  39108. return this._rectPackingMap.addRect(size);
  39109. };
  39110. /**
  39111. * Free a given rectangle from the texture map
  39112. * @param rectInfo the instance corresponding to the rect to free.
  39113. */
  39114. MapTexture.prototype.freeRect = function (rectInfo) {
  39115. if (rectInfo) {
  39116. rectInfo.freeContent();
  39117. }
  39118. };
  39119. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  39120. /**
  39121. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  39122. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  39123. * @returns {}
  39124. */
  39125. get: function () {
  39126. return this._rectPackingMap.freeSpace;
  39127. },
  39128. enumerable: true,
  39129. configurable: true
  39130. });
  39131. /**
  39132. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  39133. * 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.
  39134. * Don't forget to call unbindTexture when you're done rendering
  39135. * @param rect the zone to render to
  39136. * @param clear true to clear the portion's color/depth data
  39137. */
  39138. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  39139. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  39140. };
  39141. /**
  39142. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  39143. * 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.
  39144. * Don't forget to call unbindTexture when you're done rendering
  39145. * @param pos the position into the texture
  39146. * @param size the portion to fit the clip space to
  39147. * @param clear true to clear the portion's color/depth data
  39148. */
  39149. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  39150. var engine = this.getScene().getEngine();
  39151. engine.bindFramebuffer(this._texture);
  39152. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  39153. if (clear) {
  39154. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  39155. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  39156. }
  39157. };
  39158. /**
  39159. * Unbind the texture map from the rendering engine.
  39160. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  39161. * @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.
  39162. */
  39163. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  39164. // Dump ?
  39165. if (dumpForDebug) {
  39166. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  39167. }
  39168. var engine = this.getScene().getEngine();
  39169. if (this._replacedViewport) {
  39170. engine.setViewport(this._replacedViewport);
  39171. this._replacedViewport = null;
  39172. }
  39173. engine.unBindFramebuffer(this._texture);
  39174. };
  39175. Object.defineProperty(MapTexture.prototype, "canRescale", {
  39176. get: function () {
  39177. return false;
  39178. },
  39179. enumerable: true,
  39180. configurable: true
  39181. });
  39182. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  39183. // Anyway, there's not much point to use this method for this kind of texture I guess
  39184. MapTexture.prototype.clone = function () {
  39185. return null;
  39186. };
  39187. return MapTexture;
  39188. }(BABYLON.Texture));
  39189. BABYLON.MapTexture = MapTexture;
  39190. })(BABYLON || (BABYLON = {}));
  39191. var BABYLON;
  39192. (function (BABYLON) {
  39193. var ShaderMaterial = (function (_super) {
  39194. __extends(ShaderMaterial, _super);
  39195. function ShaderMaterial(name, scene, shaderPath, options) {
  39196. _super.call(this, name, scene);
  39197. this._textures = {};
  39198. this._textureArrays = {};
  39199. this._floats = {};
  39200. this._floatsArrays = {};
  39201. this._colors3 = {};
  39202. this._colors4 = {};
  39203. this._vectors2 = {};
  39204. this._vectors3 = {};
  39205. this._vectors4 = {};
  39206. this._matrices = {};
  39207. this._matrices3x3 = {};
  39208. this._matrices2x2 = {};
  39209. this._vectors3Arrays = {};
  39210. this._cachedWorldViewMatrix = new BABYLON.Matrix();
  39211. this._shaderPath = shaderPath;
  39212. options.needAlphaBlending = options.needAlphaBlending || false;
  39213. options.needAlphaTesting = options.needAlphaTesting || false;
  39214. options.attributes = options.attributes || ["position", "normal", "uv"];
  39215. options.uniforms = options.uniforms || ["worldViewProjection"];
  39216. options.samplers = options.samplers || [];
  39217. options.defines = options.defines || [];
  39218. this._options = options;
  39219. }
  39220. ShaderMaterial.prototype.needAlphaBlending = function () {
  39221. return this._options.needAlphaBlending;
  39222. };
  39223. ShaderMaterial.prototype.needAlphaTesting = function () {
  39224. return this._options.needAlphaTesting;
  39225. };
  39226. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  39227. if (this._options.uniforms.indexOf(uniformName) === -1) {
  39228. this._options.uniforms.push(uniformName);
  39229. }
  39230. };
  39231. ShaderMaterial.prototype.setTexture = function (name, texture) {
  39232. if (this._options.samplers.indexOf(name) === -1) {
  39233. this._options.samplers.push(name);
  39234. }
  39235. this._textures[name] = texture;
  39236. return this;
  39237. };
  39238. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  39239. if (this._options.samplers.indexOf(name) === -1) {
  39240. this._options.samplers.push(name);
  39241. }
  39242. this._checkUniform(name);
  39243. this._textureArrays[name] = textures;
  39244. return this;
  39245. };
  39246. ShaderMaterial.prototype.setFloat = function (name, value) {
  39247. this._checkUniform(name);
  39248. this._floats[name] = value;
  39249. return this;
  39250. };
  39251. ShaderMaterial.prototype.setFloats = function (name, value) {
  39252. this._checkUniform(name);
  39253. this._floatsArrays[name] = value;
  39254. return this;
  39255. };
  39256. ShaderMaterial.prototype.setColor3 = function (name, value) {
  39257. this._checkUniform(name);
  39258. this._colors3[name] = value;
  39259. return this;
  39260. };
  39261. ShaderMaterial.prototype.setColor4 = function (name, value) {
  39262. this._checkUniform(name);
  39263. this._colors4[name] = value;
  39264. return this;
  39265. };
  39266. ShaderMaterial.prototype.setVector2 = function (name, value) {
  39267. this._checkUniform(name);
  39268. this._vectors2[name] = value;
  39269. return this;
  39270. };
  39271. ShaderMaterial.prototype.setVector3 = function (name, value) {
  39272. this._checkUniform(name);
  39273. this._vectors3[name] = value;
  39274. return this;
  39275. };
  39276. ShaderMaterial.prototype.setVector4 = function (name, value) {
  39277. this._checkUniform(name);
  39278. this._vectors4[name] = value;
  39279. return this;
  39280. };
  39281. ShaderMaterial.prototype.setMatrix = function (name, value) {
  39282. this._checkUniform(name);
  39283. this._matrices[name] = value;
  39284. return this;
  39285. };
  39286. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  39287. this._checkUniform(name);
  39288. this._matrices3x3[name] = value;
  39289. return this;
  39290. };
  39291. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  39292. this._checkUniform(name);
  39293. this._matrices2x2[name] = value;
  39294. return this;
  39295. };
  39296. ShaderMaterial.prototype.setArray3 = function (name, value) {
  39297. this._checkUniform(name);
  39298. this._vectors3Arrays[name] = value;
  39299. return this;
  39300. };
  39301. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  39302. var scene = this.getScene();
  39303. var engine = scene.getEngine();
  39304. if (!this.checkReadyOnEveryCall) {
  39305. if (this._renderId === scene.getRenderId()) {
  39306. return true;
  39307. }
  39308. }
  39309. // Instances
  39310. var defines = [];
  39311. var fallbacks = new BABYLON.EffectFallbacks();
  39312. if (useInstances) {
  39313. defines.push("#define INSTANCES");
  39314. }
  39315. for (var index = 0; index < this._options.defines.length; index++) {
  39316. defines.push(this._options.defines[index]);
  39317. }
  39318. // Bones
  39319. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  39320. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  39321. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  39322. fallbacks.addCPUSkinningFallback(0, mesh);
  39323. }
  39324. // Alpha test
  39325. if (engine.getAlphaTesting()) {
  39326. defines.push("#define ALPHATEST");
  39327. }
  39328. var previousEffect = this._effect;
  39329. var join = defines.join("\n");
  39330. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  39331. if (!this._effect.isReady()) {
  39332. return false;
  39333. }
  39334. if (previousEffect !== this._effect) {
  39335. scene.resetCachedMaterial();
  39336. }
  39337. this._renderId = scene.getRenderId();
  39338. return true;
  39339. };
  39340. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  39341. var scene = this.getScene();
  39342. if (this._options.uniforms.indexOf("world") !== -1) {
  39343. this._effect.setMatrix("world", world);
  39344. }
  39345. if (this._options.uniforms.indexOf("worldView") !== -1) {
  39346. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  39347. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  39348. }
  39349. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  39350. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  39351. }
  39352. };
  39353. ShaderMaterial.prototype.bind = function (world, mesh) {
  39354. // Std values
  39355. this.bindOnlyWorldMatrix(world);
  39356. if (this.getScene().getCachedMaterial() !== this) {
  39357. if (this._options.uniforms.indexOf("view") !== -1) {
  39358. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  39359. }
  39360. if (this._options.uniforms.indexOf("projection") !== -1) {
  39361. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  39362. }
  39363. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  39364. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  39365. }
  39366. // Bones
  39367. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  39368. var name;
  39369. // Texture
  39370. for (name in this._textures) {
  39371. this._effect.setTexture(name, this._textures[name]);
  39372. }
  39373. // Texture arrays
  39374. for (name in this._textureArrays) {
  39375. this._effect.setTextureArray(name, this._textureArrays[name]);
  39376. }
  39377. // Float
  39378. for (name in this._floats) {
  39379. this._effect.setFloat(name, this._floats[name]);
  39380. }
  39381. // Float s
  39382. for (name in this._floatsArrays) {
  39383. this._effect.setArray(name, this._floatsArrays[name]);
  39384. }
  39385. // Color3
  39386. for (name in this._colors3) {
  39387. this._effect.setColor3(name, this._colors3[name]);
  39388. }
  39389. // Color4
  39390. for (name in this._colors4) {
  39391. var color = this._colors4[name];
  39392. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  39393. }
  39394. // Vector2
  39395. for (name in this._vectors2) {
  39396. this._effect.setVector2(name, this._vectors2[name]);
  39397. }
  39398. // Vector3
  39399. for (name in this._vectors3) {
  39400. this._effect.setVector3(name, this._vectors3[name]);
  39401. }
  39402. // Vector4
  39403. for (name in this._vectors4) {
  39404. this._effect.setVector4(name, this._vectors4[name]);
  39405. }
  39406. // Matrix
  39407. for (name in this._matrices) {
  39408. this._effect.setMatrix(name, this._matrices[name]);
  39409. }
  39410. // Matrix 3x3
  39411. for (name in this._matrices3x3) {
  39412. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  39413. }
  39414. // Matrix 2x2
  39415. for (name in this._matrices2x2) {
  39416. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  39417. }
  39418. // Vector3Array
  39419. for (name in this._vectors3Arrays) {
  39420. this._effect.setArray3(name, this._vectors3Arrays[name]);
  39421. }
  39422. }
  39423. _super.prototype.bind.call(this, world, mesh);
  39424. };
  39425. ShaderMaterial.prototype.clone = function (name) {
  39426. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  39427. return newShaderMaterial;
  39428. };
  39429. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  39430. if (forceDisposeTextures) {
  39431. var name;
  39432. for (name in this._textures) {
  39433. this._textures[name].dispose();
  39434. }
  39435. for (name in this._textureArrays) {
  39436. var array = this._textureArrays[name];
  39437. for (var index = 0; index < array.length; index++) {
  39438. array[index].dispose();
  39439. }
  39440. }
  39441. }
  39442. this._textures = {};
  39443. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  39444. };
  39445. ShaderMaterial.prototype.serialize = function () {
  39446. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  39447. serializationObject.customType = "BABYLON.ShaderMaterial";
  39448. serializationObject.options = this._options;
  39449. serializationObject.shaderPath = this._shaderPath;
  39450. var name;
  39451. // Texture
  39452. serializationObject.textures = {};
  39453. for (name in this._textures) {
  39454. serializationObject.textures[name] = this._textures[name].serialize();
  39455. }
  39456. // Texture arrays
  39457. serializationObject.textureArrays = {};
  39458. for (name in this._textureArrays) {
  39459. serializationObject.textureArrays[name] = [];
  39460. var array = this._textureArrays[name];
  39461. for (var index = 0; index < array.length; index++) {
  39462. serializationObject.textureArrays[name].push(array[index].serialize());
  39463. }
  39464. }
  39465. // Float
  39466. serializationObject.floats = {};
  39467. for (name in this._floats) {
  39468. serializationObject.floats[name] = this._floats[name];
  39469. }
  39470. // Float s
  39471. serializationObject.floatArrays = {};
  39472. for (name in this._floatsArrays) {
  39473. serializationObject.floatArrays[name] = this._floatsArrays[name];
  39474. }
  39475. // Color3
  39476. serializationObject.colors3 = {};
  39477. for (name in this._colors3) {
  39478. serializationObject.colors3[name] = this._colors3[name].asArray();
  39479. }
  39480. // Color4
  39481. serializationObject.colors4 = {};
  39482. for (name in this._colors4) {
  39483. serializationObject.colors4[name] = this._colors4[name].asArray();
  39484. }
  39485. // Vector2
  39486. serializationObject.vectors2 = {};
  39487. for (name in this._vectors2) {
  39488. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  39489. }
  39490. // Vector3
  39491. serializationObject.vectors3 = {};
  39492. for (name in this._vectors3) {
  39493. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  39494. }
  39495. // Vector4
  39496. serializationObject.vectors4 = {};
  39497. for (name in this._vectors4) {
  39498. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  39499. }
  39500. // Matrix
  39501. serializationObject.matrices = {};
  39502. for (name in this._matrices) {
  39503. serializationObject.matrices[name] = this._matrices[name].asArray();
  39504. }
  39505. // Matrix 3x3
  39506. serializationObject.matrices3x3 = {};
  39507. for (name in this._matrices3x3) {
  39508. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  39509. }
  39510. // Matrix 2x2
  39511. serializationObject.matrices2x2 = {};
  39512. for (name in this._matrices2x2) {
  39513. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  39514. }
  39515. // Vector3Array
  39516. serializationObject.vectors3Arrays = {};
  39517. for (name in this._vectors3Arrays) {
  39518. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  39519. }
  39520. return serializationObject;
  39521. };
  39522. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  39523. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  39524. var name;
  39525. // Texture
  39526. for (name in source.textures) {
  39527. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  39528. }
  39529. // Texture arrays
  39530. for (name in source.textureArrays) {
  39531. var array = source.textureArrays[name];
  39532. var textureArray = new Array();
  39533. for (var index = 0; index < array.length; index++) {
  39534. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  39535. }
  39536. material.setTextureArray(name, textureArray);
  39537. }
  39538. // Float
  39539. for (name in source.floats) {
  39540. material.setFloat(name, source.floats[name]);
  39541. }
  39542. // Float s
  39543. for (name in source.floatsArrays) {
  39544. material.setFloats(name, source.floatsArrays[name]);
  39545. }
  39546. // Color3
  39547. for (name in source.colors3) {
  39548. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  39549. }
  39550. // Color4
  39551. for (name in source.colors4) {
  39552. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  39553. }
  39554. // Vector2
  39555. for (name in source.vectors2) {
  39556. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  39557. }
  39558. // Vector3
  39559. for (name in source.vectors3) {
  39560. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  39561. }
  39562. // Vector4
  39563. for (name in source.vectors4) {
  39564. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  39565. }
  39566. // Matrix
  39567. for (name in source.matrices) {
  39568. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  39569. }
  39570. // Matrix 3x3
  39571. for (name in source.matrices3x3) {
  39572. material.setMatrix3x3(name, source.matrices3x3[name]);
  39573. }
  39574. // Matrix 2x2
  39575. for (name in source.matrices2x2) {
  39576. material.setMatrix2x2(name, source.matrices2x2[name]);
  39577. }
  39578. // Vector3Array
  39579. for (name in source.vectors3Arrays) {
  39580. material.setArray3(name, source.vectors3Arrays[name]);
  39581. }
  39582. return material;
  39583. };
  39584. return ShaderMaterial;
  39585. }(BABYLON.Material));
  39586. BABYLON.ShaderMaterial = ShaderMaterial;
  39587. })(BABYLON || (BABYLON = {}));
  39588. var BABYLON;
  39589. (function (BABYLON) {
  39590. var Internals;
  39591. (function (Internals) {
  39592. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  39593. // All values and structures referenced from:
  39594. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  39595. var DDS_MAGIC = 0x20534444;
  39596. 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;
  39597. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  39598. 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;
  39599. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  39600. function FourCCToInt32(value) {
  39601. return value.charCodeAt(0) +
  39602. (value.charCodeAt(1) << 8) +
  39603. (value.charCodeAt(2) << 16) +
  39604. (value.charCodeAt(3) << 24);
  39605. }
  39606. function Int32ToFourCC(value) {
  39607. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  39608. }
  39609. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  39610. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  39611. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  39612. var headerLengthInt = 31; // The header length in 32 bit ints
  39613. // Offsets into the header array
  39614. var off_magic = 0;
  39615. var off_size = 1;
  39616. var off_flags = 2;
  39617. var off_height = 3;
  39618. var off_width = 4;
  39619. var off_mipmapCount = 7;
  39620. var off_pfFlags = 20;
  39621. var off_pfFourCC = 21;
  39622. var off_RGBbpp = 22;
  39623. var off_RMask = 23;
  39624. var off_GMask = 24;
  39625. var off_BMask = 25;
  39626. var off_AMask = 26;
  39627. var off_caps1 = 27;
  39628. var off_caps2 = 28;
  39629. ;
  39630. var DDSTools = (function () {
  39631. function DDSTools() {
  39632. }
  39633. DDSTools.GetDDSInfo = function (arrayBuffer) {
  39634. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  39635. var mipmapCount = 1;
  39636. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  39637. mipmapCount = Math.max(1, header[off_mipmapCount]);
  39638. }
  39639. return {
  39640. width: header[off_width],
  39641. height: header[off_height],
  39642. mipmapCount: mipmapCount,
  39643. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  39644. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  39645. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  39646. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  39647. };
  39648. };
  39649. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39650. var byteArray = new Uint8Array(dataLength);
  39651. var srcData = new Uint8Array(arrayBuffer);
  39652. var index = 0;
  39653. for (var y = height - 1; y >= 0; y--) {
  39654. for (var x = 0; x < width; x++) {
  39655. var srcPos = dataOffset + (x + y * width) * 4;
  39656. byteArray[index + 2] = srcData[srcPos];
  39657. byteArray[index + 1] = srcData[srcPos + 1];
  39658. byteArray[index] = srcData[srcPos + 2];
  39659. byteArray[index + 3] = srcData[srcPos + 3];
  39660. index += 4;
  39661. }
  39662. }
  39663. return byteArray;
  39664. };
  39665. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39666. var byteArray = new Uint8Array(dataLength);
  39667. var srcData = new Uint8Array(arrayBuffer);
  39668. var index = 0;
  39669. for (var y = height - 1; y >= 0; y--) {
  39670. for (var x = 0; x < width; x++) {
  39671. var srcPos = dataOffset + (x + y * width) * 3;
  39672. byteArray[index + 2] = srcData[srcPos];
  39673. byteArray[index + 1] = srcData[srcPos + 1];
  39674. byteArray[index] = srcData[srcPos + 2];
  39675. index += 3;
  39676. }
  39677. }
  39678. return byteArray;
  39679. };
  39680. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  39681. var byteArray = new Uint8Array(dataLength);
  39682. var srcData = new Uint8Array(arrayBuffer);
  39683. var index = 0;
  39684. for (var y = height - 1; y >= 0; y--) {
  39685. for (var x = 0; x < width; x++) {
  39686. var srcPos = dataOffset + (x + y * width);
  39687. byteArray[index] = srcData[srcPos];
  39688. index++;
  39689. }
  39690. }
  39691. return byteArray;
  39692. };
  39693. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  39694. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  39695. if (header[off_magic] != DDS_MAGIC) {
  39696. BABYLON.Tools.Error("Invalid magic number in DDS header");
  39697. return;
  39698. }
  39699. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  39700. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  39701. return;
  39702. }
  39703. if (info.isFourCC) {
  39704. fourCC = header[off_pfFourCC];
  39705. switch (fourCC) {
  39706. case FOURCC_DXT1:
  39707. blockBytes = 8;
  39708. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  39709. break;
  39710. case FOURCC_DXT3:
  39711. blockBytes = 16;
  39712. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  39713. break;
  39714. case FOURCC_DXT5:
  39715. blockBytes = 16;
  39716. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  39717. break;
  39718. default:
  39719. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  39720. return;
  39721. }
  39722. }
  39723. mipmapCount = 1;
  39724. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  39725. mipmapCount = Math.max(1, header[off_mipmapCount]);
  39726. }
  39727. var bpp = header[off_RGBbpp];
  39728. for (var face = 0; face < faces; face++) {
  39729. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  39730. width = header[off_width];
  39731. height = header[off_height];
  39732. dataOffset = header[off_size] + 4;
  39733. for (i = 0; i < mipmapCount; ++i) {
  39734. if (info.isRGB) {
  39735. if (bpp === 24) {
  39736. dataLength = width * height * 3;
  39737. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39738. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  39739. }
  39740. else {
  39741. dataLength = width * height * 4;
  39742. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39743. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  39744. }
  39745. }
  39746. else if (info.isLuminance) {
  39747. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  39748. var unpaddedRowSize = width;
  39749. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  39750. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  39751. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  39752. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  39753. }
  39754. else {
  39755. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  39756. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  39757. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  39758. }
  39759. dataOffset += dataLength;
  39760. width *= 0.5;
  39761. height *= 0.5;
  39762. width = Math.max(1.0, width);
  39763. height = Math.max(1.0, height);
  39764. }
  39765. }
  39766. };
  39767. return DDSTools;
  39768. }());
  39769. Internals.DDSTools = DDSTools;
  39770. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  39771. })(BABYLON || (BABYLON = {}));
  39772. var BABYLON;
  39773. (function (BABYLON) {
  39774. var CannonJSPlugin = (function () {
  39775. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  39776. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  39777. if (iterations === void 0) { iterations = 10; }
  39778. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  39779. this.name = "CannonJSPlugin";
  39780. this._physicsMaterials = [];
  39781. this._fixedTimeStep = 1 / 60;
  39782. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  39783. this._currentCollisionGroup = 2;
  39784. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  39785. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  39786. this._tmpPosition = BABYLON.Vector3.Zero();
  39787. this._tmpQuaternion = new BABYLON.Quaternion();
  39788. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  39789. this._tmpDeltaRotation = new BABYLON.Quaternion();
  39790. this._tmpUnityRotation = new BABYLON.Quaternion();
  39791. if (!this.isSupported()) {
  39792. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  39793. return;
  39794. }
  39795. this.world = new CANNON.World();
  39796. this.world.broadphase = new CANNON.NaiveBroadphase();
  39797. this.world.solver.iterations = iterations;
  39798. }
  39799. CannonJSPlugin.prototype.setGravity = function (gravity) {
  39800. this.world.gravity.copy(gravity);
  39801. };
  39802. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  39803. this._fixedTimeStep = timeStep;
  39804. };
  39805. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  39806. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  39807. };
  39808. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  39809. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  39810. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  39811. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  39812. };
  39813. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  39814. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  39815. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  39816. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  39817. };
  39818. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  39819. //parent-child relationship. Does this impostor has a parent impostor?
  39820. if (impostor.parent) {
  39821. if (impostor.physicsBody) {
  39822. this.removePhysicsBody(impostor);
  39823. //TODO is that needed?
  39824. impostor.forceUpdate();
  39825. }
  39826. return;
  39827. }
  39828. //should a new body be created for this impostor?
  39829. if (impostor.isBodyInitRequired()) {
  39830. var shape = this._createShape(impostor);
  39831. //unregister events, if body is being changed
  39832. var oldBody = impostor.physicsBody;
  39833. if (oldBody) {
  39834. this.removePhysicsBody(impostor);
  39835. }
  39836. //create the body and material
  39837. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  39838. var bodyCreationObject = {
  39839. mass: impostor.getParam("mass"),
  39840. material: material
  39841. };
  39842. // A simple extend, in case native options were used.
  39843. var nativeOptions = impostor.getParam("nativeOptions");
  39844. for (var key in nativeOptions) {
  39845. if (nativeOptions.hasOwnProperty(key)) {
  39846. bodyCreationObject[key] = nativeOptions[key];
  39847. }
  39848. }
  39849. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  39850. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  39851. this.world.addEventListener("preStep", impostor.beforeStep);
  39852. this.world.addEventListener("postStep", impostor.afterStep);
  39853. impostor.physicsBody.addShape(shape);
  39854. this.world.add(impostor.physicsBody);
  39855. //try to keep the body moving in the right direction by taking old properties.
  39856. //Should be tested!
  39857. if (oldBody) {
  39858. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  39859. impostor.physicsBody[param].copy(oldBody[param]);
  39860. });
  39861. }
  39862. this._processChildMeshes(impostor);
  39863. }
  39864. //now update the body's transformation
  39865. this._updatePhysicsBodyTransformation(impostor);
  39866. };
  39867. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  39868. var _this = this;
  39869. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  39870. if (meshChildren.length) {
  39871. var processMesh = function (localPosition, mesh) {
  39872. var childImpostor = mesh.getPhysicsImpostor();
  39873. if (childImpostor) {
  39874. var parent = childImpostor.parent;
  39875. if (parent !== mainImpostor) {
  39876. var localPosition = mesh.position;
  39877. if (childImpostor.physicsBody) {
  39878. _this.removePhysicsBody(childImpostor);
  39879. childImpostor.physicsBody = null;
  39880. }
  39881. childImpostor.parent = mainImpostor;
  39882. childImpostor.resetUpdateFlags();
  39883. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  39884. //Add the mass of the children.
  39885. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  39886. }
  39887. }
  39888. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  39889. };
  39890. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  39891. }
  39892. };
  39893. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  39894. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  39895. this.world.removeEventListener("preStep", impostor.beforeStep);
  39896. this.world.removeEventListener("postStep", impostor.afterStep);
  39897. this.world.remove(impostor.physicsBody);
  39898. };
  39899. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  39900. var mainBody = impostorJoint.mainImpostor.physicsBody;
  39901. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  39902. if (!mainBody || !connectedBody) {
  39903. return;
  39904. }
  39905. var constraint;
  39906. var jointData = impostorJoint.joint.jointData;
  39907. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  39908. var constraintData = {
  39909. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  39910. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  39911. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  39912. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  39913. maxForce: jointData.nativeParams.maxForce,
  39914. collideConnected: !!jointData.collision
  39915. };
  39916. //Not needed, Cannon has a collideConnected flag
  39917. /*if (!jointData.collision) {
  39918. //add 1st body to a collision group of its own, if it is not in 1
  39919. if (mainBody.collisionFilterGroup === 1) {
  39920. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  39921. this._currentCollisionGroup <<= 1;
  39922. }
  39923. if (connectedBody.collisionFilterGroup === 1) {
  39924. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  39925. this._currentCollisionGroup <<= 1;
  39926. }
  39927. //add their mask to the collisionFilterMask of each other:
  39928. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  39929. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  39930. }*/
  39931. switch (impostorJoint.joint.type) {
  39932. case BABYLON.PhysicsJoint.HingeJoint:
  39933. case BABYLON.PhysicsJoint.Hinge2Joint:
  39934. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  39935. break;
  39936. case BABYLON.PhysicsJoint.DistanceJoint:
  39937. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  39938. break;
  39939. case BABYLON.PhysicsJoint.SpringJoint:
  39940. var springData = jointData;
  39941. constraint = new CANNON.Spring(mainBody, connectedBody, {
  39942. restLength: springData.length,
  39943. stiffness: springData.stiffness,
  39944. damping: springData.damping,
  39945. localAnchorA: constraintData.pivotA,
  39946. localAnchorB: constraintData.pivotB
  39947. });
  39948. break;
  39949. case BABYLON.PhysicsJoint.LockJoint:
  39950. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  39951. break;
  39952. case BABYLON.PhysicsJoint.PointToPointJoint:
  39953. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  39954. default:
  39955. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  39956. break;
  39957. }
  39958. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  39959. constraint.collideConnected = !!jointData.collision;
  39960. impostorJoint.joint.physicsJoint = constraint;
  39961. //don't add spring as constraint, as it is not one.
  39962. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  39963. this.world.addConstraint(constraint);
  39964. }
  39965. else {
  39966. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  39967. constraint.applyForce();
  39968. });
  39969. }
  39970. };
  39971. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  39972. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  39973. };
  39974. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  39975. var index;
  39976. var mat;
  39977. for (index = 0; index < this._physicsMaterials.length; index++) {
  39978. mat = this._physicsMaterials[index];
  39979. if (mat.friction === friction && mat.restitution === restitution) {
  39980. return mat;
  39981. }
  39982. }
  39983. var currentMat = new CANNON.Material(name);
  39984. currentMat.friction = friction;
  39985. currentMat.restitution = restitution;
  39986. this._physicsMaterials.push(currentMat);
  39987. return currentMat;
  39988. };
  39989. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  39990. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  39991. };
  39992. CannonJSPlugin.prototype._createShape = function (impostor) {
  39993. var object = impostor.object;
  39994. var returnValue;
  39995. var extendSize = impostor.getObjectExtendSize();
  39996. switch (impostor.type) {
  39997. case BABYLON.PhysicsEngine.SphereImpostor:
  39998. var radiusX = extendSize.x;
  39999. var radiusY = extendSize.y;
  40000. var radiusZ = extendSize.z;
  40001. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  40002. break;
  40003. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  40004. case BABYLON.PhysicsImpostor.CylinderImpostor:
  40005. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  40006. break;
  40007. case BABYLON.PhysicsImpostor.BoxImpostor:
  40008. var box = extendSize.scale(0.5);
  40009. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  40010. break;
  40011. case BABYLON.PhysicsImpostor.PlaneImpostor:
  40012. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  40013. returnValue = new CANNON.Plane();
  40014. break;
  40015. case BABYLON.PhysicsImpostor.MeshImpostor:
  40016. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  40017. var rawFaces = object.getIndices ? object.getIndices() : [];
  40018. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  40019. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  40020. break;
  40021. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  40022. returnValue = this._createHeightmap(object);
  40023. break;
  40024. case BABYLON.PhysicsImpostor.ParticleImpostor:
  40025. returnValue = new CANNON.Particle();
  40026. break;
  40027. }
  40028. return returnValue;
  40029. };
  40030. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  40031. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40032. var matrix = [];
  40033. //For now pointDepth will not be used and will be automatically calculated.
  40034. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  40035. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  40036. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  40037. var elementSize = dim * 2 / arraySize;
  40038. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  40039. for (var i = 0; i < pos.length; i = i + 3) {
  40040. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  40041. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  40042. var y = pos[i + 1] + minY;
  40043. if (!matrix[x]) {
  40044. matrix[x] = [];
  40045. }
  40046. if (!matrix[x][z]) {
  40047. matrix[x][z] = y;
  40048. }
  40049. matrix[x][z] = Math.max(y, matrix[x][z]);
  40050. }
  40051. for (var x = 0; x <= arraySize; ++x) {
  40052. if (!matrix[x]) {
  40053. var loc = 1;
  40054. while (!matrix[(x + loc) % arraySize]) {
  40055. loc++;
  40056. }
  40057. matrix[x] = matrix[(x + loc) % arraySize].slice();
  40058. }
  40059. for (var z = 0; z <= arraySize; ++z) {
  40060. if (!matrix[x][z]) {
  40061. var loc = 1;
  40062. var newValue;
  40063. while (newValue === undefined) {
  40064. newValue = matrix[x][(z + loc++) % arraySize];
  40065. }
  40066. matrix[x][z] = newValue;
  40067. }
  40068. }
  40069. }
  40070. var shape = new CANNON.Heightfield(matrix, {
  40071. elementSize: elementSize
  40072. });
  40073. //For future reference, needed for body transformation
  40074. shape.minY = minY;
  40075. return shape;
  40076. };
  40077. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  40078. var object = impostor.object;
  40079. //make sure it is updated...
  40080. object.computeWorldMatrix && object.computeWorldMatrix(true);
  40081. // The delta between the mesh position and the mesh bounding box center
  40082. var center = impostor.getObjectCenter();
  40083. var extendSize = impostor.getObjectExtendSize();
  40084. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  40085. this._tmpPosition.copyFrom(center);
  40086. var quaternion = object.rotationQuaternion;
  40087. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  40088. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  40089. //-90 DEG in X, precalculated
  40090. quaternion = quaternion.multiply(this._minus90X);
  40091. //Invert! (Precalculated, 90 deg in X)
  40092. //No need to clone. this will never change.
  40093. impostor.setDeltaRotation(this._plus90X);
  40094. }
  40095. //If it is a heightfield, if should be centered.
  40096. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  40097. var mesh = object;
  40098. //calculate the correct body position:
  40099. var rotationQuaternion = mesh.rotationQuaternion;
  40100. mesh.rotationQuaternion = this._tmpUnityRotation;
  40101. mesh.computeWorldMatrix(true);
  40102. //get original center with no rotation
  40103. var c = center.clone();
  40104. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  40105. //rotation is back
  40106. mesh.rotationQuaternion = rotationQuaternion;
  40107. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  40108. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  40109. mesh.setPivotMatrix(p);
  40110. mesh.computeWorldMatrix(true);
  40111. //calculate the translation
  40112. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  40113. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  40114. //add it inverted to the delta
  40115. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  40116. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  40117. mesh.setPivotMatrix(oldPivot);
  40118. mesh.computeWorldMatrix(true);
  40119. }
  40120. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  40121. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  40122. this._tmpPosition.copyFrom(object.position);
  40123. }
  40124. impostor.setDeltaPosition(this._tmpDeltaPosition);
  40125. //Now update the impostor object
  40126. impostor.physicsBody.position.copy(this._tmpPosition);
  40127. impostor.physicsBody.quaternion.copy(quaternion);
  40128. };
  40129. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  40130. impostor.object.position.copyFrom(impostor.physicsBody.position);
  40131. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  40132. };
  40133. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  40134. impostor.physicsBody.position.copy(newPosition);
  40135. impostor.physicsBody.quaternion.copy(newRotation);
  40136. };
  40137. CannonJSPlugin.prototype.isSupported = function () {
  40138. return window.CANNON !== undefined;
  40139. };
  40140. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  40141. impostor.physicsBody.velocity.copy(velocity);
  40142. };
  40143. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  40144. impostor.physicsBody.angularVelocity.copy(velocity);
  40145. };
  40146. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  40147. var v = impostor.physicsBody.velocity;
  40148. if (!v)
  40149. return null;
  40150. return new BABYLON.Vector3(v.x, v.y, v.z);
  40151. };
  40152. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  40153. var v = impostor.physicsBody.angularVelocity;
  40154. if (!v)
  40155. return null;
  40156. return new BABYLON.Vector3(v.x, v.y, v.z);
  40157. };
  40158. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  40159. impostor.physicsBody.mass = mass;
  40160. impostor.physicsBody.updateMassProperties();
  40161. };
  40162. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  40163. impostor.physicsBody.sleep();
  40164. };
  40165. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  40166. impostor.physicsBody.wakeUp();
  40167. };
  40168. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  40169. joint.physicsJoint.distance = maxDistance;
  40170. };
  40171. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  40172. if (!motorIndex) {
  40173. joint.physicsJoint.enableMotor();
  40174. }
  40175. };
  40176. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  40177. if (!motorIndex) {
  40178. joint.physicsJoint.disableMotor();
  40179. }
  40180. };
  40181. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  40182. if (!motorIndex) {
  40183. joint.physicsJoint.enableMotor();
  40184. joint.physicsJoint.setMotorSpeed(speed);
  40185. if (maxForce) {
  40186. this.setLimit(joint, maxForce);
  40187. }
  40188. }
  40189. };
  40190. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  40191. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  40192. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  40193. };
  40194. CannonJSPlugin.prototype.dispose = function () {
  40195. //nothing to do, actually.
  40196. };
  40197. return CannonJSPlugin;
  40198. }());
  40199. BABYLON.CannonJSPlugin = CannonJSPlugin;
  40200. })(BABYLON || (BABYLON = {}));
  40201. var BABYLON;
  40202. (function (BABYLON) {
  40203. var OimoJSPlugin = (function () {
  40204. function OimoJSPlugin(iterations) {
  40205. this.name = "OimoJSPlugin";
  40206. this._tmpImpostorsArray = [];
  40207. this._tmpPositionVector = BABYLON.Vector3.Zero();
  40208. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  40209. this.world.worldscale(1);
  40210. this.world.clear();
  40211. //making sure no stats are calculated
  40212. this.world.isNoStat = true;
  40213. }
  40214. OimoJSPlugin.prototype.setGravity = function (gravity) {
  40215. this.world.gravity.copy(gravity);
  40216. };
  40217. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  40218. this.world.timeStep = timeStep;
  40219. };
  40220. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  40221. var _this = this;
  40222. impostors.forEach(function (impostor) {
  40223. impostor.beforeStep();
  40224. });
  40225. this.world.step();
  40226. impostors.forEach(function (impostor) {
  40227. impostor.afterStep();
  40228. //update the ordered impostors array
  40229. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  40230. });
  40231. //check for collisions
  40232. var contact = this.world.contacts;
  40233. while (contact !== null) {
  40234. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  40235. contact = contact.next;
  40236. continue;
  40237. }
  40238. //is this body colliding with any other? get the impostor
  40239. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  40240. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  40241. if (!mainImpostor || !collidingImpostor) {
  40242. contact = contact.next;
  40243. continue;
  40244. }
  40245. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  40246. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  40247. contact = contact.next;
  40248. }
  40249. };
  40250. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  40251. var mass = impostor.physicsBody.massInfo.mass;
  40252. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  40253. };
  40254. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  40255. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  40256. this.applyImpulse(impostor, force, contactPoint);
  40257. };
  40258. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  40259. var _this = this;
  40260. //parent-child relationship. Does this impostor has a parent impostor?
  40261. if (impostor.parent) {
  40262. if (impostor.physicsBody) {
  40263. this.removePhysicsBody(impostor);
  40264. //TODO is that needed?
  40265. impostor.forceUpdate();
  40266. }
  40267. return;
  40268. }
  40269. if (impostor.isBodyInitRequired()) {
  40270. var bodyConfig = {
  40271. name: impostor.uniqueId,
  40272. //Oimo must have mass, also for static objects.
  40273. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  40274. size: [],
  40275. type: [],
  40276. pos: [],
  40277. rot: [],
  40278. move: impostor.getParam("mass") !== 0,
  40279. //Supporting older versions of Oimo
  40280. world: this.world
  40281. };
  40282. var impostors = [impostor];
  40283. var addToArray = function (parent) {
  40284. if (!parent.getChildMeshes)
  40285. return;
  40286. parent.getChildMeshes().forEach(function (m) {
  40287. if (m.physicsImpostor) {
  40288. impostors.push(m.physicsImpostor);
  40289. m.physicsImpostor._init();
  40290. }
  40291. });
  40292. };
  40293. addToArray(impostor.object);
  40294. var checkWithEpsilon_1 = function (value) {
  40295. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  40296. };
  40297. impostors.forEach(function (i) {
  40298. //get the correct bounding box
  40299. var oldQuaternion = i.object.rotationQuaternion;
  40300. var rot = new OIMO.Euler().setFromQuaternion({
  40301. x: impostor.object.rotationQuaternion.x,
  40302. y: impostor.object.rotationQuaternion.y,
  40303. z: impostor.object.rotationQuaternion.z,
  40304. s: impostor.object.rotationQuaternion.w
  40305. });
  40306. var extendSize = i.getObjectExtendSize();
  40307. if (i === impostor) {
  40308. var center = impostor.getObjectCenter();
  40309. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  40310. //Can also use Array.prototype.push.apply
  40311. bodyConfig.pos.push(center.x);
  40312. bodyConfig.pos.push(center.y);
  40313. bodyConfig.pos.push(center.z);
  40314. //tmp solution
  40315. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  40316. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  40317. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  40318. }
  40319. else {
  40320. bodyConfig.pos.push(i.object.position.x);
  40321. bodyConfig.pos.push(i.object.position.y);
  40322. bodyConfig.pos.push(i.object.position.z);
  40323. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  40324. bodyConfig.rot.push(0);
  40325. bodyConfig.rot.push(0);
  40326. bodyConfig.rot.push(0);
  40327. }
  40328. // register mesh
  40329. switch (i.type) {
  40330. case BABYLON.PhysicsImpostor.ParticleImpostor:
  40331. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  40332. case BABYLON.PhysicsImpostor.SphereImpostor:
  40333. var radiusX = extendSize.x;
  40334. var radiusY = extendSize.y;
  40335. var radiusZ = extendSize.z;
  40336. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  40337. bodyConfig.type.push('sphere');
  40338. //due to the way oimo works with compounds, add 3 times
  40339. bodyConfig.size.push(size);
  40340. bodyConfig.size.push(size);
  40341. bodyConfig.size.push(size);
  40342. break;
  40343. case BABYLON.PhysicsImpostor.CylinderImpostor:
  40344. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  40345. var sizeY = checkWithEpsilon_1(extendSize.y);
  40346. bodyConfig.type.push('cylinder');
  40347. bodyConfig.size.push(sizeX);
  40348. bodyConfig.size.push(sizeY);
  40349. //due to the way oimo works with compounds, add one more value.
  40350. bodyConfig.size.push(sizeY);
  40351. break;
  40352. case BABYLON.PhysicsImpostor.PlaneImpostor:
  40353. case BABYLON.PhysicsImpostor.BoxImpostor:
  40354. default:
  40355. var sizeX = checkWithEpsilon_1(extendSize.x);
  40356. var sizeY = checkWithEpsilon_1(extendSize.y);
  40357. var sizeZ = checkWithEpsilon_1(extendSize.z);
  40358. bodyConfig.type.push('box');
  40359. bodyConfig.size.push(sizeX);
  40360. bodyConfig.size.push(sizeY);
  40361. bodyConfig.size.push(sizeZ);
  40362. break;
  40363. }
  40364. //actually not needed, but hey...
  40365. i.object.rotationQuaternion = oldQuaternion;
  40366. });
  40367. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  40368. }
  40369. else {
  40370. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  40371. }
  40372. impostor.setDeltaPosition(this._tmpPositionVector);
  40373. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  40374. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  40375. };
  40376. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  40377. //impostor.physicsBody.dispose();
  40378. //Same as : (older oimo versions)
  40379. this.world.removeRigidBody(impostor.physicsBody);
  40380. };
  40381. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  40382. var mainBody = impostorJoint.mainImpostor.physicsBody;
  40383. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  40384. if (!mainBody || !connectedBody) {
  40385. return;
  40386. }
  40387. var jointData = impostorJoint.joint.jointData;
  40388. var options = jointData.nativeParams || {};
  40389. var type;
  40390. var nativeJointData = {
  40391. body1: mainBody,
  40392. body2: connectedBody,
  40393. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  40394. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  40395. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  40396. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  40397. min: options.min,
  40398. max: options.max,
  40399. collision: options.collision || jointData.collision,
  40400. spring: options.spring,
  40401. //supporting older version of Oimo
  40402. world: this.world
  40403. };
  40404. switch (impostorJoint.joint.type) {
  40405. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  40406. type = "jointBall";
  40407. break;
  40408. case BABYLON.PhysicsJoint.SpringJoint:
  40409. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  40410. var springData = jointData;
  40411. nativeJointData.min = springData.length || nativeJointData.min;
  40412. //Max should also be set, just make sure it is at least min
  40413. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  40414. case BABYLON.PhysicsJoint.DistanceJoint:
  40415. type = "jointDistance";
  40416. nativeJointData.max = jointData.maxDistance;
  40417. break;
  40418. case BABYLON.PhysicsJoint.PrismaticJoint:
  40419. type = "jointPrisme";
  40420. break;
  40421. case BABYLON.PhysicsJoint.SliderJoint:
  40422. type = "jointSlide";
  40423. break;
  40424. case BABYLON.PhysicsJoint.WheelJoint:
  40425. type = "jointWheel";
  40426. break;
  40427. case BABYLON.PhysicsJoint.HingeJoint:
  40428. default:
  40429. type = "jointHinge";
  40430. break;
  40431. }
  40432. nativeJointData.type = type;
  40433. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  40434. };
  40435. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  40436. //Bug in Oimo prevents us from disposing a joint in the playground
  40437. //joint.joint.physicsJoint.dispose();
  40438. //So we will bruteforce it!
  40439. try {
  40440. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  40441. }
  40442. catch (e) {
  40443. BABYLON.Tools.Warn(e);
  40444. }
  40445. };
  40446. OimoJSPlugin.prototype.isSupported = function () {
  40447. return OIMO !== undefined;
  40448. };
  40449. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  40450. if (!impostor.physicsBody.sleeping) {
  40451. //TODO check that
  40452. if (impostor.physicsBody.shapes.next) {
  40453. var parentShape = this._getLastShape(impostor.physicsBody);
  40454. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  40455. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  40456. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  40457. }
  40458. else {
  40459. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  40460. }
  40461. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  40462. impostor.object.rotationQuaternion.normalize();
  40463. }
  40464. };
  40465. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  40466. var body = impostor.physicsBody;
  40467. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  40468. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  40469. body.syncShapes();
  40470. body.awake();
  40471. };
  40472. OimoJSPlugin.prototype._getLastShape = function (body) {
  40473. var lastShape = body.shapes;
  40474. while (lastShape.next) {
  40475. lastShape = lastShape.next;
  40476. }
  40477. return lastShape;
  40478. };
  40479. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  40480. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  40481. };
  40482. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  40483. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  40484. };
  40485. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  40486. var v = impostor.physicsBody.linearVelocity;
  40487. if (!v)
  40488. return null;
  40489. return new BABYLON.Vector3(v.x, v.y, v.z);
  40490. };
  40491. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  40492. var v = impostor.physicsBody.angularVelocity;
  40493. if (!v)
  40494. return null;
  40495. return new BABYLON.Vector3(v.x, v.y, v.z);
  40496. };
  40497. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  40498. var staticBody = mass === 0;
  40499. //this will actually set the body's density and not its mass.
  40500. //But this is how oimo treats the mass variable.
  40501. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  40502. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  40503. };
  40504. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  40505. impostor.physicsBody.sleep();
  40506. };
  40507. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  40508. impostor.physicsBody.awake();
  40509. };
  40510. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  40511. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  40512. if (minDistance !== void 0) {
  40513. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  40514. }
  40515. };
  40516. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  40517. //TODO separate rotational and transational motors.
  40518. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  40519. if (motor) {
  40520. motor.setMotor(speed, maxForce);
  40521. }
  40522. };
  40523. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  40524. //TODO separate rotational and transational motors.
  40525. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  40526. if (motor) {
  40527. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  40528. }
  40529. };
  40530. OimoJSPlugin.prototype.dispose = function () {
  40531. this.world.clear();
  40532. };
  40533. return OimoJSPlugin;
  40534. }());
  40535. BABYLON.OimoJSPlugin = OimoJSPlugin;
  40536. })(BABYLON || (BABYLON = {}));
  40537. var BABYLON;
  40538. (function (BABYLON) {
  40539. var DisplayPassPostProcess = (function (_super) {
  40540. __extends(DisplayPassPostProcess, _super);
  40541. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  40542. _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable);
  40543. }
  40544. return DisplayPassPostProcess;
  40545. }(BABYLON.PostProcess));
  40546. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  40547. })(BABYLON || (BABYLON = {}));
  40548. var BABYLON;
  40549. (function (BABYLON) {
  40550. var SimplificationSettings = (function () {
  40551. function SimplificationSettings(quality, distance, optimizeMesh) {
  40552. this.quality = quality;
  40553. this.distance = distance;
  40554. this.optimizeMesh = optimizeMesh;
  40555. }
  40556. return SimplificationSettings;
  40557. }());
  40558. BABYLON.SimplificationSettings = SimplificationSettings;
  40559. var SimplificationQueue = (function () {
  40560. function SimplificationQueue() {
  40561. this.running = false;
  40562. this._simplificationArray = [];
  40563. }
  40564. SimplificationQueue.prototype.addTask = function (task) {
  40565. this._simplificationArray.push(task);
  40566. };
  40567. SimplificationQueue.prototype.executeNext = function () {
  40568. var task = this._simplificationArray.pop();
  40569. if (task) {
  40570. this.running = true;
  40571. this.runSimplification(task);
  40572. }
  40573. else {
  40574. this.running = false;
  40575. }
  40576. };
  40577. SimplificationQueue.prototype.runSimplification = function (task) {
  40578. var _this = this;
  40579. if (task.parallelProcessing) {
  40580. //parallel simplifier
  40581. task.settings.forEach(function (setting) {
  40582. var simplifier = _this.getSimplifier(task);
  40583. simplifier.simplify(setting, function (newMesh) {
  40584. task.mesh.addLODLevel(setting.distance, newMesh);
  40585. newMesh.isVisible = true;
  40586. //check if it is the last
  40587. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  40588. //all done, run the success callback.
  40589. task.successCallback();
  40590. }
  40591. _this.executeNext();
  40592. });
  40593. });
  40594. }
  40595. else {
  40596. //single simplifier.
  40597. var simplifier = this.getSimplifier(task);
  40598. var runDecimation = function (setting, callback) {
  40599. simplifier.simplify(setting, function (newMesh) {
  40600. task.mesh.addLODLevel(setting.distance, newMesh);
  40601. newMesh.isVisible = true;
  40602. //run the next quality level
  40603. callback();
  40604. });
  40605. };
  40606. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  40607. runDecimation(task.settings[loop.index], function () {
  40608. loop.executeNext();
  40609. });
  40610. }, function () {
  40611. //execution ended, run the success callback.
  40612. if (task.successCallback) {
  40613. task.successCallback();
  40614. }
  40615. _this.executeNext();
  40616. });
  40617. }
  40618. };
  40619. SimplificationQueue.prototype.getSimplifier = function (task) {
  40620. switch (task.simplificationType) {
  40621. case SimplificationType.QUADRATIC:
  40622. default:
  40623. return new QuadraticErrorSimplification(task.mesh);
  40624. }
  40625. };
  40626. return SimplificationQueue;
  40627. }());
  40628. BABYLON.SimplificationQueue = SimplificationQueue;
  40629. /**
  40630. * The implemented types of simplification.
  40631. * At the moment only Quadratic Error Decimation is implemented.
  40632. */
  40633. (function (SimplificationType) {
  40634. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  40635. })(BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  40636. var SimplificationType = BABYLON.SimplificationType;
  40637. var DecimationTriangle = (function () {
  40638. function DecimationTriangle(vertices) {
  40639. this.vertices = vertices;
  40640. this.error = new Array(4);
  40641. this.deleted = false;
  40642. this.isDirty = false;
  40643. this.deletePending = false;
  40644. this.borderFactor = 0;
  40645. }
  40646. return DecimationTriangle;
  40647. }());
  40648. BABYLON.DecimationTriangle = DecimationTriangle;
  40649. var DecimationVertex = (function () {
  40650. function DecimationVertex(position, id) {
  40651. this.position = position;
  40652. this.id = id;
  40653. this.isBorder = true;
  40654. this.q = new QuadraticMatrix();
  40655. this.triangleCount = 0;
  40656. this.triangleStart = 0;
  40657. this.originalOffsets = [];
  40658. }
  40659. DecimationVertex.prototype.updatePosition = function (newPosition) {
  40660. this.position.copyFrom(newPosition);
  40661. };
  40662. return DecimationVertex;
  40663. }());
  40664. BABYLON.DecimationVertex = DecimationVertex;
  40665. var QuadraticMatrix = (function () {
  40666. function QuadraticMatrix(data) {
  40667. this.data = new Array(10);
  40668. for (var i = 0; i < 10; ++i) {
  40669. if (data && data[i]) {
  40670. this.data[i] = data[i];
  40671. }
  40672. else {
  40673. this.data[i] = 0;
  40674. }
  40675. }
  40676. }
  40677. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  40678. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  40679. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  40680. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  40681. return det;
  40682. };
  40683. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  40684. for (var i = 0; i < 10; ++i) {
  40685. this.data[i] += matrix.data[i];
  40686. }
  40687. };
  40688. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  40689. for (var i = 0; i < 10; ++i) {
  40690. this.data[i] += data[i];
  40691. }
  40692. };
  40693. QuadraticMatrix.prototype.add = function (matrix) {
  40694. var m = new QuadraticMatrix();
  40695. for (var i = 0; i < 10; ++i) {
  40696. m.data[i] = this.data[i] + matrix.data[i];
  40697. }
  40698. return m;
  40699. };
  40700. QuadraticMatrix.FromData = function (a, b, c, d) {
  40701. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  40702. };
  40703. //returning an array to avoid garbage collection
  40704. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  40705. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  40706. };
  40707. return QuadraticMatrix;
  40708. }());
  40709. BABYLON.QuadraticMatrix = QuadraticMatrix;
  40710. var Reference = (function () {
  40711. function Reference(vertexId, triangleId) {
  40712. this.vertexId = vertexId;
  40713. this.triangleId = triangleId;
  40714. }
  40715. return Reference;
  40716. }());
  40717. BABYLON.Reference = Reference;
  40718. /**
  40719. * An implementation of the Quadratic Error simplification algorithm.
  40720. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  40721. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  40722. * @author RaananW
  40723. */
  40724. var QuadraticErrorSimplification = (function () {
  40725. function QuadraticErrorSimplification(_mesh) {
  40726. this._mesh = _mesh;
  40727. this.initialized = false;
  40728. this.syncIterations = 5000;
  40729. this.aggressiveness = 7;
  40730. this.decimationIterations = 100;
  40731. this.boundingBoxEpsilon = BABYLON.Epsilon;
  40732. }
  40733. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  40734. var _this = this;
  40735. this.initDecimatedMesh();
  40736. //iterating through the submeshes array, one after the other.
  40737. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  40738. _this.initWithMesh(loop.index, function () {
  40739. _this.runDecimation(settings, loop.index, function () {
  40740. loop.executeNext();
  40741. });
  40742. }, settings.optimizeMesh);
  40743. }, function () {
  40744. setTimeout(function () {
  40745. successCallback(_this._reconstructedMesh);
  40746. }, 0);
  40747. });
  40748. };
  40749. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  40750. var _this = this;
  40751. var gCount = 0;
  40752. triangle.vertices.forEach(function (vertex) {
  40753. var count = 0;
  40754. var vPos = vertex.position;
  40755. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  40756. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  40757. ++count;
  40758. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  40759. ++count;
  40760. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  40761. ++count;
  40762. if (count > 1) {
  40763. ++gCount;
  40764. }
  40765. ;
  40766. });
  40767. if (gCount > 1) {
  40768. console.log(triangle, gCount);
  40769. }
  40770. return gCount > 1;
  40771. };
  40772. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  40773. var _this = this;
  40774. var targetCount = ~~(this.triangles.length * settings.quality);
  40775. var deletedTriangles = 0;
  40776. var triangleCount = this.triangles.length;
  40777. var iterationFunction = function (iteration, callback) {
  40778. setTimeout(function () {
  40779. if (iteration % 5 === 0) {
  40780. _this.updateMesh(iteration === 0);
  40781. }
  40782. for (var i = 0; i < _this.triangles.length; ++i) {
  40783. _this.triangles[i].isDirty = false;
  40784. }
  40785. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  40786. var trianglesIterator = function (i) {
  40787. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  40788. var t = _this.triangles[tIdx];
  40789. if (!t)
  40790. return;
  40791. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  40792. return;
  40793. }
  40794. for (var j = 0; j < 3; ++j) {
  40795. if (t.error[j] < threshold) {
  40796. var deleted0 = [];
  40797. var deleted1 = [];
  40798. var v0 = t.vertices[j];
  40799. var v1 = t.vertices[(j + 1) % 3];
  40800. if (v0.isBorder || v1.isBorder)
  40801. continue;
  40802. var p = BABYLON.Vector3.Zero();
  40803. var n = BABYLON.Vector3.Zero();
  40804. var uv = BABYLON.Vector2.Zero();
  40805. var color = new BABYLON.Color4(0, 0, 0, 1);
  40806. _this.calculateError(v0, v1, p, n, uv, color);
  40807. var delTr = [];
  40808. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  40809. continue;
  40810. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  40811. continue;
  40812. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  40813. continue;
  40814. var uniqueArray = [];
  40815. delTr.forEach(function (deletedT) {
  40816. if (uniqueArray.indexOf(deletedT) === -1) {
  40817. deletedT.deletePending = true;
  40818. uniqueArray.push(deletedT);
  40819. }
  40820. });
  40821. if (uniqueArray.length % 2 !== 0) {
  40822. continue;
  40823. }
  40824. v0.q = v1.q.add(v0.q);
  40825. v0.updatePosition(p);
  40826. var tStart = _this.references.length;
  40827. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  40828. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  40829. var tCount = _this.references.length - tStart;
  40830. if (tCount <= v0.triangleCount) {
  40831. if (tCount) {
  40832. for (var c = 0; c < tCount; c++) {
  40833. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  40834. }
  40835. }
  40836. }
  40837. else {
  40838. v0.triangleStart = tStart;
  40839. }
  40840. v0.triangleCount = tCount;
  40841. break;
  40842. }
  40843. }
  40844. };
  40845. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  40846. }, 0);
  40847. };
  40848. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  40849. if (triangleCount - deletedTriangles <= targetCount)
  40850. loop.breakLoop();
  40851. else {
  40852. iterationFunction(loop.index, function () {
  40853. loop.executeNext();
  40854. });
  40855. }
  40856. }, function () {
  40857. setTimeout(function () {
  40858. //reconstruct this part of the mesh
  40859. _this.reconstructMesh(submeshIndex);
  40860. successCallback();
  40861. }, 0);
  40862. });
  40863. };
  40864. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  40865. var _this = this;
  40866. this.vertices = [];
  40867. this.triangles = [];
  40868. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40869. var indices = this._mesh.getIndices();
  40870. var submesh = this._mesh.subMeshes[submeshIndex];
  40871. var findInVertices = function (positionToSearch) {
  40872. if (optimizeMesh) {
  40873. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  40874. if (_this.vertices[ii].position.equals(positionToSearch)) {
  40875. return _this.vertices[ii];
  40876. }
  40877. }
  40878. }
  40879. return null;
  40880. };
  40881. var vertexReferences = [];
  40882. var vertexInit = function (i) {
  40883. var offset = i + submesh.verticesStart;
  40884. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  40885. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  40886. vertex.originalOffsets.push(offset);
  40887. if (vertex.id === _this.vertices.length) {
  40888. _this.vertices.push(vertex);
  40889. }
  40890. vertexReferences.push(vertex.id);
  40891. };
  40892. //var totalVertices = mesh.getTotalVertices();
  40893. var totalVertices = submesh.verticesCount;
  40894. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  40895. var indicesInit = function (i) {
  40896. var offset = (submesh.indexStart / 3) + i;
  40897. var pos = (offset * 3);
  40898. var i0 = indices[pos + 0];
  40899. var i1 = indices[pos + 1];
  40900. var i2 = indices[pos + 2];
  40901. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  40902. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  40903. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  40904. var triangle = new DecimationTriangle([v0, v1, v2]);
  40905. triangle.originalOffset = pos;
  40906. _this.triangles.push(triangle);
  40907. };
  40908. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  40909. _this.init(callback);
  40910. });
  40911. });
  40912. };
  40913. QuadraticErrorSimplification.prototype.init = function (callback) {
  40914. var _this = this;
  40915. var triangleInit1 = function (i) {
  40916. var t = _this.triangles[i];
  40917. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  40918. for (var j = 0; j < 3; j++) {
  40919. 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))));
  40920. }
  40921. };
  40922. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  40923. var triangleInit2 = function (i) {
  40924. var t = _this.triangles[i];
  40925. for (var j = 0; j < 3; ++j) {
  40926. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  40927. }
  40928. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  40929. };
  40930. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  40931. _this.initialized = true;
  40932. callback();
  40933. });
  40934. });
  40935. };
  40936. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  40937. var newTriangles = [];
  40938. var i;
  40939. for (i = 0; i < this.vertices.length; ++i) {
  40940. this.vertices[i].triangleCount = 0;
  40941. }
  40942. var t;
  40943. var j;
  40944. for (i = 0; i < this.triangles.length; ++i) {
  40945. if (!this.triangles[i].deleted) {
  40946. t = this.triangles[i];
  40947. for (j = 0; j < 3; ++j) {
  40948. t.vertices[j].triangleCount = 1;
  40949. }
  40950. newTriangles.push(t);
  40951. }
  40952. }
  40953. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  40954. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  40955. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  40956. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  40957. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40958. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40959. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40960. var vertexCount = 0;
  40961. for (i = 0; i < this.vertices.length; ++i) {
  40962. var vertex = this.vertices[i];
  40963. vertex.id = vertexCount;
  40964. if (vertex.triangleCount) {
  40965. vertex.originalOffsets.forEach(function (originalOffset) {
  40966. newPositionData.push(vertex.position.x);
  40967. newPositionData.push(vertex.position.y);
  40968. newPositionData.push(vertex.position.z);
  40969. newNormalData.push(normalData[originalOffset * 3]);
  40970. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  40971. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  40972. if (uvs && uvs.length) {
  40973. newUVsData.push(uvs[(originalOffset * 2)]);
  40974. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  40975. }
  40976. else if (colorsData && colorsData.length) {
  40977. newColorsData.push(colorsData[(originalOffset * 4)]);
  40978. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  40979. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  40980. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  40981. }
  40982. ++vertexCount;
  40983. });
  40984. }
  40985. }
  40986. var startingIndex = this._reconstructedMesh.getTotalIndices();
  40987. var startingVertex = this._reconstructedMesh.getTotalVertices();
  40988. var submeshesArray = this._reconstructedMesh.subMeshes;
  40989. this._reconstructedMesh.subMeshes = [];
  40990. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  40991. var originalIndices = this._mesh.getIndices();
  40992. for (i = 0; i < newTriangles.length; ++i) {
  40993. t = newTriangles[i]; //now get the new referencing point for each vertex
  40994. [0, 1, 2].forEach(function (idx) {
  40995. var id = originalIndices[t.originalOffset + idx];
  40996. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  40997. if (offset < 0)
  40998. offset = 0;
  40999. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  41000. });
  41001. }
  41002. //overwriting the old vertex buffers and indices.
  41003. this._reconstructedMesh.setIndices(newIndicesArray);
  41004. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  41005. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  41006. if (newUVsData.length > 0)
  41007. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  41008. if (newColorsData.length > 0)
  41009. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  41010. //create submesh
  41011. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  41012. if (submeshIndex > 0) {
  41013. this._reconstructedMesh.subMeshes = [];
  41014. submeshesArray.forEach(function (submesh) {
  41015. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  41016. });
  41017. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  41018. }
  41019. };
  41020. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  41021. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  41022. this._reconstructedMesh.material = this._mesh.material;
  41023. this._reconstructedMesh.parent = this._mesh.parent;
  41024. this._reconstructedMesh.isVisible = false;
  41025. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  41026. };
  41027. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  41028. for (var i = 0; i < vertex1.triangleCount; ++i) {
  41029. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  41030. if (t.deleted)
  41031. continue;
  41032. var s = this.references[vertex1.triangleStart + i].vertexId;
  41033. var v1 = t.vertices[(s + 1) % 3];
  41034. var v2 = t.vertices[(s + 2) % 3];
  41035. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  41036. deletedArray[i] = true;
  41037. delTr.push(t);
  41038. continue;
  41039. }
  41040. var d1 = v1.position.subtract(point);
  41041. d1 = d1.normalize();
  41042. var d2 = v2.position.subtract(point);
  41043. d2 = d2.normalize();
  41044. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  41045. return true;
  41046. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  41047. deletedArray[i] = false;
  41048. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  41049. return true;
  41050. }
  41051. return false;
  41052. };
  41053. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  41054. var newDeleted = deletedTriangles;
  41055. for (var i = 0; i < vertex.triangleCount; ++i) {
  41056. var ref = this.references[vertex.triangleStart + i];
  41057. var t = this.triangles[ref.triangleId];
  41058. if (t.deleted)
  41059. continue;
  41060. if (deletedArray[i] && t.deletePending) {
  41061. t.deleted = true;
  41062. newDeleted++;
  41063. continue;
  41064. }
  41065. t.vertices[ref.vertexId] = origVertex;
  41066. t.isDirty = true;
  41067. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  41068. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  41069. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  41070. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  41071. this.references.push(ref);
  41072. }
  41073. return newDeleted;
  41074. };
  41075. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  41076. for (var i = 0; i < this.vertices.length; ++i) {
  41077. var vCount = [];
  41078. var vId = [];
  41079. var v = this.vertices[i];
  41080. var j;
  41081. for (j = 0; j < v.triangleCount; ++j) {
  41082. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  41083. for (var ii = 0; ii < 3; ii++) {
  41084. var ofs = 0;
  41085. var vv = triangle.vertices[ii];
  41086. while (ofs < vCount.length) {
  41087. if (vId[ofs] === vv.id)
  41088. break;
  41089. ++ofs;
  41090. }
  41091. if (ofs === vCount.length) {
  41092. vCount.push(1);
  41093. vId.push(vv.id);
  41094. }
  41095. else {
  41096. vCount[ofs]++;
  41097. }
  41098. }
  41099. }
  41100. for (j = 0; j < vCount.length; ++j) {
  41101. if (vCount[j] === 1) {
  41102. this.vertices[vId[j]].isBorder = true;
  41103. }
  41104. else {
  41105. this.vertices[vId[j]].isBorder = false;
  41106. }
  41107. }
  41108. }
  41109. };
  41110. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  41111. if (identifyBorders === void 0) { identifyBorders = false; }
  41112. var i;
  41113. if (!identifyBorders) {
  41114. var newTrianglesVector = [];
  41115. for (i = 0; i < this.triangles.length; ++i) {
  41116. if (!this.triangles[i].deleted) {
  41117. newTrianglesVector.push(this.triangles[i]);
  41118. }
  41119. }
  41120. this.triangles = newTrianglesVector;
  41121. }
  41122. for (i = 0; i < this.vertices.length; ++i) {
  41123. this.vertices[i].triangleCount = 0;
  41124. this.vertices[i].triangleStart = 0;
  41125. }
  41126. var t;
  41127. var j;
  41128. var v;
  41129. for (i = 0; i < this.triangles.length; ++i) {
  41130. t = this.triangles[i];
  41131. for (j = 0; j < 3; ++j) {
  41132. v = t.vertices[j];
  41133. v.triangleCount++;
  41134. }
  41135. }
  41136. var tStart = 0;
  41137. for (i = 0; i < this.vertices.length; ++i) {
  41138. this.vertices[i].triangleStart = tStart;
  41139. tStart += this.vertices[i].triangleCount;
  41140. this.vertices[i].triangleCount = 0;
  41141. }
  41142. var newReferences = new Array(this.triangles.length * 3);
  41143. for (i = 0; i < this.triangles.length; ++i) {
  41144. t = this.triangles[i];
  41145. for (j = 0; j < 3; ++j) {
  41146. v = t.vertices[j];
  41147. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  41148. v.triangleCount++;
  41149. }
  41150. }
  41151. this.references = newReferences;
  41152. if (identifyBorders) {
  41153. this.identifyBorder();
  41154. }
  41155. };
  41156. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  41157. var x = point.x;
  41158. var y = point.y;
  41159. var z = point.z;
  41160. 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
  41161. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  41162. };
  41163. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  41164. var q = vertex1.q.add(vertex2.q);
  41165. var border = vertex1.isBorder && vertex2.isBorder;
  41166. var error = 0;
  41167. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  41168. if (qDet !== 0 && !border) {
  41169. if (!pointResult) {
  41170. pointResult = BABYLON.Vector3.Zero();
  41171. }
  41172. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  41173. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  41174. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  41175. error = this.vertexError(q, pointResult);
  41176. }
  41177. else {
  41178. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  41179. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  41180. var error1 = this.vertexError(q, vertex1.position);
  41181. var error2 = this.vertexError(q, vertex2.position);
  41182. var error3 = this.vertexError(q, p3);
  41183. error = Math.min(error1, error2, error3);
  41184. if (error === error1) {
  41185. if (pointResult) {
  41186. pointResult.copyFrom(vertex1.position);
  41187. }
  41188. }
  41189. else if (error === error2) {
  41190. if (pointResult) {
  41191. pointResult.copyFrom(vertex2.position);
  41192. }
  41193. }
  41194. else {
  41195. if (pointResult) {
  41196. pointResult.copyFrom(p3);
  41197. }
  41198. }
  41199. }
  41200. return error;
  41201. };
  41202. return QuadraticErrorSimplification;
  41203. }());
  41204. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  41205. })(BABYLON || (BABYLON = {}));
  41206. var BABYLON;
  41207. (function (BABYLON) {
  41208. var serializedGeometries = [];
  41209. var serializeGeometry = function (geometry, serializationGeometries) {
  41210. if (serializedGeometries[geometry.id]) {
  41211. return;
  41212. }
  41213. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  41214. serializationGeometries.boxes.push(geometry.serialize());
  41215. }
  41216. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  41217. serializationGeometries.spheres.push(geometry.serialize());
  41218. }
  41219. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  41220. serializationGeometries.cylinders.push(geometry.serialize());
  41221. }
  41222. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  41223. serializationGeometries.toruses.push(geometry.serialize());
  41224. }
  41225. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  41226. serializationGeometries.grounds.push(geometry.serialize());
  41227. }
  41228. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  41229. serializationGeometries.planes.push(geometry.serialize());
  41230. }
  41231. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  41232. serializationGeometries.torusKnots.push(geometry.serialize());
  41233. }
  41234. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  41235. throw new Error("Unknown primitive type");
  41236. }
  41237. else {
  41238. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  41239. }
  41240. serializedGeometries[geometry.id] = true;
  41241. };
  41242. var serializeMesh = function (mesh, serializationScene) {
  41243. var serializationObject = {};
  41244. serializationObject.name = mesh.name;
  41245. serializationObject.id = mesh.id;
  41246. if (BABYLON.Tags.HasTags(mesh)) {
  41247. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  41248. }
  41249. serializationObject.position = mesh.position.asArray();
  41250. if (mesh.rotationQuaternion) {
  41251. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  41252. }
  41253. else if (mesh.rotation) {
  41254. serializationObject.rotation = mesh.rotation.asArray();
  41255. }
  41256. serializationObject.scaling = mesh.scaling.asArray();
  41257. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  41258. serializationObject.isEnabled = mesh.isEnabled();
  41259. serializationObject.isVisible = mesh.isVisible;
  41260. serializationObject.infiniteDistance = mesh.infiniteDistance;
  41261. serializationObject.pickable = mesh.isPickable;
  41262. serializationObject.receiveShadows = mesh.receiveShadows;
  41263. serializationObject.billboardMode = mesh.billboardMode;
  41264. serializationObject.visibility = mesh.visibility;
  41265. serializationObject.checkCollisions = mesh.checkCollisions;
  41266. // Parent
  41267. if (mesh.parent) {
  41268. serializationObject.parentId = mesh.parent.id;
  41269. }
  41270. // Geometry
  41271. var geometry = mesh._geometry;
  41272. if (geometry) {
  41273. var geometryId = geometry.id;
  41274. serializationObject.geometryId = geometryId;
  41275. if (!mesh.getScene().getGeometryByID(geometryId)) {
  41276. // 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
  41277. serializeGeometry(geometry, serializationScene.geometries);
  41278. }
  41279. // SubMeshes
  41280. serializationObject.subMeshes = [];
  41281. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  41282. var subMesh = mesh.subMeshes[subIndex];
  41283. serializationObject.subMeshes.push({
  41284. materialIndex: subMesh.materialIndex,
  41285. verticesStart: subMesh.verticesStart,
  41286. verticesCount: subMesh.verticesCount,
  41287. indexStart: subMesh.indexStart,
  41288. indexCount: subMesh.indexCount
  41289. });
  41290. }
  41291. }
  41292. // Material
  41293. if (mesh.material) {
  41294. serializationObject.materialId = mesh.material.id;
  41295. }
  41296. else {
  41297. mesh.material = null;
  41298. }
  41299. // Skeleton
  41300. if (mesh.skeleton) {
  41301. serializationObject.skeletonId = mesh.skeleton.id;
  41302. }
  41303. // Physics
  41304. //TODO implement correct serialization for physics impostors.
  41305. if (mesh.getPhysicsImpostor()) {
  41306. serializationObject.physicsMass = mesh.getPhysicsMass();
  41307. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  41308. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  41309. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  41310. }
  41311. // Instances
  41312. serializationObject.instances = [];
  41313. for (var index = 0; index < mesh.instances.length; index++) {
  41314. var instance = mesh.instances[index];
  41315. var serializationInstance = {
  41316. name: instance.name,
  41317. position: instance.position.asArray(),
  41318. scaling: instance.scaling.asArray()
  41319. };
  41320. if (instance.rotationQuaternion) {
  41321. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  41322. }
  41323. else if (instance.rotation) {
  41324. serializationInstance.rotation = instance.rotation.asArray();
  41325. }
  41326. serializationObject.instances.push(serializationInstance);
  41327. // Animations
  41328. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  41329. serializationInstance.ranges = instance.serializeAnimationRanges();
  41330. }
  41331. // Animations
  41332. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  41333. serializationObject.ranges = mesh.serializeAnimationRanges();
  41334. // Layer mask
  41335. serializationObject.layerMask = mesh.layerMask;
  41336. // Action Manager
  41337. if (mesh.actionManager) {
  41338. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  41339. }
  41340. return serializationObject;
  41341. };
  41342. var finalizeSingleMesh = function (mesh, serializationObject) {
  41343. //only works if the mesh is already loaded
  41344. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  41345. //serialize material
  41346. if (mesh.material) {
  41347. if (mesh.material instanceof BABYLON.StandardMaterial) {
  41348. serializationObject.materials = serializationObject.materials || [];
  41349. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  41350. serializationObject.materials.push(mesh.material.serialize());
  41351. }
  41352. }
  41353. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  41354. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  41355. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  41356. serializationObject.multiMaterials.push(mesh.material.serialize());
  41357. }
  41358. }
  41359. }
  41360. //serialize geometry
  41361. var geometry = mesh._geometry;
  41362. if (geometry) {
  41363. if (!serializationObject.geometries) {
  41364. serializationObject.geometries = {};
  41365. serializationObject.geometries.boxes = [];
  41366. serializationObject.geometries.spheres = [];
  41367. serializationObject.geometries.cylinders = [];
  41368. serializationObject.geometries.toruses = [];
  41369. serializationObject.geometries.grounds = [];
  41370. serializationObject.geometries.planes = [];
  41371. serializationObject.geometries.torusKnots = [];
  41372. serializationObject.geometries.vertexData = [];
  41373. }
  41374. serializeGeometry(geometry, serializationObject.geometries);
  41375. }
  41376. // Skeletons
  41377. if (mesh.skeleton) {
  41378. serializationObject.skeletons = serializationObject.skeletons || [];
  41379. serializationObject.skeletons.push(mesh.skeleton.serialize());
  41380. }
  41381. //serialize the actual mesh
  41382. serializationObject.meshes = serializationObject.meshes || [];
  41383. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  41384. }
  41385. };
  41386. var SceneSerializer = (function () {
  41387. function SceneSerializer() {
  41388. }
  41389. SceneSerializer.ClearCache = function () {
  41390. serializedGeometries = [];
  41391. };
  41392. SceneSerializer.Serialize = function (scene) {
  41393. var serializationObject = {};
  41394. // Scene
  41395. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  41396. serializationObject.autoClear = scene.autoClear;
  41397. serializationObject.clearColor = scene.clearColor.asArray();
  41398. serializationObject.ambientColor = scene.ambientColor.asArray();
  41399. serializationObject.gravity = scene.gravity.asArray();
  41400. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  41401. serializationObject.workerCollisions = scene.workerCollisions;
  41402. // Fog
  41403. if (scene.fogMode && scene.fogMode !== 0) {
  41404. serializationObject.fogMode = scene.fogMode;
  41405. serializationObject.fogColor = scene.fogColor.asArray();
  41406. serializationObject.fogStart = scene.fogStart;
  41407. serializationObject.fogEnd = scene.fogEnd;
  41408. serializationObject.fogDensity = scene.fogDensity;
  41409. }
  41410. //Physics
  41411. if (scene.isPhysicsEnabled()) {
  41412. serializationObject.physicsEnabled = true;
  41413. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  41414. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  41415. }
  41416. // Lights
  41417. serializationObject.lights = [];
  41418. var index;
  41419. var light;
  41420. for (index = 0; index < scene.lights.length; index++) {
  41421. light = scene.lights[index];
  41422. serializationObject.lights.push(light.serialize());
  41423. }
  41424. // Cameras
  41425. serializationObject.cameras = [];
  41426. for (index = 0; index < scene.cameras.length; index++) {
  41427. var camera = scene.cameras[index];
  41428. serializationObject.cameras.push(camera.serialize());
  41429. }
  41430. if (scene.activeCamera) {
  41431. serializationObject.activeCameraID = scene.activeCamera.id;
  41432. }
  41433. // Animations
  41434. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  41435. // Materials
  41436. serializationObject.materials = [];
  41437. serializationObject.multiMaterials = [];
  41438. var material;
  41439. for (index = 0; index < scene.materials.length; index++) {
  41440. material = scene.materials[index];
  41441. serializationObject.materials.push(material.serialize());
  41442. }
  41443. // MultiMaterials
  41444. serializationObject.multiMaterials = [];
  41445. for (index = 0; index < scene.multiMaterials.length; index++) {
  41446. var multiMaterial = scene.multiMaterials[index];
  41447. serializationObject.multiMaterials.push(multiMaterial.serialize());
  41448. }
  41449. // Skeletons
  41450. serializationObject.skeletons = [];
  41451. for (index = 0; index < scene.skeletons.length; index++) {
  41452. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  41453. }
  41454. // Geometries
  41455. serializationObject.geometries = {};
  41456. serializationObject.geometries.boxes = [];
  41457. serializationObject.geometries.spheres = [];
  41458. serializationObject.geometries.cylinders = [];
  41459. serializationObject.geometries.toruses = [];
  41460. serializationObject.geometries.grounds = [];
  41461. serializationObject.geometries.planes = [];
  41462. serializationObject.geometries.torusKnots = [];
  41463. serializationObject.geometries.vertexData = [];
  41464. serializedGeometries = [];
  41465. var geometries = scene.getGeometries();
  41466. for (index = 0; index < geometries.length; index++) {
  41467. var geometry = geometries[index];
  41468. if (geometry.isReady()) {
  41469. serializeGeometry(geometry, serializationObject.geometries);
  41470. }
  41471. }
  41472. // Meshes
  41473. serializationObject.meshes = [];
  41474. for (index = 0; index < scene.meshes.length; index++) {
  41475. var abstractMesh = scene.meshes[index];
  41476. if (abstractMesh instanceof BABYLON.Mesh) {
  41477. var mesh = abstractMesh;
  41478. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  41479. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  41480. }
  41481. }
  41482. }
  41483. // Particles Systems
  41484. serializationObject.particleSystems = [];
  41485. for (index = 0; index < scene.particleSystems.length; index++) {
  41486. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  41487. }
  41488. // Lens flares
  41489. serializationObject.lensFlareSystems = [];
  41490. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  41491. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  41492. }
  41493. // Shadows
  41494. serializationObject.shadowGenerators = [];
  41495. for (index = 0; index < scene.lights.length; index++) {
  41496. light = scene.lights[index];
  41497. var shadowGenerator = light.getShadowGenerator();
  41498. // Only support serialization for official generator so far.
  41499. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  41500. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  41501. }
  41502. }
  41503. // Action Manager
  41504. if (scene.actionManager) {
  41505. serializationObject.actions = scene.actionManager.serialize("scene");
  41506. }
  41507. // Audio
  41508. serializationObject.sounds = [];
  41509. for (index = 0; index < scene.soundTracks.length; index++) {
  41510. var soundtrack = scene.soundTracks[index];
  41511. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  41512. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  41513. }
  41514. }
  41515. return serializationObject;
  41516. };
  41517. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  41518. if (withParents === void 0) { withParents = false; }
  41519. if (withChildren === void 0) { withChildren = false; }
  41520. var serializationObject = {};
  41521. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  41522. if (withParents || withChildren) {
  41523. //deliberate for loop! not for each, appended should be processed as well.
  41524. for (var i = 0; i < toSerialize.length; ++i) {
  41525. if (withChildren) {
  41526. toSerialize[i].getDescendants().forEach(function (node) {
  41527. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  41528. toSerialize.push(node);
  41529. }
  41530. });
  41531. }
  41532. //make sure the array doesn't contain the object already
  41533. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  41534. toSerialize.push(toSerialize[i].parent);
  41535. }
  41536. }
  41537. }
  41538. toSerialize.forEach(function (mesh) {
  41539. finalizeSingleMesh(mesh, serializationObject);
  41540. });
  41541. return serializationObject;
  41542. };
  41543. return SceneSerializer;
  41544. }());
  41545. BABYLON.SceneSerializer = SceneSerializer;
  41546. })(BABYLON || (BABYLON = {}));
  41547. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  41548. // Huge respect for a such great lib.
  41549. // Earcut license:
  41550. // Copyright (c) 2016, Mapbox
  41551. //
  41552. // Permission to use, copy, modify, and/or distribute this software for any purpose
  41553. // with or without fee is hereby granted, provided that the above copyright notice
  41554. // and this permission notice appear in all copies.
  41555. //
  41556. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  41557. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  41558. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  41559. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  41560. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  41561. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  41562. // THIS SOFTWARE.
  41563. var Earcut;
  41564. (function (Earcut) {
  41565. /**
  41566. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  41567. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  41568. * @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).
  41569. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  41570. */
  41571. function earcut(data, holeIndices, dim) {
  41572. dim = dim || 2;
  41573. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  41574. if (!outerNode)
  41575. return triangles;
  41576. var minX, minY, maxX, maxY, x, y, size;
  41577. if (hasHoles)
  41578. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  41579. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  41580. if (data.length > 80 * dim) {
  41581. minX = maxX = data[0];
  41582. minY = maxY = data[1];
  41583. for (var i = dim; i < outerLen; i += dim) {
  41584. x = data[i];
  41585. y = data[i + 1];
  41586. if (x < minX)
  41587. minX = x;
  41588. if (y < minY)
  41589. minY = y;
  41590. if (x > maxX)
  41591. maxX = x;
  41592. if (y > maxY)
  41593. maxY = y;
  41594. }
  41595. // minX, minY and size are later used to transform coords into integers for z-order calculation
  41596. size = Math.max(maxX - minX, maxY - minY);
  41597. }
  41598. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  41599. return triangles;
  41600. }
  41601. Earcut.earcut = earcut;
  41602. // create a circular doubly linked list from polygon points in the specified winding order
  41603. function linkedList(data, start, end, dim, clockwise) {
  41604. var i, last;
  41605. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  41606. for (i = start; i < end; i += dim)
  41607. last = insertNode(i, data[i], data[i + 1], last);
  41608. }
  41609. else {
  41610. for (i = end - dim; i >= start; i -= dim)
  41611. last = insertNode(i, data[i], data[i + 1], last);
  41612. }
  41613. if (last && equals(last, last.next)) {
  41614. removeNode(last);
  41615. last = last.next;
  41616. }
  41617. return last;
  41618. }
  41619. // eliminate colinear or duplicate points
  41620. function filterPoints(start, end) {
  41621. if (!start)
  41622. return start;
  41623. if (!end)
  41624. end = start;
  41625. var p = start, again;
  41626. do {
  41627. again = false;
  41628. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  41629. removeNode(p);
  41630. p = end = p.prev;
  41631. if (p === p.next)
  41632. return null;
  41633. again = true;
  41634. }
  41635. else {
  41636. p = p.next;
  41637. }
  41638. } while (again || p !== end);
  41639. return end;
  41640. }
  41641. // main ear slicing loop which triangulates a polygon (given as a linked list)
  41642. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  41643. if (!ear)
  41644. return;
  41645. // interlink polygon nodes in z-order
  41646. if (!pass && size)
  41647. indexCurve(ear, minX, minY, size);
  41648. var stop = ear, prev, next;
  41649. // iterate through ears, slicing them one by one
  41650. while (ear.prev !== ear.next) {
  41651. prev = ear.prev;
  41652. next = ear.next;
  41653. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  41654. // cut off the triangle
  41655. triangles.push(prev.i / dim);
  41656. triangles.push(ear.i / dim);
  41657. triangles.push(next.i / dim);
  41658. removeNode(ear);
  41659. // skipping the next vertice leads to less sliver triangles
  41660. ear = next.next;
  41661. stop = next.next;
  41662. continue;
  41663. }
  41664. ear = next;
  41665. // if we looped through the whole remaining polygon and can't find any more ears
  41666. if (ear === stop) {
  41667. // try filtering points and slicing again
  41668. if (!pass) {
  41669. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  41670. }
  41671. else if (pass === 1) {
  41672. ear = cureLocalIntersections(ear, triangles, dim);
  41673. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  41674. }
  41675. else if (pass === 2) {
  41676. splitEarcut(ear, triangles, dim, minX, minY, size);
  41677. }
  41678. break;
  41679. }
  41680. }
  41681. }
  41682. // check whether a polygon node forms a valid ear with adjacent nodes
  41683. function isEar(ear) {
  41684. var a = ear.prev, b = ear, c = ear.next;
  41685. if (area(a, b, c) >= 0)
  41686. return false; // reflex, can't be an ear
  41687. // now make sure we don't have other points inside the potential ear
  41688. var p = ear.next.next;
  41689. while (p !== ear.prev) {
  41690. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41691. area(p.prev, p, p.next) >= 0)
  41692. return false;
  41693. p = p.next;
  41694. }
  41695. return true;
  41696. }
  41697. function isEarHashed(ear, minX, minY, size) {
  41698. var a = ear.prev, b = ear, c = ear.next;
  41699. if (area(a, b, c) >= 0)
  41700. return false; // reflex, can't be an ear
  41701. // triangle bbox; min & max are calculated like this for speed
  41702. 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);
  41703. // z-order range for the current triangle bbox;
  41704. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  41705. // first look for points inside the triangle in increasing z-order
  41706. var p = ear.nextZ;
  41707. while (p && p.z <= maxZ) {
  41708. if (p !== ear.prev &&
  41709. p !== ear.next &&
  41710. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41711. area(p.prev, p, p.next) >= 0)
  41712. return false;
  41713. p = p.nextZ;
  41714. }
  41715. // then look for points in decreasing z-order
  41716. p = ear.prevZ;
  41717. while (p && p.z >= minZ) {
  41718. if (p !== ear.prev &&
  41719. p !== ear.next &&
  41720. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  41721. area(p.prev, p, p.next) >= 0)
  41722. return false;
  41723. p = p.prevZ;
  41724. }
  41725. return true;
  41726. }
  41727. // go through all polygon nodes and cure small local self-intersections
  41728. function cureLocalIntersections(start, triangles, dim) {
  41729. var p = start;
  41730. do {
  41731. var a = p.prev, b = p.next.next;
  41732. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  41733. triangles.push(a.i / dim);
  41734. triangles.push(p.i / dim);
  41735. triangles.push(b.i / dim);
  41736. // remove two nodes involved
  41737. removeNode(p);
  41738. removeNode(p.next);
  41739. p = start = b;
  41740. }
  41741. p = p.next;
  41742. } while (p !== start);
  41743. return p;
  41744. }
  41745. // try splitting polygon into two and triangulate them independently
  41746. function splitEarcut(start, triangles, dim, minX, minY, size) {
  41747. // look for a valid diagonal that divides the polygon into two
  41748. var a = start;
  41749. do {
  41750. var b = a.next.next;
  41751. while (b !== a.prev) {
  41752. if (a.i !== b.i && isValidDiagonal(a, b)) {
  41753. // split the polygon in two by the diagonal
  41754. var c = splitPolygon(a, b);
  41755. // filter colinear points around the cuts
  41756. a = filterPoints(a, a.next);
  41757. c = filterPoints(c, c.next);
  41758. // run earcut on each half
  41759. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  41760. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  41761. return;
  41762. }
  41763. b = b.next;
  41764. }
  41765. a = a.next;
  41766. } while (a !== start);
  41767. }
  41768. // link every hole into the outer loop, producing a single-ring polygon without holes
  41769. function eliminateHoles(data, holeIndices, outerNode, dim) {
  41770. var queue = [], i, len, start, end, list;
  41771. for (i = 0, len = holeIndices.length; i < len; i++) {
  41772. start = holeIndices[i] * dim;
  41773. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  41774. list = linkedList(data, start, end, dim, false);
  41775. if (list === list.next)
  41776. list.steiner = true;
  41777. queue.push(getLeftmost(list));
  41778. }
  41779. queue.sort(compareX);
  41780. // process holes from left to right
  41781. for (i = 0; i < queue.length; i++) {
  41782. eliminateHole(queue[i], outerNode);
  41783. outerNode = filterPoints(outerNode, outerNode.next);
  41784. }
  41785. return outerNode;
  41786. }
  41787. function compareX(a, b) {
  41788. return a.x - b.x;
  41789. }
  41790. // find a bridge between vertices that connects hole with an outer ring and and link it
  41791. function eliminateHole(hole, outerNode) {
  41792. outerNode = findHoleBridge(hole, outerNode);
  41793. if (outerNode) {
  41794. var b = splitPolygon(outerNode, hole);
  41795. filterPoints(b, b.next);
  41796. }
  41797. }
  41798. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  41799. function findHoleBridge(hole, outerNode) {
  41800. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  41801. // find a segment intersected by a ray from the hole's leftmost point to the left;
  41802. // segment's endpoint with lesser x will be potential connection point
  41803. do {
  41804. if (hy <= p.y && hy >= p.next.y) {
  41805. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  41806. if (x <= hx && x > qx) {
  41807. qx = x;
  41808. if (x === hx) {
  41809. if (hy === p.y)
  41810. return p;
  41811. if (hy === p.next.y)
  41812. return p.next;
  41813. }
  41814. m = p.x < p.next.x ? p : p.next;
  41815. }
  41816. }
  41817. p = p.next;
  41818. } while (p !== outerNode);
  41819. if (!m)
  41820. return null;
  41821. if (hx === qx)
  41822. return m.prev; // hole touches outer segment; pick lower endpoint
  41823. // look for points inside the triangle of hole point, segment intersection and endpoint;
  41824. // if there are no points found, we have a valid connection;
  41825. // otherwise choose the point of the minimum angle with the ray as connection point
  41826. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  41827. p = m.next;
  41828. while (p !== stop) {
  41829. if (hx >= p.x &&
  41830. p.x >= mx &&
  41831. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  41832. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  41833. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  41834. m = p;
  41835. tanMin = tan;
  41836. }
  41837. }
  41838. p = p.next;
  41839. }
  41840. return m;
  41841. }
  41842. // interlink polygon nodes in z-order
  41843. function indexCurve(start, minX, minY, size) {
  41844. var p = start;
  41845. do {
  41846. if (p.z === null)
  41847. p.z = zOrder(p.x, p.y, minX, minY, size);
  41848. p.prevZ = p.prev;
  41849. p.nextZ = p.next;
  41850. p = p.next;
  41851. } while (p !== start);
  41852. p.prevZ.nextZ = null;
  41853. p.prevZ = null;
  41854. sortLinked(p);
  41855. }
  41856. // Simon Tatham's linked list merge sort algorithm
  41857. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  41858. function sortLinked(list) {
  41859. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  41860. do {
  41861. p = list;
  41862. list = null;
  41863. tail = null;
  41864. numMerges = 0;
  41865. while (p) {
  41866. numMerges++;
  41867. q = p;
  41868. pSize = 0;
  41869. for (i = 0; i < inSize; i++) {
  41870. pSize++;
  41871. q = q.nextZ;
  41872. if (!q)
  41873. break;
  41874. }
  41875. qSize = inSize;
  41876. while (pSize > 0 || (qSize > 0 && q)) {
  41877. if (pSize === 0) {
  41878. e = q;
  41879. q = q.nextZ;
  41880. qSize--;
  41881. }
  41882. else if (qSize === 0 || !q) {
  41883. e = p;
  41884. p = p.nextZ;
  41885. pSize--;
  41886. }
  41887. else if (p.z <= q.z) {
  41888. e = p;
  41889. p = p.nextZ;
  41890. pSize--;
  41891. }
  41892. else {
  41893. e = q;
  41894. q = q.nextZ;
  41895. qSize--;
  41896. }
  41897. if (tail)
  41898. tail.nextZ = e;
  41899. else
  41900. list = e;
  41901. e.prevZ = tail;
  41902. tail = e;
  41903. }
  41904. p = q;
  41905. }
  41906. tail.nextZ = null;
  41907. inSize *= 2;
  41908. } while (numMerges > 1);
  41909. return list;
  41910. }
  41911. // z-order of a point given coords and size of the data bounding box
  41912. function zOrder(x, y, minX, minY, size) {
  41913. // coords are transformed into non-negative 15-bit integer range
  41914. x = 32767 * (x - minX) / size;
  41915. y = 32767 * (y - minY) / size;
  41916. x = (x | (x << 8)) & 0x00FF00FF;
  41917. x = (x | (x << 4)) & 0x0F0F0F0F;
  41918. x = (x | (x << 2)) & 0x33333333;
  41919. x = (x | (x << 1)) & 0x55555555;
  41920. y = (y | (y << 8)) & 0x00FF00FF;
  41921. y = (y | (y << 4)) & 0x0F0F0F0F;
  41922. y = (y | (y << 2)) & 0x33333333;
  41923. y = (y | (y << 1)) & 0x55555555;
  41924. return x | (y << 1);
  41925. }
  41926. // find the leftmost node of a polygon ring
  41927. function getLeftmost(start) {
  41928. var p = start, leftmost = start;
  41929. do {
  41930. if (p.x < leftmost.x)
  41931. leftmost = p;
  41932. p = p.next;
  41933. } while (p !== start);
  41934. return leftmost;
  41935. }
  41936. // check if a point lies within a convex triangle
  41937. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  41938. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  41939. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  41940. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  41941. }
  41942. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  41943. function isValidDiagonal(a, b) {
  41944. return a.next.i !== b.i &&
  41945. a.prev.i !== b.i &&
  41946. !intersectsPolygon(a, b) &&
  41947. locallyInside(a, b) &&
  41948. locallyInside(b, a) &&
  41949. middleInside(a, b);
  41950. }
  41951. // signed area of a triangle
  41952. function area(p, q, r) {
  41953. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  41954. }
  41955. // check if two points are equal
  41956. function equals(p1, p2) {
  41957. return p1.x === p2.x && p1.y === p2.y;
  41958. }
  41959. // check if two segments intersect
  41960. function intersects(p1, q1, p2, q2) {
  41961. if ((equals(p1, q1) && equals(p2, q2)) ||
  41962. (equals(p1, q2) && equals(p2, q1)))
  41963. return true;
  41964. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  41965. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  41966. }
  41967. // check if a polygon diagonal intersects any polygon segments
  41968. function intersectsPolygon(a, b) {
  41969. var p = a;
  41970. do {
  41971. if (p.i !== a.i &&
  41972. p.next.i !== a.i &&
  41973. p.i !== b.i &&
  41974. p.next.i !== b.i &&
  41975. intersects(p, p.next, a, b))
  41976. return true;
  41977. p = p.next;
  41978. } while (p !== a);
  41979. return false;
  41980. }
  41981. // check if a polygon diagonal is locally inside the polygon
  41982. function locallyInside(a, b) {
  41983. return area(a.prev, a, a.next) < 0
  41984. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  41985. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  41986. }
  41987. // check if the middle point of a polygon diagonal is inside the polygon
  41988. function middleInside(a, b) {
  41989. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  41990. do {
  41991. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  41992. inside = !inside;
  41993. p = p.next;
  41994. } while (p !== a);
  41995. return inside;
  41996. }
  41997. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  41998. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  41999. function splitPolygon(a, b) {
  42000. 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;
  42001. a.next = b;
  42002. b.prev = a;
  42003. a2.next = an;
  42004. an.prev = a2;
  42005. b2.next = a2;
  42006. a2.prev = b2;
  42007. bp.next = b2;
  42008. b2.prev = bp;
  42009. return b2;
  42010. }
  42011. // create a node and optionally link it with previous one (in a circular doubly linked list)
  42012. function insertNode(i, x, y, last) {
  42013. var p = new Node(i, x, y);
  42014. if (!last) {
  42015. p.prev = p;
  42016. p.next = p;
  42017. }
  42018. else {
  42019. p.next = last.next;
  42020. p.prev = last;
  42021. last.next.prev = p;
  42022. last.next = p;
  42023. }
  42024. return p;
  42025. }
  42026. function removeNode(p) {
  42027. p.next.prev = p.prev;
  42028. p.prev.next = p.next;
  42029. if (p.prevZ)
  42030. p.prevZ.nextZ = p.nextZ;
  42031. if (p.nextZ)
  42032. p.nextZ.prevZ = p.prevZ;
  42033. }
  42034. function Node(i, x, y) {
  42035. // vertice index in coordinates array
  42036. this.i = i;
  42037. // vertex coordinates
  42038. this.x = x;
  42039. this.y = y;
  42040. // previous and next vertice nodes in a polygon ring
  42041. this.prev = null;
  42042. this.next = null;
  42043. // z-order curve value
  42044. this.z = null;
  42045. // previous and next nodes in z-order
  42046. this.prevZ = null;
  42047. this.nextZ = null;
  42048. // indicates whether this is a steiner point
  42049. this.steiner = false;
  42050. }
  42051. /**
  42052. * return a percentage difference between the polygon area and its triangulation area;
  42053. * used to verify correctness of triangulation
  42054. */
  42055. function deviation(data, holeIndices, dim, triangles) {
  42056. var hasHoles = holeIndices && holeIndices.length;
  42057. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  42058. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  42059. if (hasHoles) {
  42060. for (var i = 0, len = holeIndices.length; i < len; i++) {
  42061. var start = holeIndices[i] * dim;
  42062. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  42063. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  42064. }
  42065. }
  42066. var trianglesArea = 0;
  42067. for (i = 0; i < triangles.length; i += 3) {
  42068. var a = triangles[i] * dim;
  42069. var b = triangles[i + 1] * dim;
  42070. var c = triangles[i + 2] * dim;
  42071. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  42072. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  42073. }
  42074. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  42075. }
  42076. Earcut.deviation = deviation;
  42077. ;
  42078. function signedArea(data, start, end, dim) {
  42079. var sum = 0;
  42080. for (var i = start, j = end - dim; i < end; i += dim) {
  42081. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  42082. j = i;
  42083. }
  42084. return sum;
  42085. }
  42086. /**
  42087. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  42088. */
  42089. function flatten(data) {
  42090. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  42091. for (var i = 0; i < data.length; i++) {
  42092. for (var j = 0; j < data[i].length; j++) {
  42093. for (var d = 0; d < dim; d++)
  42094. result.vertices.push(data[i][j][d]);
  42095. }
  42096. if (i > 0) {
  42097. holeIndex += data[i - 1].length;
  42098. result.holes.push(holeIndex);
  42099. }
  42100. }
  42101. return result;
  42102. }
  42103. Earcut.flatten = flatten;
  42104. ;
  42105. })(Earcut || (Earcut = {}));
  42106. var BABYLON;
  42107. (function (BABYLON) {
  42108. // Unique ID when we import meshes from Babylon to CSG
  42109. var currentCSGMeshId = 0;
  42110. // # class Vertex
  42111. // Represents a vertex of a polygon. Use your own vertex class instead of this
  42112. // one to provide additional features like texture coordinates and vertex
  42113. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  42114. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  42115. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  42116. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  42117. // is not used anywhere else.
  42118. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  42119. var Vertex = (function () {
  42120. function Vertex(pos, normal, uv) {
  42121. this.pos = pos;
  42122. this.normal = normal;
  42123. this.uv = uv;
  42124. }
  42125. Vertex.prototype.clone = function () {
  42126. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  42127. };
  42128. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  42129. // orientation of a polygon is flipped.
  42130. Vertex.prototype.flip = function () {
  42131. this.normal = this.normal.scale(-1);
  42132. };
  42133. // Create a new vertex between this vertex and `other` by linearly
  42134. // interpolating all properties using a parameter of `t`. Subclasses should
  42135. // override this to interpolate additional properties.
  42136. Vertex.prototype.interpolate = function (other, t) {
  42137. 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));
  42138. };
  42139. return Vertex;
  42140. }());
  42141. // # class Plane
  42142. // Represents a plane in 3D space.
  42143. var Plane = (function () {
  42144. function Plane(normal, w) {
  42145. this.normal = normal;
  42146. this.w = w;
  42147. }
  42148. Plane.FromPoints = function (a, b, c) {
  42149. var v0 = c.subtract(a);
  42150. var v1 = b.subtract(a);
  42151. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  42152. return null;
  42153. }
  42154. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  42155. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  42156. };
  42157. Plane.prototype.clone = function () {
  42158. return new Plane(this.normal.clone(), this.w);
  42159. };
  42160. Plane.prototype.flip = function () {
  42161. this.normal.scaleInPlace(-1);
  42162. this.w = -this.w;
  42163. };
  42164. // Split `polygon` by this plane if needed, then put the polygon or polygon
  42165. // fragments in the appropriate lists. Coplanar polygons go into either
  42166. // `coplanarFront` or `coplanarBack` depending on their orientation with
  42167. // respect to this plane. Polygons in front or in back of this plane go into
  42168. // either `front` or `back`.
  42169. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  42170. var COPLANAR = 0;
  42171. var FRONT = 1;
  42172. var BACK = 2;
  42173. var SPANNING = 3;
  42174. // Classify each point as well as the entire polygon into one of the above
  42175. // four classes.
  42176. var polygonType = 0;
  42177. var types = [];
  42178. var i;
  42179. var t;
  42180. for (i = 0; i < polygon.vertices.length; i++) {
  42181. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  42182. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  42183. polygonType |= type;
  42184. types.push(type);
  42185. }
  42186. // Put the polygon in the correct list, splitting it when necessary.
  42187. switch (polygonType) {
  42188. case COPLANAR:
  42189. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  42190. break;
  42191. case FRONT:
  42192. front.push(polygon);
  42193. break;
  42194. case BACK:
  42195. back.push(polygon);
  42196. break;
  42197. case SPANNING:
  42198. var f = [], b = [];
  42199. for (i = 0; i < polygon.vertices.length; i++) {
  42200. var j = (i + 1) % polygon.vertices.length;
  42201. var ti = types[i], tj = types[j];
  42202. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  42203. if (ti !== BACK)
  42204. f.push(vi);
  42205. if (ti !== FRONT)
  42206. b.push(ti !== BACK ? vi.clone() : vi);
  42207. if ((ti | tj) === SPANNING) {
  42208. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  42209. var v = vi.interpolate(vj, t);
  42210. f.push(v);
  42211. b.push(v.clone());
  42212. }
  42213. }
  42214. var poly;
  42215. if (f.length >= 3) {
  42216. poly = new Polygon(f, polygon.shared);
  42217. if (poly.plane)
  42218. front.push(poly);
  42219. }
  42220. if (b.length >= 3) {
  42221. poly = new Polygon(b, polygon.shared);
  42222. if (poly.plane)
  42223. back.push(poly);
  42224. }
  42225. break;
  42226. }
  42227. };
  42228. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  42229. // point is on the plane.
  42230. Plane.EPSILON = 1e-5;
  42231. return Plane;
  42232. }());
  42233. // # class Polygon
  42234. // Represents a convex polygon. The vertices used to initialize a polygon must
  42235. // be coplanar and form a convex loop.
  42236. //
  42237. // Each convex polygon has a `shared` property, which is shared between all
  42238. // polygons that are clones of each other or were split from the same polygon.
  42239. // This can be used to define per-polygon properties (such as surface color).
  42240. var Polygon = (function () {
  42241. function Polygon(vertices, shared) {
  42242. this.vertices = vertices;
  42243. this.shared = shared;
  42244. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  42245. }
  42246. Polygon.prototype.clone = function () {
  42247. var vertices = this.vertices.map(function (v) { return v.clone(); });
  42248. return new Polygon(vertices, this.shared);
  42249. };
  42250. Polygon.prototype.flip = function () {
  42251. this.vertices.reverse().map(function (v) { v.flip(); });
  42252. this.plane.flip();
  42253. };
  42254. return Polygon;
  42255. }());
  42256. // # class Node
  42257. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  42258. // by picking a polygon to split along. That polygon (and all other coplanar
  42259. // polygons) are added directly to that node and the other polygons are added to
  42260. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  42261. // no distinction between internal and leaf nodes.
  42262. var Node = (function () {
  42263. function Node(polygons) {
  42264. this.plane = null;
  42265. this.front = null;
  42266. this.back = null;
  42267. this.polygons = [];
  42268. if (polygons) {
  42269. this.build(polygons);
  42270. }
  42271. }
  42272. Node.prototype.clone = function () {
  42273. var node = new Node();
  42274. node.plane = this.plane && this.plane.clone();
  42275. node.front = this.front && this.front.clone();
  42276. node.back = this.back && this.back.clone();
  42277. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  42278. return node;
  42279. };
  42280. // Convert solid space to empty space and empty space to solid space.
  42281. Node.prototype.invert = function () {
  42282. for (var i = 0; i < this.polygons.length; i++) {
  42283. this.polygons[i].flip();
  42284. }
  42285. if (this.plane) {
  42286. this.plane.flip();
  42287. }
  42288. if (this.front) {
  42289. this.front.invert();
  42290. }
  42291. if (this.back) {
  42292. this.back.invert();
  42293. }
  42294. var temp = this.front;
  42295. this.front = this.back;
  42296. this.back = temp;
  42297. };
  42298. // Recursively remove all polygons in `polygons` that are inside this BSP
  42299. // tree.
  42300. Node.prototype.clipPolygons = function (polygons) {
  42301. if (!this.plane)
  42302. return polygons.slice();
  42303. var front = [], back = [];
  42304. for (var i = 0; i < polygons.length; i++) {
  42305. this.plane.splitPolygon(polygons[i], front, back, front, back);
  42306. }
  42307. if (this.front) {
  42308. front = this.front.clipPolygons(front);
  42309. }
  42310. if (this.back) {
  42311. back = this.back.clipPolygons(back);
  42312. }
  42313. else {
  42314. back = [];
  42315. }
  42316. return front.concat(back);
  42317. };
  42318. // Remove all polygons in this BSP tree that are inside the other BSP tree
  42319. // `bsp`.
  42320. Node.prototype.clipTo = function (bsp) {
  42321. this.polygons = bsp.clipPolygons(this.polygons);
  42322. if (this.front)
  42323. this.front.clipTo(bsp);
  42324. if (this.back)
  42325. this.back.clipTo(bsp);
  42326. };
  42327. // Return a list of all polygons in this BSP tree.
  42328. Node.prototype.allPolygons = function () {
  42329. var polygons = this.polygons.slice();
  42330. if (this.front)
  42331. polygons = polygons.concat(this.front.allPolygons());
  42332. if (this.back)
  42333. polygons = polygons.concat(this.back.allPolygons());
  42334. return polygons;
  42335. };
  42336. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  42337. // new polygons are filtered down to the bottom of the tree and become new
  42338. // nodes there. Each set of polygons is partitioned using the first polygon
  42339. // (no heuristic is used to pick a good split).
  42340. Node.prototype.build = function (polygons) {
  42341. if (!polygons.length)
  42342. return;
  42343. if (!this.plane)
  42344. this.plane = polygons[0].plane.clone();
  42345. var front = [], back = [];
  42346. for (var i = 0; i < polygons.length; i++) {
  42347. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  42348. }
  42349. if (front.length) {
  42350. if (!this.front)
  42351. this.front = new Node();
  42352. this.front.build(front);
  42353. }
  42354. if (back.length) {
  42355. if (!this.back)
  42356. this.back = new Node();
  42357. this.back.build(back);
  42358. }
  42359. };
  42360. return Node;
  42361. }());
  42362. var CSG = (function () {
  42363. function CSG() {
  42364. this.polygons = new Array();
  42365. }
  42366. // Convert BABYLON.Mesh to BABYLON.CSG
  42367. CSG.FromMesh = function (mesh) {
  42368. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  42369. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  42370. if (mesh instanceof BABYLON.Mesh) {
  42371. mesh.computeWorldMatrix(true);
  42372. matrix = mesh.getWorldMatrix();
  42373. meshPosition = mesh.position.clone();
  42374. meshRotation = mesh.rotation.clone();
  42375. if (mesh.rotationQuaternion) {
  42376. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  42377. }
  42378. meshScaling = mesh.scaling.clone();
  42379. }
  42380. else {
  42381. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  42382. }
  42383. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42384. var subMeshes = mesh.subMeshes;
  42385. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  42386. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  42387. vertices = [];
  42388. for (var j = 0; j < 3; j++) {
  42389. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  42390. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  42391. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  42392. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  42393. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  42394. vertex = new Vertex(position, normal, uv);
  42395. vertices.push(vertex);
  42396. }
  42397. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  42398. // To handle the case of degenerated triangle
  42399. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  42400. if (polygon.plane)
  42401. polygons.push(polygon);
  42402. }
  42403. }
  42404. var csg = CSG.FromPolygons(polygons);
  42405. csg.matrix = matrix;
  42406. csg.position = meshPosition;
  42407. csg.rotation = meshRotation;
  42408. csg.scaling = meshScaling;
  42409. csg.rotationQuaternion = meshRotationQuaternion;
  42410. currentCSGMeshId++;
  42411. return csg;
  42412. };
  42413. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  42414. CSG.FromPolygons = function (polygons) {
  42415. var csg = new CSG();
  42416. csg.polygons = polygons;
  42417. return csg;
  42418. };
  42419. CSG.prototype.clone = function () {
  42420. var csg = new CSG();
  42421. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  42422. csg.copyTransformAttributes(this);
  42423. return csg;
  42424. };
  42425. CSG.prototype.toPolygons = function () {
  42426. return this.polygons;
  42427. };
  42428. CSG.prototype.union = function (csg) {
  42429. var a = new Node(this.clone().polygons);
  42430. var b = new Node(csg.clone().polygons);
  42431. a.clipTo(b);
  42432. b.clipTo(a);
  42433. b.invert();
  42434. b.clipTo(a);
  42435. b.invert();
  42436. a.build(b.allPolygons());
  42437. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42438. };
  42439. CSG.prototype.unionInPlace = function (csg) {
  42440. var a = new Node(this.polygons);
  42441. var b = new Node(csg.polygons);
  42442. a.clipTo(b);
  42443. b.clipTo(a);
  42444. b.invert();
  42445. b.clipTo(a);
  42446. b.invert();
  42447. a.build(b.allPolygons());
  42448. this.polygons = a.allPolygons();
  42449. };
  42450. CSG.prototype.subtract = function (csg) {
  42451. var a = new Node(this.clone().polygons);
  42452. var b = new Node(csg.clone().polygons);
  42453. a.invert();
  42454. a.clipTo(b);
  42455. b.clipTo(a);
  42456. b.invert();
  42457. b.clipTo(a);
  42458. b.invert();
  42459. a.build(b.allPolygons());
  42460. a.invert();
  42461. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42462. };
  42463. CSG.prototype.subtractInPlace = function (csg) {
  42464. var a = new Node(this.polygons);
  42465. var b = new Node(csg.polygons);
  42466. a.invert();
  42467. a.clipTo(b);
  42468. b.clipTo(a);
  42469. b.invert();
  42470. b.clipTo(a);
  42471. b.invert();
  42472. a.build(b.allPolygons());
  42473. a.invert();
  42474. this.polygons = a.allPolygons();
  42475. };
  42476. CSG.prototype.intersect = function (csg) {
  42477. var a = new Node(this.clone().polygons);
  42478. var b = new Node(csg.clone().polygons);
  42479. a.invert();
  42480. b.clipTo(a);
  42481. b.invert();
  42482. a.clipTo(b);
  42483. b.clipTo(a);
  42484. a.build(b.allPolygons());
  42485. a.invert();
  42486. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  42487. };
  42488. CSG.prototype.intersectInPlace = function (csg) {
  42489. var a = new Node(this.polygons);
  42490. var b = new Node(csg.polygons);
  42491. a.invert();
  42492. b.clipTo(a);
  42493. b.invert();
  42494. a.clipTo(b);
  42495. b.clipTo(a);
  42496. a.build(b.allPolygons());
  42497. a.invert();
  42498. this.polygons = a.allPolygons();
  42499. };
  42500. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  42501. // not modified.
  42502. CSG.prototype.inverse = function () {
  42503. var csg = this.clone();
  42504. csg.inverseInPlace();
  42505. return csg;
  42506. };
  42507. CSG.prototype.inverseInPlace = function () {
  42508. this.polygons.map(function (p) { p.flip(); });
  42509. };
  42510. // This is used to keep meshes transformations so they can be restored
  42511. // when we build back a Babylon Mesh
  42512. // NB : All CSG operations are performed in world coordinates
  42513. CSG.prototype.copyTransformAttributes = function (csg) {
  42514. this.matrix = csg.matrix;
  42515. this.position = csg.position;
  42516. this.rotation = csg.rotation;
  42517. this.scaling = csg.scaling;
  42518. this.rotationQuaternion = csg.rotationQuaternion;
  42519. return this;
  42520. };
  42521. // Build Raw mesh from CSG
  42522. // Coordinates here are in world space
  42523. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  42524. var matrix = this.matrix.clone();
  42525. matrix.invert();
  42526. 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;
  42527. if (keepSubMeshes) {
  42528. // Sort Polygons, since subMeshes are indices range
  42529. polygons.sort(function (a, b) {
  42530. if (a.shared.meshId === b.shared.meshId) {
  42531. return a.shared.subMeshId - b.shared.subMeshId;
  42532. }
  42533. else {
  42534. return a.shared.meshId - b.shared.meshId;
  42535. }
  42536. });
  42537. }
  42538. for (var i = 0, il = polygons.length; i < il; i++) {
  42539. polygon = polygons[i];
  42540. // Building SubMeshes
  42541. if (!subMesh_dict[polygon.shared.meshId]) {
  42542. subMesh_dict[polygon.shared.meshId] = {};
  42543. }
  42544. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  42545. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  42546. indexStart: +Infinity,
  42547. indexEnd: -Infinity,
  42548. materialIndex: polygon.shared.materialIndex
  42549. };
  42550. }
  42551. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  42552. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  42553. polygonIndices[0] = 0;
  42554. polygonIndices[1] = j - 1;
  42555. polygonIndices[2] = j;
  42556. for (var k = 0; k < 3; k++) {
  42557. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  42558. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  42559. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  42560. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  42561. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  42562. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  42563. // Check if 2 points can be merged
  42564. if (!(typeof vertex_idx !== 'undefined' &&
  42565. normals[vertex_idx * 3] === localNormal.x &&
  42566. normals[vertex_idx * 3 + 1] === localNormal.y &&
  42567. normals[vertex_idx * 3 + 2] === localNormal.z &&
  42568. uvs[vertex_idx * 2] === uv.x &&
  42569. uvs[vertex_idx * 2 + 1] === uv.y)) {
  42570. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  42571. uvs.push(uv.x, uv.y);
  42572. normals.push(normal.x, normal.y, normal.z);
  42573. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  42574. }
  42575. indices.push(vertex_idx);
  42576. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  42577. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  42578. currentIndex++;
  42579. }
  42580. }
  42581. }
  42582. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  42583. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  42584. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  42585. mesh.setIndices(indices);
  42586. if (keepSubMeshes) {
  42587. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  42588. var materialIndexOffset = 0, materialMaxIndex;
  42589. mesh.subMeshes = new Array();
  42590. for (var m in subMesh_dict) {
  42591. materialMaxIndex = -1;
  42592. for (var sm in subMesh_dict[m]) {
  42593. subMesh_obj = subMesh_dict[m][sm];
  42594. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  42595. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  42596. }
  42597. materialIndexOffset += ++materialMaxIndex;
  42598. }
  42599. }
  42600. return mesh;
  42601. };
  42602. // Build Mesh from CSG taking material and transforms into account
  42603. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  42604. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  42605. mesh.material = material;
  42606. mesh.position.copyFrom(this.position);
  42607. mesh.rotation.copyFrom(this.rotation);
  42608. if (this.rotationQuaternion) {
  42609. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  42610. }
  42611. mesh.scaling.copyFrom(this.scaling);
  42612. mesh.computeWorldMatrix(true);
  42613. return mesh;
  42614. };
  42615. return CSG;
  42616. }());
  42617. BABYLON.CSG = CSG;
  42618. })(BABYLON || (BABYLON = {}));
  42619. var BABYLON;
  42620. (function (BABYLON) {
  42621. var VRDistortionCorrectionPostProcess = (function (_super) {
  42622. __extends(VRDistortionCorrectionPostProcess, _super);
  42623. //ANY
  42624. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  42625. var _this = this;
  42626. _super.call(this, name, "vrDistortionCorrection", [
  42627. 'LensCenter',
  42628. 'Scale',
  42629. 'ScaleIn',
  42630. 'HmdWarpParam'
  42631. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null);
  42632. this._isRightEye = isRightEye;
  42633. this._distortionFactors = vrMetrics.distortionK;
  42634. this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  42635. this._lensCenterOffset = vrMetrics.lensCenterOffset;
  42636. this.onSizeChangedObservable.add(function () {
  42637. _this.aspectRatio = _this.width * .5 / _this.height;
  42638. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  42639. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  42640. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  42641. });
  42642. this.onApplyObservable.add(function (effect) {
  42643. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  42644. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  42645. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  42646. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  42647. });
  42648. }
  42649. return VRDistortionCorrectionPostProcess;
  42650. }(BABYLON.PostProcess));
  42651. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  42652. })(BABYLON || (BABYLON = {}));
  42653. // Mainly based on these 2 articles :
  42654. // 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
  42655. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  42656. var BABYLON;
  42657. (function (BABYLON) {
  42658. (function (JoystickAxis) {
  42659. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  42660. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  42661. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  42662. })(BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  42663. var JoystickAxis = BABYLON.JoystickAxis;
  42664. var VirtualJoystick = (function () {
  42665. function VirtualJoystick(leftJoystick) {
  42666. var _this = this;
  42667. if (leftJoystick) {
  42668. this._leftJoystick = true;
  42669. }
  42670. else {
  42671. this._leftJoystick = false;
  42672. }
  42673. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  42674. VirtualJoystick._globalJoystickIndex++;
  42675. // By default left & right arrow keys are moving the X
  42676. // and up & down keys are moving the Y
  42677. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  42678. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  42679. this.reverseLeftRight = false;
  42680. this.reverseUpDown = false;
  42681. // collections of pointers
  42682. this._touches = new BABYLON.StringDictionary();
  42683. this.deltaPosition = BABYLON.Vector3.Zero();
  42684. this._joystickSensibility = 25;
  42685. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42686. this._rotationSpeed = 25;
  42687. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  42688. this._rotateOnAxisRelativeToMesh = false;
  42689. this._onResize = function (evt) {
  42690. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42691. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42692. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  42693. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  42694. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  42695. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  42696. };
  42697. // injecting a canvas element on top of the canvas 3D game
  42698. if (!VirtualJoystick.vjCanvas) {
  42699. window.addEventListener("resize", this._onResize, false);
  42700. VirtualJoystick.vjCanvas = document.createElement("canvas");
  42701. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  42702. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  42703. VirtualJoystick.vjCanvas.width = window.innerWidth;
  42704. VirtualJoystick.vjCanvas.height = window.innerHeight;
  42705. VirtualJoystick.vjCanvas.style.width = "100%";
  42706. VirtualJoystick.vjCanvas.style.height = "100%";
  42707. VirtualJoystick.vjCanvas.style.position = "absolute";
  42708. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  42709. VirtualJoystick.vjCanvas.style.top = "0px";
  42710. VirtualJoystick.vjCanvas.style.left = "0px";
  42711. VirtualJoystick.vjCanvas.style.zIndex = "5";
  42712. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  42713. // Support for jQuery PEP polyfill
  42714. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  42715. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  42716. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  42717. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  42718. document.body.appendChild(VirtualJoystick.vjCanvas);
  42719. }
  42720. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  42721. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  42722. this.pressed = false;
  42723. // default joystick color
  42724. this._joystickColor = "cyan";
  42725. this._joystickPointerID = -1;
  42726. // current joystick position
  42727. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  42728. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  42729. // origin joystick position
  42730. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  42731. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  42732. this._onPointerDownHandlerRef = function (evt) {
  42733. _this._onPointerDown(evt);
  42734. };
  42735. this._onPointerMoveHandlerRef = function (evt) {
  42736. _this._onPointerMove(evt);
  42737. };
  42738. this._onPointerOutHandlerRef = function (evt) {
  42739. _this._onPointerUp(evt);
  42740. };
  42741. this._onPointerUpHandlerRef = function (evt) {
  42742. _this._onPointerUp(evt);
  42743. };
  42744. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  42745. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  42746. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  42747. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  42748. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  42749. evt.preventDefault(); // Disables system menu
  42750. }, false);
  42751. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  42752. }
  42753. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  42754. this._joystickSensibility = newJoystickSensibility;
  42755. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  42756. };
  42757. VirtualJoystick.prototype._onPointerDown = function (e) {
  42758. var positionOnScreenCondition;
  42759. e.preventDefault();
  42760. if (this._leftJoystick === true) {
  42761. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  42762. }
  42763. else {
  42764. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  42765. }
  42766. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  42767. // First contact will be dedicated to the virtual joystick
  42768. this._joystickPointerID = e.pointerId;
  42769. this._joystickPointerStartPos.x = e.clientX;
  42770. this._joystickPointerStartPos.y = e.clientY;
  42771. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  42772. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  42773. this._deltaJoystickVector.x = 0;
  42774. this._deltaJoystickVector.y = 0;
  42775. this.pressed = true;
  42776. this._touches.add(e.pointerId.toString(), e);
  42777. }
  42778. else {
  42779. // You can only trigger the action buttons with a joystick declared
  42780. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  42781. this._action();
  42782. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  42783. }
  42784. }
  42785. };
  42786. VirtualJoystick.prototype._onPointerMove = function (e) {
  42787. // If the current pointer is the one associated to the joystick (first touch contact)
  42788. if (this._joystickPointerID == e.pointerId) {
  42789. this._joystickPointerPos.x = e.clientX;
  42790. this._joystickPointerPos.y = e.clientY;
  42791. this._deltaJoystickVector = this._joystickPointerPos.clone();
  42792. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  42793. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  42794. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  42795. switch (this._axisTargetedByLeftAndRight) {
  42796. case JoystickAxis.X:
  42797. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  42798. break;
  42799. case JoystickAxis.Y:
  42800. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  42801. break;
  42802. case JoystickAxis.Z:
  42803. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  42804. break;
  42805. }
  42806. var directionUpDown = this.reverseUpDown ? 1 : -1;
  42807. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  42808. switch (this._axisTargetedByUpAndDown) {
  42809. case JoystickAxis.X:
  42810. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  42811. break;
  42812. case JoystickAxis.Y:
  42813. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  42814. break;
  42815. case JoystickAxis.Z:
  42816. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  42817. break;
  42818. }
  42819. }
  42820. else {
  42821. var data = this._touches.get(e.pointerId.toString());
  42822. if (data) {
  42823. data.x = e.clientX;
  42824. data.y = e.clientY;
  42825. }
  42826. }
  42827. };
  42828. VirtualJoystick.prototype._onPointerUp = function (e) {
  42829. if (this._joystickPointerID == e.pointerId) {
  42830. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  42831. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  42832. this._joystickPointerID = -1;
  42833. this.pressed = false;
  42834. }
  42835. else {
  42836. var touch = this._touches.get(e.pointerId.toString());
  42837. if (touch) {
  42838. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  42839. }
  42840. }
  42841. this._deltaJoystickVector.x = 0;
  42842. this._deltaJoystickVector.y = 0;
  42843. this._touches.remove(e.pointerId.toString());
  42844. };
  42845. /**
  42846. * Change the color of the virtual joystick
  42847. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  42848. */
  42849. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  42850. this._joystickColor = newColor;
  42851. };
  42852. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  42853. this._action = action;
  42854. };
  42855. // Define which axis you'd like to control for left & right
  42856. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  42857. switch (axis) {
  42858. case JoystickAxis.X:
  42859. case JoystickAxis.Y:
  42860. case JoystickAxis.Z:
  42861. this._axisTargetedByLeftAndRight = axis;
  42862. break;
  42863. default:
  42864. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  42865. break;
  42866. }
  42867. };
  42868. // Define which axis you'd like to control for up & down
  42869. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  42870. switch (axis) {
  42871. case JoystickAxis.X:
  42872. case JoystickAxis.Y:
  42873. case JoystickAxis.Z:
  42874. this._axisTargetedByUpAndDown = axis;
  42875. break;
  42876. default:
  42877. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  42878. break;
  42879. }
  42880. };
  42881. VirtualJoystick.prototype._clearCanvas = function () {
  42882. if (this._leftJoystick) {
  42883. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  42884. }
  42885. else {
  42886. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  42887. }
  42888. };
  42889. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  42890. var _this = this;
  42891. if (this.pressed) {
  42892. this._touches.forEach(function (touch) {
  42893. if (touch.pointerId === _this._joystickPointerID) {
  42894. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  42895. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  42896. VirtualJoystick.vjCanvasContext.beginPath();
  42897. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  42898. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42899. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  42900. VirtualJoystick.vjCanvasContext.stroke();
  42901. VirtualJoystick.vjCanvasContext.closePath();
  42902. VirtualJoystick.vjCanvasContext.beginPath();
  42903. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42904. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  42905. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  42906. VirtualJoystick.vjCanvasContext.stroke();
  42907. VirtualJoystick.vjCanvasContext.closePath();
  42908. VirtualJoystick.vjCanvasContext.beginPath();
  42909. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  42910. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  42911. VirtualJoystick.vjCanvasContext.stroke();
  42912. VirtualJoystick.vjCanvasContext.closePath();
  42913. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  42914. }
  42915. else {
  42916. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  42917. VirtualJoystick.vjCanvasContext.beginPath();
  42918. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  42919. VirtualJoystick.vjCanvasContext.beginPath();
  42920. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  42921. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  42922. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  42923. VirtualJoystick.vjCanvasContext.stroke();
  42924. VirtualJoystick.vjCanvasContext.closePath();
  42925. touch.prevX = touch.x;
  42926. touch.prevY = touch.y;
  42927. }
  42928. ;
  42929. });
  42930. }
  42931. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  42932. };
  42933. VirtualJoystick.prototype.releaseCanvas = function () {
  42934. if (VirtualJoystick.vjCanvas) {
  42935. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  42936. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  42937. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  42938. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  42939. window.removeEventListener("resize", this._onResize);
  42940. document.body.removeChild(VirtualJoystick.vjCanvas);
  42941. VirtualJoystick.vjCanvas = null;
  42942. }
  42943. };
  42944. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  42945. VirtualJoystick._globalJoystickIndex = 0;
  42946. return VirtualJoystick;
  42947. }());
  42948. BABYLON.VirtualJoystick = VirtualJoystick;
  42949. })(BABYLON || (BABYLON = {}));
  42950. var BABYLON;
  42951. (function (BABYLON) {
  42952. // We're mainly based on the logic defined into the FreeCamera code
  42953. var VirtualJoysticksCamera = (function (_super) {
  42954. __extends(VirtualJoysticksCamera, _super);
  42955. function VirtualJoysticksCamera(name, position, scene) {
  42956. _super.call(this, name, position, scene);
  42957. this.inputs.addVirtualJoystick();
  42958. }
  42959. return VirtualJoysticksCamera;
  42960. }(BABYLON.FreeCamera));
  42961. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  42962. })(BABYLON || (BABYLON = {}));
  42963. var BABYLON;
  42964. (function (BABYLON) {
  42965. var FreeCameraVirtualJoystickInput = (function () {
  42966. function FreeCameraVirtualJoystickInput() {
  42967. }
  42968. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  42969. return this._leftjoystick;
  42970. };
  42971. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  42972. return this._rightjoystick;
  42973. };
  42974. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  42975. if (this._leftjoystick) {
  42976. var camera = this.camera;
  42977. var speed = camera._computeLocalCameraSpeed() * 50;
  42978. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  42979. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  42980. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  42981. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  42982. if (!this._leftjoystick.pressed) {
  42983. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  42984. }
  42985. if (!this._rightjoystick.pressed) {
  42986. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  42987. }
  42988. }
  42989. };
  42990. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  42991. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  42992. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  42993. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  42994. this._leftjoystick.setJoystickSensibility(0.15);
  42995. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  42996. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  42997. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  42998. this._rightjoystick.reverseUpDown = true;
  42999. this._rightjoystick.setJoystickSensibility(0.05);
  43000. this._rightjoystick.setJoystickColor("yellow");
  43001. };
  43002. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  43003. this._leftjoystick.releaseCanvas();
  43004. this._rightjoystick.releaseCanvas();
  43005. };
  43006. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  43007. return "FreeCameraVirtualJoystickInput";
  43008. };
  43009. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  43010. return "virtualJoystick";
  43011. };
  43012. return FreeCameraVirtualJoystickInput;
  43013. }());
  43014. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  43015. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  43016. })(BABYLON || (BABYLON = {}));
  43017. var BABYLON;
  43018. (function (BABYLON) {
  43019. var AnaglyphPostProcess = (function (_super) {
  43020. __extends(AnaglyphPostProcess, _super);
  43021. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  43022. var _this = this;
  43023. _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable);
  43024. this._passedProcess = rigCameras[0]._rigPostProcess;
  43025. this.onApplyObservable.add(function (effect) {
  43026. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  43027. });
  43028. }
  43029. return AnaglyphPostProcess;
  43030. }(BABYLON.PostProcess));
  43031. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  43032. })(BABYLON || (BABYLON = {}));
  43033. var BABYLON;
  43034. (function (BABYLON) {
  43035. var OutlineRenderer = (function () {
  43036. function OutlineRenderer(scene) {
  43037. this._scene = scene;
  43038. }
  43039. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  43040. var _this = this;
  43041. if (useOverlay === void 0) { useOverlay = false; }
  43042. var scene = this._scene;
  43043. var engine = this._scene.getEngine();
  43044. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  43045. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  43046. return;
  43047. }
  43048. var mesh = subMesh.getRenderingMesh();
  43049. var material = subMesh.getMaterial();
  43050. engine.enableEffect(this._effect);
  43051. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  43052. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  43053. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  43054. // Bones
  43055. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43056. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  43057. }
  43058. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  43059. // Alpha test
  43060. if (material && material.needAlphaTesting()) {
  43061. var alphaTexture = material.getAlphaTestTexture();
  43062. this._effect.setTexture("diffuseSampler", alphaTexture);
  43063. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  43064. }
  43065. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  43066. };
  43067. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  43068. var defines = [];
  43069. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  43070. var mesh = subMesh.getMesh();
  43071. var material = subMesh.getMaterial();
  43072. // Alpha test
  43073. if (material && material.needAlphaTesting()) {
  43074. defines.push("#define ALPHATEST");
  43075. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  43076. attribs.push(BABYLON.VertexBuffer.UVKind);
  43077. defines.push("#define UV1");
  43078. }
  43079. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  43080. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43081. defines.push("#define UV2");
  43082. }
  43083. }
  43084. // Bones
  43085. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  43086. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  43087. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  43088. if (mesh.numBoneInfluencers > 4) {
  43089. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  43090. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  43091. }
  43092. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  43093. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  43094. }
  43095. else {
  43096. defines.push("#define NUM_BONE_INFLUENCERS 0");
  43097. }
  43098. // Instances
  43099. if (useInstances) {
  43100. defines.push("#define INSTANCES");
  43101. attribs.push("world0");
  43102. attribs.push("world1");
  43103. attribs.push("world2");
  43104. attribs.push("world3");
  43105. }
  43106. // Get correct effect
  43107. var join = defines.join("\n");
  43108. if (this._cachedDefines !== join) {
  43109. this._cachedDefines = join;
  43110. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  43111. }
  43112. return this._effect.isReady();
  43113. };
  43114. return OutlineRenderer;
  43115. }());
  43116. BABYLON.OutlineRenderer = OutlineRenderer;
  43117. })(BABYLON || (BABYLON = {}));
  43118. var BABYLON;
  43119. (function (BABYLON) {
  43120. var MeshAssetTask = (function () {
  43121. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  43122. this.name = name;
  43123. this.meshesNames = meshesNames;
  43124. this.rootUrl = rootUrl;
  43125. this.sceneFilename = sceneFilename;
  43126. this.isCompleted = false;
  43127. }
  43128. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43129. var _this = this;
  43130. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  43131. _this.loadedMeshes = meshes;
  43132. _this.loadedParticleSystems = particleSystems;
  43133. _this.loadedSkeletons = skeletons;
  43134. _this.isCompleted = true;
  43135. if (_this.onSuccess) {
  43136. _this.onSuccess(_this);
  43137. }
  43138. onSuccess();
  43139. }, null, function () {
  43140. if (_this.onError) {
  43141. _this.onError(_this);
  43142. }
  43143. onError();
  43144. });
  43145. };
  43146. return MeshAssetTask;
  43147. }());
  43148. BABYLON.MeshAssetTask = MeshAssetTask;
  43149. var TextFileAssetTask = (function () {
  43150. function TextFileAssetTask(name, url) {
  43151. this.name = name;
  43152. this.url = url;
  43153. this.isCompleted = false;
  43154. }
  43155. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43156. var _this = this;
  43157. BABYLON.Tools.LoadFile(this.url, function (data) {
  43158. _this.text = data;
  43159. _this.isCompleted = true;
  43160. if (_this.onSuccess) {
  43161. _this.onSuccess(_this);
  43162. }
  43163. onSuccess();
  43164. }, null, scene.database, false, function () {
  43165. if (_this.onError) {
  43166. _this.onError(_this);
  43167. }
  43168. onError();
  43169. });
  43170. };
  43171. return TextFileAssetTask;
  43172. }());
  43173. BABYLON.TextFileAssetTask = TextFileAssetTask;
  43174. var BinaryFileAssetTask = (function () {
  43175. function BinaryFileAssetTask(name, url) {
  43176. this.name = name;
  43177. this.url = url;
  43178. this.isCompleted = false;
  43179. }
  43180. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43181. var _this = this;
  43182. BABYLON.Tools.LoadFile(this.url, function (data) {
  43183. _this.data = data;
  43184. _this.isCompleted = true;
  43185. if (_this.onSuccess) {
  43186. _this.onSuccess(_this);
  43187. }
  43188. onSuccess();
  43189. }, null, scene.database, true, function () {
  43190. if (_this.onError) {
  43191. _this.onError(_this);
  43192. }
  43193. onError();
  43194. });
  43195. };
  43196. return BinaryFileAssetTask;
  43197. }());
  43198. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  43199. var ImageAssetTask = (function () {
  43200. function ImageAssetTask(name, url) {
  43201. this.name = name;
  43202. this.url = url;
  43203. this.isCompleted = false;
  43204. }
  43205. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43206. var _this = this;
  43207. var img = new Image();
  43208. BABYLON.Tools.SetCorsBehavior(this.url, img);
  43209. img.onload = function () {
  43210. _this.image = img;
  43211. _this.isCompleted = true;
  43212. if (_this.onSuccess) {
  43213. _this.onSuccess(_this);
  43214. }
  43215. onSuccess();
  43216. };
  43217. img.onerror = function () {
  43218. if (_this.onError) {
  43219. _this.onError(_this);
  43220. }
  43221. onError();
  43222. };
  43223. img.src = this.url;
  43224. };
  43225. return ImageAssetTask;
  43226. }());
  43227. BABYLON.ImageAssetTask = ImageAssetTask;
  43228. var TextureAssetTask = (function () {
  43229. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  43230. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43231. this.name = name;
  43232. this.url = url;
  43233. this.noMipmap = noMipmap;
  43234. this.invertY = invertY;
  43235. this.samplingMode = samplingMode;
  43236. this.isCompleted = false;
  43237. }
  43238. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43239. var _this = this;
  43240. var onload = function () {
  43241. _this.isCompleted = true;
  43242. if (_this.onSuccess) {
  43243. _this.onSuccess(_this);
  43244. }
  43245. onSuccess();
  43246. };
  43247. var onerror = function () {
  43248. if (_this.onError) {
  43249. _this.onError(_this);
  43250. }
  43251. onError();
  43252. };
  43253. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  43254. };
  43255. return TextureAssetTask;
  43256. }());
  43257. BABYLON.TextureAssetTask = TextureAssetTask;
  43258. var CubeTextureAssetTask = (function () {
  43259. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  43260. this.name = name;
  43261. this.url = url;
  43262. this.extensions = extensions;
  43263. this.noMipmap = noMipmap;
  43264. this.files = files;
  43265. this.isCompleted = false;
  43266. }
  43267. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  43268. var _this = this;
  43269. var onload = function () {
  43270. _this.isCompleted = true;
  43271. if (_this.onSuccess) {
  43272. _this.onSuccess(_this);
  43273. }
  43274. onSuccess();
  43275. };
  43276. var onerror = function () {
  43277. if (_this.onError) {
  43278. _this.onError(_this);
  43279. }
  43280. onError();
  43281. };
  43282. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  43283. };
  43284. return CubeTextureAssetTask;
  43285. }());
  43286. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  43287. var AssetsManager = (function () {
  43288. function AssetsManager(scene) {
  43289. this.tasks = new Array();
  43290. this.waitingTasksCount = 0;
  43291. this.useDefaultLoadingScreen = true;
  43292. this._scene = scene;
  43293. }
  43294. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  43295. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  43296. this.tasks.push(task);
  43297. return task;
  43298. };
  43299. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  43300. var task = new TextFileAssetTask(taskName, url);
  43301. this.tasks.push(task);
  43302. return task;
  43303. };
  43304. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  43305. var task = new BinaryFileAssetTask(taskName, url);
  43306. this.tasks.push(task);
  43307. return task;
  43308. };
  43309. AssetsManager.prototype.addImageTask = function (taskName, url) {
  43310. var task = new ImageAssetTask(taskName, url);
  43311. this.tasks.push(task);
  43312. return task;
  43313. };
  43314. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  43315. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43316. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  43317. this.tasks.push(task);
  43318. return task;
  43319. };
  43320. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  43321. this.waitingTasksCount--;
  43322. if (this.waitingTasksCount === 0) {
  43323. if (this.onFinish) {
  43324. this.onFinish(this.tasks);
  43325. }
  43326. this._scene.getEngine().hideLoadingUI();
  43327. }
  43328. };
  43329. AssetsManager.prototype._runTask = function (task) {
  43330. var _this = this;
  43331. task.run(this._scene, function () {
  43332. if (_this.onTaskSuccess) {
  43333. _this.onTaskSuccess(task);
  43334. }
  43335. _this._decreaseWaitingTasksCount();
  43336. }, function () {
  43337. if (_this.onTaskError) {
  43338. _this.onTaskError(task);
  43339. }
  43340. _this._decreaseWaitingTasksCount();
  43341. });
  43342. };
  43343. AssetsManager.prototype.reset = function () {
  43344. this.tasks = new Array();
  43345. return this;
  43346. };
  43347. AssetsManager.prototype.load = function () {
  43348. this.waitingTasksCount = this.tasks.length;
  43349. if (this.waitingTasksCount === 0) {
  43350. if (this.onFinish) {
  43351. this.onFinish(this.tasks);
  43352. }
  43353. return this;
  43354. }
  43355. if (this.useDefaultLoadingScreen) {
  43356. this._scene.getEngine().displayLoadingUI();
  43357. }
  43358. for (var index = 0; index < this.tasks.length; index++) {
  43359. var task = this.tasks[index];
  43360. this._runTask(task);
  43361. }
  43362. return this;
  43363. };
  43364. return AssetsManager;
  43365. }());
  43366. BABYLON.AssetsManager = AssetsManager;
  43367. })(BABYLON || (BABYLON = {}));
  43368. var BABYLON;
  43369. (function (BABYLON) {
  43370. var VRCameraMetrics = (function () {
  43371. function VRCameraMetrics() {
  43372. this.compensateDistortion = true;
  43373. }
  43374. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  43375. get: function () {
  43376. return this.hResolution / (2 * this.vResolution);
  43377. },
  43378. enumerable: true,
  43379. configurable: true
  43380. });
  43381. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  43382. get: function () {
  43383. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  43384. },
  43385. enumerable: true,
  43386. configurable: true
  43387. });
  43388. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  43389. get: function () {
  43390. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  43391. var h = (4 * meters) / this.hScreenSize;
  43392. return BABYLON.Matrix.Translation(h, 0, 0);
  43393. },
  43394. enumerable: true,
  43395. configurable: true
  43396. });
  43397. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  43398. get: function () {
  43399. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  43400. var h = (4 * meters) / this.hScreenSize;
  43401. return BABYLON.Matrix.Translation(-h, 0, 0);
  43402. },
  43403. enumerable: true,
  43404. configurable: true
  43405. });
  43406. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  43407. get: function () {
  43408. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  43409. },
  43410. enumerable: true,
  43411. configurable: true
  43412. });
  43413. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  43414. get: function () {
  43415. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  43416. },
  43417. enumerable: true,
  43418. configurable: true
  43419. });
  43420. VRCameraMetrics.GetDefault = function () {
  43421. var result = new VRCameraMetrics();
  43422. result.hResolution = 1280;
  43423. result.vResolution = 800;
  43424. result.hScreenSize = 0.149759993;
  43425. result.vScreenSize = 0.0935999975;
  43426. result.vScreenCenter = 0.0467999987,
  43427. result.eyeToScreenDistance = 0.0410000011;
  43428. result.lensSeparationDistance = 0.0635000020;
  43429. result.interpupillaryDistance = 0.0640000030;
  43430. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  43431. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  43432. result.postProcessScaleFactor = 1.714605507808412;
  43433. result.lensCenterOffset = 0.151976421;
  43434. return result;
  43435. };
  43436. return VRCameraMetrics;
  43437. }());
  43438. BABYLON.VRCameraMetrics = VRCameraMetrics;
  43439. })(BABYLON || (BABYLON = {}));
  43440. var BABYLON;
  43441. (function (BABYLON) {
  43442. var WebVRFreeCamera = (function (_super) {
  43443. __extends(WebVRFreeCamera, _super);
  43444. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  43445. var _this = this;
  43446. if (compensateDistortion === void 0) { compensateDistortion = false; }
  43447. if (webVROptions === void 0) { webVROptions = {}; }
  43448. _super.call(this, name, position, scene);
  43449. this.webVROptions = webVROptions;
  43450. this._vrDevice = null;
  43451. this._cacheState = null;
  43452. this._vrEnabled = false;
  43453. this._attached = false;
  43454. //enable VR
  43455. this.getEngine().initWebVR();
  43456. if (!this.getEngine().vrDisplaysPromise) {
  43457. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  43458. }
  43459. else {
  43460. //TODO get the metrics updated using the device's eye parameters!
  43461. //TODO also check that the device has the right capabilities!
  43462. this._frameData = new VRFrameData();
  43463. this.getEngine().vrDisplaysPromise.then(function (devices) {
  43464. if (devices.length > 0) {
  43465. _this._vrEnabled = true;
  43466. if (_this.webVROptions.displayName) {
  43467. var found = devices.some(function (device) {
  43468. if (device.displayName === _this.webVROptions.displayName) {
  43469. _this._vrDevice = device;
  43470. return true;
  43471. }
  43472. else {
  43473. return false;
  43474. }
  43475. });
  43476. if (!found) {
  43477. _this._vrDevice = devices[0];
  43478. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  43479. }
  43480. }
  43481. else {
  43482. //choose the first one
  43483. _this._vrDevice = devices[0];
  43484. }
  43485. //reset the rig parameters.
  43486. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  43487. if (_this._attached) {
  43488. _this.getEngine().enableVR(_this._vrDevice);
  43489. }
  43490. }
  43491. else {
  43492. BABYLON.Tools.Error("No WebVR devices found!");
  43493. }
  43494. });
  43495. }
  43496. this.rotationQuaternion = new BABYLON.Quaternion();
  43497. this._quaternionCache = new BABYLON.Quaternion();
  43498. }
  43499. WebVRFreeCamera.prototype._checkInputs = function () {
  43500. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  43501. var currentPost = this._frameData.pose;
  43502. //make sure we have data
  43503. if (currentPost && currentPost.orientation) {
  43504. this._cacheState = currentPost;
  43505. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  43506. if (this.webVROptions.trackPosition && this._cacheState.position) {
  43507. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  43508. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  43509. }
  43510. }
  43511. }
  43512. _super.prototype._checkInputs.call(this);
  43513. };
  43514. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  43515. _super.prototype.attachControl.call(this, element, noPreventDefault);
  43516. this._attached = true;
  43517. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  43518. if (this._vrEnabled) {
  43519. this.getEngine().enableVR(this._vrDevice);
  43520. }
  43521. };
  43522. WebVRFreeCamera.prototype.detachControl = function (element) {
  43523. _super.prototype.detachControl.call(this, element);
  43524. this._vrEnabled = false;
  43525. this._attached = false;
  43526. this.getEngine().disableVR();
  43527. };
  43528. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  43529. //Backwards comp.
  43530. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  43531. //this.getEngine().switchFullscreen(requestPointerlock);
  43532. };
  43533. WebVRFreeCamera.prototype.getTypeName = function () {
  43534. return "WebVRFreeCamera";
  43535. };
  43536. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  43537. //uses the vrDisplay's "resetPose()".
  43538. //pitch and roll won't be affected.
  43539. this._vrDevice.resetPose();
  43540. };
  43541. return WebVRFreeCamera;
  43542. }(BABYLON.FreeCamera));
  43543. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  43544. })(BABYLON || (BABYLON = {}));
  43545. var BABYLON;
  43546. (function (BABYLON) {
  43547. // Standard optimizations
  43548. var SceneOptimization = (function () {
  43549. function SceneOptimization(priority) {
  43550. if (priority === void 0) { priority = 0; }
  43551. this.priority = priority;
  43552. this.apply = function (scene) {
  43553. return true; // Return true if everything that can be done was applied
  43554. };
  43555. }
  43556. return SceneOptimization;
  43557. }());
  43558. BABYLON.SceneOptimization = SceneOptimization;
  43559. var TextureOptimization = (function (_super) {
  43560. __extends(TextureOptimization, _super);
  43561. function TextureOptimization(priority, maximumSize) {
  43562. var _this = this;
  43563. if (priority === void 0) { priority = 0; }
  43564. if (maximumSize === void 0) { maximumSize = 1024; }
  43565. _super.call(this, priority);
  43566. this.priority = priority;
  43567. this.maximumSize = maximumSize;
  43568. this.apply = function (scene) {
  43569. var allDone = true;
  43570. for (var index = 0; index < scene.textures.length; index++) {
  43571. var texture = scene.textures[index];
  43572. if (!texture.canRescale) {
  43573. continue;
  43574. }
  43575. var currentSize = texture.getSize();
  43576. var maxDimension = Math.max(currentSize.width, currentSize.height);
  43577. if (maxDimension > _this.maximumSize) {
  43578. texture.scale(0.5);
  43579. allDone = false;
  43580. }
  43581. }
  43582. return allDone;
  43583. };
  43584. }
  43585. return TextureOptimization;
  43586. }(SceneOptimization));
  43587. BABYLON.TextureOptimization = TextureOptimization;
  43588. var HardwareScalingOptimization = (function (_super) {
  43589. __extends(HardwareScalingOptimization, _super);
  43590. function HardwareScalingOptimization(priority, maximumScale) {
  43591. var _this = this;
  43592. if (priority === void 0) { priority = 0; }
  43593. if (maximumScale === void 0) { maximumScale = 2; }
  43594. _super.call(this, priority);
  43595. this.priority = priority;
  43596. this.maximumScale = maximumScale;
  43597. this._currentScale = 1;
  43598. this.apply = function (scene) {
  43599. _this._currentScale++;
  43600. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  43601. return _this._currentScale >= _this.maximumScale;
  43602. };
  43603. }
  43604. return HardwareScalingOptimization;
  43605. }(SceneOptimization));
  43606. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  43607. var ShadowsOptimization = (function (_super) {
  43608. __extends(ShadowsOptimization, _super);
  43609. function ShadowsOptimization() {
  43610. _super.apply(this, arguments);
  43611. this.apply = function (scene) {
  43612. scene.shadowsEnabled = false;
  43613. return true;
  43614. };
  43615. }
  43616. return ShadowsOptimization;
  43617. }(SceneOptimization));
  43618. BABYLON.ShadowsOptimization = ShadowsOptimization;
  43619. var PostProcessesOptimization = (function (_super) {
  43620. __extends(PostProcessesOptimization, _super);
  43621. function PostProcessesOptimization() {
  43622. _super.apply(this, arguments);
  43623. this.apply = function (scene) {
  43624. scene.postProcessesEnabled = false;
  43625. return true;
  43626. };
  43627. }
  43628. return PostProcessesOptimization;
  43629. }(SceneOptimization));
  43630. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  43631. var LensFlaresOptimization = (function (_super) {
  43632. __extends(LensFlaresOptimization, _super);
  43633. function LensFlaresOptimization() {
  43634. _super.apply(this, arguments);
  43635. this.apply = function (scene) {
  43636. scene.lensFlaresEnabled = false;
  43637. return true;
  43638. };
  43639. }
  43640. return LensFlaresOptimization;
  43641. }(SceneOptimization));
  43642. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  43643. var ParticlesOptimization = (function (_super) {
  43644. __extends(ParticlesOptimization, _super);
  43645. function ParticlesOptimization() {
  43646. _super.apply(this, arguments);
  43647. this.apply = function (scene) {
  43648. scene.particlesEnabled = false;
  43649. return true;
  43650. };
  43651. }
  43652. return ParticlesOptimization;
  43653. }(SceneOptimization));
  43654. BABYLON.ParticlesOptimization = ParticlesOptimization;
  43655. var RenderTargetsOptimization = (function (_super) {
  43656. __extends(RenderTargetsOptimization, _super);
  43657. function RenderTargetsOptimization() {
  43658. _super.apply(this, arguments);
  43659. this.apply = function (scene) {
  43660. scene.renderTargetsEnabled = false;
  43661. return true;
  43662. };
  43663. }
  43664. return RenderTargetsOptimization;
  43665. }(SceneOptimization));
  43666. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  43667. var MergeMeshesOptimization = (function (_super) {
  43668. __extends(MergeMeshesOptimization, _super);
  43669. function MergeMeshesOptimization() {
  43670. var _this = this;
  43671. _super.apply(this, arguments);
  43672. this._canBeMerged = function (abstractMesh) {
  43673. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  43674. return false;
  43675. }
  43676. var mesh = abstractMesh;
  43677. if (!mesh.isVisible || !mesh.isEnabled()) {
  43678. return false;
  43679. }
  43680. if (mesh.instances.length > 0) {
  43681. return false;
  43682. }
  43683. if (mesh.skeleton || mesh.hasLODLevels) {
  43684. return false;
  43685. }
  43686. if (mesh.parent) {
  43687. return false;
  43688. }
  43689. return true;
  43690. };
  43691. this.apply = function (scene, updateSelectionTree) {
  43692. var globalPool = scene.meshes.slice(0);
  43693. var globalLength = globalPool.length;
  43694. for (var index = 0; index < globalLength; index++) {
  43695. var currentPool = new Array();
  43696. var current = globalPool[index];
  43697. // Checks
  43698. if (!_this._canBeMerged(current)) {
  43699. continue;
  43700. }
  43701. currentPool.push(current);
  43702. // Find compatible meshes
  43703. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  43704. var otherMesh = globalPool[subIndex];
  43705. if (!_this._canBeMerged(otherMesh)) {
  43706. continue;
  43707. }
  43708. if (otherMesh.material !== current.material) {
  43709. continue;
  43710. }
  43711. if (otherMesh.checkCollisions !== current.checkCollisions) {
  43712. continue;
  43713. }
  43714. currentPool.push(otherMesh);
  43715. globalLength--;
  43716. globalPool.splice(subIndex, 1);
  43717. subIndex--;
  43718. }
  43719. if (currentPool.length < 2) {
  43720. continue;
  43721. }
  43722. // Merge meshes
  43723. BABYLON.Mesh.MergeMeshes(currentPool);
  43724. }
  43725. if (updateSelectionTree != undefined) {
  43726. if (updateSelectionTree) {
  43727. scene.createOrUpdateSelectionOctree();
  43728. }
  43729. }
  43730. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  43731. scene.createOrUpdateSelectionOctree();
  43732. }
  43733. return true;
  43734. };
  43735. }
  43736. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  43737. get: function () {
  43738. return MergeMeshesOptimization._UpdateSelectionTree;
  43739. },
  43740. set: function (value) {
  43741. MergeMeshesOptimization._UpdateSelectionTree = value;
  43742. },
  43743. enumerable: true,
  43744. configurable: true
  43745. });
  43746. MergeMeshesOptimization._UpdateSelectionTree = false;
  43747. return MergeMeshesOptimization;
  43748. }(SceneOptimization));
  43749. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  43750. // Options
  43751. var SceneOptimizerOptions = (function () {
  43752. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  43753. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  43754. if (trackerDuration === void 0) { trackerDuration = 2000; }
  43755. this.targetFrameRate = targetFrameRate;
  43756. this.trackerDuration = trackerDuration;
  43757. this.optimizations = new Array();
  43758. }
  43759. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  43760. var result = new SceneOptimizerOptions(targetFrameRate);
  43761. var priority = 0;
  43762. result.optimizations.push(new MergeMeshesOptimization(priority));
  43763. result.optimizations.push(new ShadowsOptimization(priority));
  43764. result.optimizations.push(new LensFlaresOptimization(priority));
  43765. // Next priority
  43766. priority++;
  43767. result.optimizations.push(new PostProcessesOptimization(priority));
  43768. result.optimizations.push(new ParticlesOptimization(priority));
  43769. // Next priority
  43770. priority++;
  43771. result.optimizations.push(new TextureOptimization(priority, 1024));
  43772. return result;
  43773. };
  43774. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  43775. var result = new SceneOptimizerOptions(targetFrameRate);
  43776. var priority = 0;
  43777. result.optimizations.push(new MergeMeshesOptimization(priority));
  43778. result.optimizations.push(new ShadowsOptimization(priority));
  43779. result.optimizations.push(new LensFlaresOptimization(priority));
  43780. // Next priority
  43781. priority++;
  43782. result.optimizations.push(new PostProcessesOptimization(priority));
  43783. result.optimizations.push(new ParticlesOptimization(priority));
  43784. // Next priority
  43785. priority++;
  43786. result.optimizations.push(new TextureOptimization(priority, 512));
  43787. // Next priority
  43788. priority++;
  43789. result.optimizations.push(new RenderTargetsOptimization(priority));
  43790. // Next priority
  43791. priority++;
  43792. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  43793. return result;
  43794. };
  43795. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  43796. var result = new SceneOptimizerOptions(targetFrameRate);
  43797. var priority = 0;
  43798. result.optimizations.push(new MergeMeshesOptimization(priority));
  43799. result.optimizations.push(new ShadowsOptimization(priority));
  43800. result.optimizations.push(new LensFlaresOptimization(priority));
  43801. // Next priority
  43802. priority++;
  43803. result.optimizations.push(new PostProcessesOptimization(priority));
  43804. result.optimizations.push(new ParticlesOptimization(priority));
  43805. // Next priority
  43806. priority++;
  43807. result.optimizations.push(new TextureOptimization(priority, 256));
  43808. // Next priority
  43809. priority++;
  43810. result.optimizations.push(new RenderTargetsOptimization(priority));
  43811. // Next priority
  43812. priority++;
  43813. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  43814. return result;
  43815. };
  43816. return SceneOptimizerOptions;
  43817. }());
  43818. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  43819. // Scene optimizer tool
  43820. var SceneOptimizer = (function () {
  43821. function SceneOptimizer() {
  43822. }
  43823. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  43824. // TODO: add an epsilon
  43825. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  43826. if (onSuccess) {
  43827. onSuccess();
  43828. }
  43829. return;
  43830. }
  43831. // Apply current level of optimizations
  43832. var allDone = true;
  43833. var noOptimizationApplied = true;
  43834. for (var index = 0; index < options.optimizations.length; index++) {
  43835. var optimization = options.optimizations[index];
  43836. if (optimization.priority === currentPriorityLevel) {
  43837. noOptimizationApplied = false;
  43838. allDone = allDone && optimization.apply(scene);
  43839. }
  43840. }
  43841. // If no optimization was applied, this is a failure :(
  43842. if (noOptimizationApplied) {
  43843. if (onFailure) {
  43844. onFailure();
  43845. }
  43846. return;
  43847. }
  43848. // If all optimizations were done, move to next level
  43849. if (allDone) {
  43850. currentPriorityLevel++;
  43851. }
  43852. // Let's the system running for a specific amount of time before checking FPS
  43853. scene.executeWhenReady(function () {
  43854. setTimeout(function () {
  43855. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  43856. }, options.trackerDuration);
  43857. });
  43858. };
  43859. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  43860. if (!options) {
  43861. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  43862. }
  43863. // Let's the system running for a specific amount of time before checking FPS
  43864. scene.executeWhenReady(function () {
  43865. setTimeout(function () {
  43866. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  43867. }, options.trackerDuration);
  43868. });
  43869. };
  43870. return SceneOptimizer;
  43871. }());
  43872. BABYLON.SceneOptimizer = SceneOptimizer;
  43873. })(BABYLON || (BABYLON = {}));
  43874. var BABYLON;
  43875. (function (BABYLON) {
  43876. var Internals;
  43877. (function (Internals) {
  43878. var MeshLODLevel = (function () {
  43879. function MeshLODLevel(distance, mesh) {
  43880. this.distance = distance;
  43881. this.mesh = mesh;
  43882. }
  43883. return MeshLODLevel;
  43884. }());
  43885. Internals.MeshLODLevel = MeshLODLevel;
  43886. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  43887. })(BABYLON || (BABYLON = {}));
  43888. var BABYLON;
  43889. (function (BABYLON) {
  43890. var RawTexture = (function (_super) {
  43891. __extends(RawTexture, _super);
  43892. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  43893. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43894. if (invertY === void 0) { invertY = false; }
  43895. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43896. _super.call(this, null, scene, !generateMipMaps, invertY);
  43897. this.format = format;
  43898. this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  43899. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43900. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  43901. }
  43902. RawTexture.prototype.update = function (data) {
  43903. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  43904. };
  43905. // Statics
  43906. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43907. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43908. if (invertY === void 0) { invertY = false; }
  43909. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43910. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  43911. };
  43912. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43913. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43914. if (invertY === void 0) { invertY = false; }
  43915. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43916. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43917. };
  43918. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43919. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43920. if (invertY === void 0) { invertY = false; }
  43921. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43922. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  43923. };
  43924. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43925. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43926. if (invertY === void 0) { invertY = false; }
  43927. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43928. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  43929. };
  43930. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  43931. if (generateMipMaps === void 0) { generateMipMaps = true; }
  43932. if (invertY === void 0) { invertY = false; }
  43933. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  43934. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  43935. };
  43936. return RawTexture;
  43937. }(BABYLON.Texture));
  43938. BABYLON.RawTexture = RawTexture;
  43939. })(BABYLON || (BABYLON = {}));
  43940. var BABYLON;
  43941. (function (BABYLON) {
  43942. var IndexedVector2 = (function (_super) {
  43943. __extends(IndexedVector2, _super);
  43944. function IndexedVector2(original, index) {
  43945. _super.call(this, original.x, original.y);
  43946. this.index = index;
  43947. }
  43948. return IndexedVector2;
  43949. }(BABYLON.Vector2));
  43950. var PolygonPoints = (function () {
  43951. function PolygonPoints() {
  43952. this.elements = new Array();
  43953. }
  43954. PolygonPoints.prototype.add = function (originalPoints) {
  43955. var _this = this;
  43956. var result = new Array();
  43957. originalPoints.forEach(function (point) {
  43958. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  43959. var newPoint = new IndexedVector2(point, _this.elements.length);
  43960. result.push(newPoint);
  43961. _this.elements.push(newPoint);
  43962. }
  43963. });
  43964. return result;
  43965. };
  43966. PolygonPoints.prototype.computeBounds = function () {
  43967. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  43968. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  43969. this.elements.forEach(function (point) {
  43970. // x
  43971. if (point.x < lmin.x) {
  43972. lmin.x = point.x;
  43973. }
  43974. else if (point.x > lmax.x) {
  43975. lmax.x = point.x;
  43976. }
  43977. // y
  43978. if (point.y < lmin.y) {
  43979. lmin.y = point.y;
  43980. }
  43981. else if (point.y > lmax.y) {
  43982. lmax.y = point.y;
  43983. }
  43984. });
  43985. return {
  43986. min: lmin,
  43987. max: lmax,
  43988. width: lmax.x - lmin.x,
  43989. height: lmax.y - lmin.y
  43990. };
  43991. };
  43992. return PolygonPoints;
  43993. }());
  43994. var Polygon = (function () {
  43995. function Polygon() {
  43996. }
  43997. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  43998. return [
  43999. new BABYLON.Vector2(xmin, ymin),
  44000. new BABYLON.Vector2(xmax, ymin),
  44001. new BABYLON.Vector2(xmax, ymax),
  44002. new BABYLON.Vector2(xmin, ymax)
  44003. ];
  44004. };
  44005. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  44006. if (cx === void 0) { cx = 0; }
  44007. if (cy === void 0) { cy = 0; }
  44008. if (numberOfSides === void 0) { numberOfSides = 32; }
  44009. var result = new Array();
  44010. var angle = 0;
  44011. var increment = (Math.PI * 2) / numberOfSides;
  44012. for (var i = 0; i < numberOfSides; i++) {
  44013. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  44014. angle -= increment;
  44015. }
  44016. return result;
  44017. };
  44018. Polygon.Parse = function (input) {
  44019. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  44020. var i, result = [];
  44021. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  44022. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  44023. }
  44024. return result;
  44025. };
  44026. Polygon.StartingAt = function (x, y) {
  44027. return BABYLON.Path2.StartingAt(x, y);
  44028. };
  44029. return Polygon;
  44030. }());
  44031. BABYLON.Polygon = Polygon;
  44032. var PolygonMeshBuilder = (function () {
  44033. function PolygonMeshBuilder(name, contours, scene) {
  44034. this._points = new PolygonPoints();
  44035. this._outlinepoints = new PolygonPoints();
  44036. this._holes = [];
  44037. this._epoints = new Array();
  44038. this._eholes = new Array();
  44039. this._name = name;
  44040. this._scene = scene;
  44041. var points;
  44042. if (contours instanceof BABYLON.Path2) {
  44043. points = contours.getPoints();
  44044. }
  44045. else {
  44046. points = contours;
  44047. }
  44048. this._addToepoint(points);
  44049. this._points.add(points);
  44050. this._outlinepoints.add(points);
  44051. }
  44052. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  44053. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  44054. var p = points_1[_i];
  44055. this._epoints.push(p.x, p.y);
  44056. }
  44057. };
  44058. PolygonMeshBuilder.prototype.addHole = function (hole) {
  44059. this._points.add(hole);
  44060. var holepoints = new PolygonPoints();
  44061. holepoints.add(hole);
  44062. this._holes.push(holepoints);
  44063. this._eholes.push(this._epoints.length / 2);
  44064. this._addToepoint(hole);
  44065. return this;
  44066. };
  44067. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  44068. var _this = this;
  44069. if (updatable === void 0) { updatable = false; }
  44070. var result = new BABYLON.Mesh(this._name, this._scene);
  44071. var normals = [];
  44072. var positions = [];
  44073. var uvs = [];
  44074. var bounds = this._points.computeBounds();
  44075. this._points.elements.forEach(function (p) {
  44076. normals.push(0, 1.0, 0);
  44077. positions.push(p.x, 0, p.y);
  44078. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  44079. });
  44080. var indices = [];
  44081. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  44082. for (var i = 0; i < res.length; i++) {
  44083. indices.push(res[i]);
  44084. }
  44085. if (depth > 0) {
  44086. var positionscount = (positions.length / 3); //get the current pointcount
  44087. this._points.elements.forEach(function (p) {
  44088. normals.push(0, -1.0, 0);
  44089. positions.push(p.x, -depth, p.y);
  44090. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  44091. });
  44092. var totalCount = indices.length;
  44093. for (var i = 0; i < totalCount; i += 3) {
  44094. var i0 = indices[i + 0];
  44095. var i1 = indices[i + 1];
  44096. var i2 = indices[i + 2];
  44097. indices.push(i2 + positionscount);
  44098. indices.push(i1 + positionscount);
  44099. indices.push(i0 + positionscount);
  44100. }
  44101. //Add the sides
  44102. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  44103. this._holes.forEach(function (hole) {
  44104. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  44105. });
  44106. }
  44107. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  44108. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  44109. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  44110. result.setIndices(indices);
  44111. return result;
  44112. };
  44113. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  44114. var StartIndex = positions.length / 3;
  44115. var ulength = 0;
  44116. for (var i = 0; i < points.elements.length; i++) {
  44117. var p = points.elements[i];
  44118. var p1;
  44119. if ((i + 1) > points.elements.length - 1) {
  44120. p1 = points.elements[0];
  44121. }
  44122. else {
  44123. p1 = points.elements[i + 1];
  44124. }
  44125. positions.push(p.x, 0, p.y);
  44126. positions.push(p.x, -depth, p.y);
  44127. positions.push(p1.x, 0, p1.y);
  44128. positions.push(p1.x, -depth, p1.y);
  44129. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  44130. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  44131. var v3 = v2.subtract(v1);
  44132. var v4 = new BABYLON.Vector3(0, 1, 0);
  44133. var vn = BABYLON.Vector3.Cross(v3, v4);
  44134. vn = vn.normalize();
  44135. uvs.push(ulength / bounds.width, 0);
  44136. uvs.push(ulength / bounds.width, 1);
  44137. ulength += v3.length();
  44138. uvs.push((ulength / bounds.width), 0);
  44139. uvs.push((ulength / bounds.width), 1);
  44140. if (!flip) {
  44141. normals.push(-vn.x, -vn.y, -vn.z);
  44142. normals.push(-vn.x, -vn.y, -vn.z);
  44143. normals.push(-vn.x, -vn.y, -vn.z);
  44144. normals.push(-vn.x, -vn.y, -vn.z);
  44145. indices.push(StartIndex);
  44146. indices.push(StartIndex + 1);
  44147. indices.push(StartIndex + 2);
  44148. indices.push(StartIndex + 1);
  44149. indices.push(StartIndex + 3);
  44150. indices.push(StartIndex + 2);
  44151. }
  44152. else {
  44153. normals.push(vn.x, vn.y, vn.z);
  44154. normals.push(vn.x, vn.y, vn.z);
  44155. normals.push(vn.x, vn.y, vn.z);
  44156. normals.push(vn.x, vn.y, vn.z);
  44157. indices.push(StartIndex);
  44158. indices.push(StartIndex + 2);
  44159. indices.push(StartIndex + 1);
  44160. indices.push(StartIndex + 1);
  44161. indices.push(StartIndex + 2);
  44162. indices.push(StartIndex + 3);
  44163. }
  44164. StartIndex += 4;
  44165. }
  44166. ;
  44167. };
  44168. return PolygonMeshBuilder;
  44169. }());
  44170. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  44171. })(BABYLON || (BABYLON = {}));
  44172. var BABYLON;
  44173. (function (BABYLON) {
  44174. var Octree = (function () {
  44175. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  44176. if (maxDepth === void 0) { maxDepth = 2; }
  44177. this.maxDepth = maxDepth;
  44178. this.dynamicContent = new Array();
  44179. this._maxBlockCapacity = maxBlockCapacity || 64;
  44180. this._selectionContent = new BABYLON.SmartArray(1024);
  44181. this._creationFunc = creationFunc;
  44182. }
  44183. // Methods
  44184. Octree.prototype.update = function (worldMin, worldMax, entries) {
  44185. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  44186. };
  44187. Octree.prototype.addMesh = function (entry) {
  44188. for (var index = 0; index < this.blocks.length; index++) {
  44189. var block = this.blocks[index];
  44190. block.addEntry(entry);
  44191. }
  44192. };
  44193. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  44194. this._selectionContent.reset();
  44195. for (var index = 0; index < this.blocks.length; index++) {
  44196. var block = this.blocks[index];
  44197. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  44198. }
  44199. if (allowDuplicate) {
  44200. this._selectionContent.concat(this.dynamicContent);
  44201. }
  44202. else {
  44203. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44204. }
  44205. return this._selectionContent;
  44206. };
  44207. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  44208. this._selectionContent.reset();
  44209. for (var index = 0; index < this.blocks.length; index++) {
  44210. var block = this.blocks[index];
  44211. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  44212. }
  44213. if (allowDuplicate) {
  44214. this._selectionContent.concat(this.dynamicContent);
  44215. }
  44216. else {
  44217. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44218. }
  44219. return this._selectionContent;
  44220. };
  44221. Octree.prototype.intersectsRay = function (ray) {
  44222. this._selectionContent.reset();
  44223. for (var index = 0; index < this.blocks.length; index++) {
  44224. var block = this.blocks[index];
  44225. block.intersectsRay(ray, this._selectionContent);
  44226. }
  44227. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  44228. return this._selectionContent;
  44229. };
  44230. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  44231. target.blocks = new Array();
  44232. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  44233. // Segmenting space
  44234. for (var x = 0; x < 2; x++) {
  44235. for (var y = 0; y < 2; y++) {
  44236. for (var z = 0; z < 2; z++) {
  44237. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  44238. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  44239. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  44240. block.addEntries(entries);
  44241. target.blocks.push(block);
  44242. }
  44243. }
  44244. }
  44245. };
  44246. Octree.CreationFuncForMeshes = function (entry, block) {
  44247. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  44248. block.entries.push(entry);
  44249. }
  44250. };
  44251. Octree.CreationFuncForSubMeshes = function (entry, block) {
  44252. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  44253. block.entries.push(entry);
  44254. }
  44255. };
  44256. return Octree;
  44257. }());
  44258. BABYLON.Octree = Octree;
  44259. })(BABYLON || (BABYLON = {}));
  44260. var BABYLON;
  44261. (function (BABYLON) {
  44262. var OctreeBlock = (function () {
  44263. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  44264. this.entries = new Array();
  44265. this._boundingVectors = new Array();
  44266. this._capacity = capacity;
  44267. this._depth = depth;
  44268. this._maxDepth = maxDepth;
  44269. this._creationFunc = creationFunc;
  44270. this._minPoint = minPoint;
  44271. this._maxPoint = maxPoint;
  44272. this._boundingVectors.push(minPoint.clone());
  44273. this._boundingVectors.push(maxPoint.clone());
  44274. this._boundingVectors.push(minPoint.clone());
  44275. this._boundingVectors[2].x = maxPoint.x;
  44276. this._boundingVectors.push(minPoint.clone());
  44277. this._boundingVectors[3].y = maxPoint.y;
  44278. this._boundingVectors.push(minPoint.clone());
  44279. this._boundingVectors[4].z = maxPoint.z;
  44280. this._boundingVectors.push(maxPoint.clone());
  44281. this._boundingVectors[5].z = minPoint.z;
  44282. this._boundingVectors.push(maxPoint.clone());
  44283. this._boundingVectors[6].x = minPoint.x;
  44284. this._boundingVectors.push(maxPoint.clone());
  44285. this._boundingVectors[7].y = minPoint.y;
  44286. }
  44287. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  44288. // Property
  44289. get: function () {
  44290. return this._capacity;
  44291. },
  44292. enumerable: true,
  44293. configurable: true
  44294. });
  44295. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  44296. get: function () {
  44297. return this._minPoint;
  44298. },
  44299. enumerable: true,
  44300. configurable: true
  44301. });
  44302. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  44303. get: function () {
  44304. return this._maxPoint;
  44305. },
  44306. enumerable: true,
  44307. configurable: true
  44308. });
  44309. // Methods
  44310. OctreeBlock.prototype.addEntry = function (entry) {
  44311. if (this.blocks) {
  44312. for (var index = 0; index < this.blocks.length; index++) {
  44313. var block = this.blocks[index];
  44314. block.addEntry(entry);
  44315. }
  44316. return;
  44317. }
  44318. this._creationFunc(entry, this);
  44319. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  44320. this.createInnerBlocks();
  44321. }
  44322. };
  44323. OctreeBlock.prototype.addEntries = function (entries) {
  44324. for (var index = 0; index < entries.length; index++) {
  44325. var mesh = entries[index];
  44326. this.addEntry(mesh);
  44327. }
  44328. };
  44329. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  44330. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  44331. if (this.blocks) {
  44332. for (var index = 0; index < this.blocks.length; index++) {
  44333. var block = this.blocks[index];
  44334. block.select(frustumPlanes, selection, allowDuplicate);
  44335. }
  44336. return;
  44337. }
  44338. if (allowDuplicate) {
  44339. selection.concat(this.entries);
  44340. }
  44341. else {
  44342. selection.concatWithNoDuplicate(this.entries);
  44343. }
  44344. }
  44345. };
  44346. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  44347. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  44348. if (this.blocks) {
  44349. for (var index = 0; index < this.blocks.length; index++) {
  44350. var block = this.blocks[index];
  44351. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  44352. }
  44353. return;
  44354. }
  44355. if (allowDuplicate) {
  44356. selection.concat(this.entries);
  44357. }
  44358. else {
  44359. selection.concatWithNoDuplicate(this.entries);
  44360. }
  44361. }
  44362. };
  44363. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  44364. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  44365. if (this.blocks) {
  44366. for (var index = 0; index < this.blocks.length; index++) {
  44367. var block = this.blocks[index];
  44368. block.intersectsRay(ray, selection);
  44369. }
  44370. return;
  44371. }
  44372. selection.concatWithNoDuplicate(this.entries);
  44373. }
  44374. };
  44375. OctreeBlock.prototype.createInnerBlocks = function () {
  44376. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  44377. };
  44378. return OctreeBlock;
  44379. }());
  44380. BABYLON.OctreeBlock = OctreeBlock;
  44381. })(BABYLON || (BABYLON = {}));
  44382. var BABYLON;
  44383. (function (BABYLON) {
  44384. var BlurPostProcess = (function (_super) {
  44385. __extends(BlurPostProcess, _super);
  44386. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  44387. var _this = this;
  44388. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  44389. _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable);
  44390. this.direction = direction;
  44391. this.blurWidth = blurWidth;
  44392. this.onApplyObservable.add(function (effect) {
  44393. effect.setFloat2("screenSize", _this.width, _this.height);
  44394. effect.setVector2("direction", _this.direction);
  44395. effect.setFloat("blurWidth", _this.blurWidth);
  44396. });
  44397. }
  44398. return BlurPostProcess;
  44399. }(BABYLON.PostProcess));
  44400. BABYLON.BlurPostProcess = BlurPostProcess;
  44401. })(BABYLON || (BABYLON = {}));
  44402. var BABYLON;
  44403. (function (BABYLON) {
  44404. var RefractionPostProcess = (function (_super) {
  44405. __extends(RefractionPostProcess, _super);
  44406. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  44407. var _this = this;
  44408. _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable);
  44409. this.color = color;
  44410. this.depth = depth;
  44411. this.colorLevel = colorLevel;
  44412. this.onActivateObservable.add(function (cam) {
  44413. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  44414. });
  44415. this.onApplyObservable.add(function (effect) {
  44416. effect.setColor3("baseColor", _this.color);
  44417. effect.setFloat("depth", _this.depth);
  44418. effect.setFloat("colorLevel", _this.colorLevel);
  44419. effect.setTexture("refractionSampler", _this._refRexture);
  44420. });
  44421. }
  44422. // Methods
  44423. RefractionPostProcess.prototype.dispose = function (camera) {
  44424. if (this._refRexture) {
  44425. this._refRexture.dispose();
  44426. }
  44427. _super.prototype.dispose.call(this, camera);
  44428. };
  44429. return RefractionPostProcess;
  44430. }(BABYLON.PostProcess));
  44431. BABYLON.RefractionPostProcess = RefractionPostProcess;
  44432. })(BABYLON || (BABYLON = {}));
  44433. var BABYLON;
  44434. (function (BABYLON) {
  44435. var BlackAndWhitePostProcess = (function (_super) {
  44436. __extends(BlackAndWhitePostProcess, _super);
  44437. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  44438. _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable);
  44439. }
  44440. return BlackAndWhitePostProcess;
  44441. }(BABYLON.PostProcess));
  44442. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  44443. })(BABYLON || (BABYLON = {}));
  44444. var BABYLON;
  44445. (function (BABYLON) {
  44446. var ConvolutionPostProcess = (function (_super) {
  44447. __extends(ConvolutionPostProcess, _super);
  44448. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  44449. var _this = this;
  44450. _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable);
  44451. this.kernel = kernel;
  44452. this.onApply = function (effect) {
  44453. effect.setFloat2("screenSize", _this.width, _this.height);
  44454. effect.setArray("kernel", _this.kernel);
  44455. };
  44456. }
  44457. // Statics
  44458. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  44459. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  44460. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  44461. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  44462. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  44463. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  44464. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  44465. return ConvolutionPostProcess;
  44466. }(BABYLON.PostProcess));
  44467. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  44468. })(BABYLON || (BABYLON = {}));
  44469. var BABYLON;
  44470. (function (BABYLON) {
  44471. var FilterPostProcess = (function (_super) {
  44472. __extends(FilterPostProcess, _super);
  44473. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  44474. var _this = this;
  44475. _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable);
  44476. this.kernelMatrix = kernelMatrix;
  44477. this.onApply = function (effect) {
  44478. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  44479. };
  44480. }
  44481. return FilterPostProcess;
  44482. }(BABYLON.PostProcess));
  44483. BABYLON.FilterPostProcess = FilterPostProcess;
  44484. })(BABYLON || (BABYLON = {}));
  44485. var BABYLON;
  44486. (function (BABYLON) {
  44487. var FxaaPostProcess = (function (_super) {
  44488. __extends(FxaaPostProcess, _super);
  44489. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  44490. var _this = this;
  44491. _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable);
  44492. this.onSizeChangedObservable.add(function () {
  44493. _this.texelWidth = 1.0 / _this.width;
  44494. _this.texelHeight = 1.0 / _this.height;
  44495. });
  44496. this.onApplyObservable.add(function (effect) {
  44497. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  44498. });
  44499. }
  44500. return FxaaPostProcess;
  44501. }(BABYLON.PostProcess));
  44502. BABYLON.FxaaPostProcess = FxaaPostProcess;
  44503. })(BABYLON || (BABYLON = {}));
  44504. var BABYLON;
  44505. (function (BABYLON) {
  44506. var StereoscopicInterlacePostProcess = (function (_super) {
  44507. __extends(StereoscopicInterlacePostProcess, _super);
  44508. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  44509. var _this = this;
  44510. _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined);
  44511. this._passedProcess = rigCameras[0]._rigPostProcess;
  44512. this._stepSize = new BABYLON.Vector2(1 / this.width, 1 / this.height);
  44513. this.onSizeChangedObservable.add(function () {
  44514. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  44515. });
  44516. this.onApplyObservable.add(function (effect) {
  44517. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  44518. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  44519. });
  44520. }
  44521. return StereoscopicInterlacePostProcess;
  44522. }(BABYLON.PostProcess));
  44523. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  44524. })(BABYLON || (BABYLON = {}));
  44525. var BABYLON;
  44526. (function (BABYLON) {
  44527. var LensFlare = (function () {
  44528. function LensFlare(size, position, color, imgUrl, system) {
  44529. this.size = size;
  44530. this.position = position;
  44531. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  44532. this.dispose = function () {
  44533. if (this.texture) {
  44534. this.texture.dispose();
  44535. }
  44536. // Remove from scene
  44537. var index = this._system.lensFlares.indexOf(this);
  44538. this._system.lensFlares.splice(index, 1);
  44539. };
  44540. this.color = color || new BABYLON.Color3(1, 1, 1);
  44541. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  44542. this._system = system;
  44543. system.lensFlares.push(this);
  44544. }
  44545. return LensFlare;
  44546. }());
  44547. BABYLON.LensFlare = LensFlare;
  44548. })(BABYLON || (BABYLON = {}));
  44549. var BABYLON;
  44550. (function (BABYLON) {
  44551. var LensFlareSystem = (function () {
  44552. function LensFlareSystem(name, emitter, scene) {
  44553. this.name = name;
  44554. this.lensFlares = new Array();
  44555. this.borderLimit = 300;
  44556. this.viewportBorder = 0;
  44557. this.layerMask = 0x0FFFFFFF;
  44558. this._vertexBuffers = {};
  44559. this._isEnabled = true;
  44560. this._scene = scene;
  44561. this._emitter = emitter;
  44562. this.id = name;
  44563. scene.lensFlareSystems.push(this);
  44564. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  44565. var engine = scene.getEngine();
  44566. // VBO
  44567. var vertices = [];
  44568. vertices.push(1, 1);
  44569. vertices.push(-1, 1);
  44570. vertices.push(-1, -1);
  44571. vertices.push(1, -1);
  44572. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  44573. // Indices
  44574. var indices = [];
  44575. indices.push(0);
  44576. indices.push(1);
  44577. indices.push(2);
  44578. indices.push(0);
  44579. indices.push(2);
  44580. indices.push(3);
  44581. this._indexBuffer = engine.createIndexBuffer(indices);
  44582. // Effects
  44583. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  44584. }
  44585. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  44586. get: function () {
  44587. return this._isEnabled;
  44588. },
  44589. set: function (value) {
  44590. this._isEnabled = value;
  44591. },
  44592. enumerable: true,
  44593. configurable: true
  44594. });
  44595. LensFlareSystem.prototype.getScene = function () {
  44596. return this._scene;
  44597. };
  44598. LensFlareSystem.prototype.getEmitter = function () {
  44599. return this._emitter;
  44600. };
  44601. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  44602. this._emitter = newEmitter;
  44603. };
  44604. LensFlareSystem.prototype.getEmitterPosition = function () {
  44605. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  44606. };
  44607. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  44608. var position = this.getEmitterPosition();
  44609. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  44610. this._positionX = position.x;
  44611. this._positionY = position.y;
  44612. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  44613. if (this.viewportBorder > 0) {
  44614. globalViewport.x -= this.viewportBorder;
  44615. globalViewport.y -= this.viewportBorder;
  44616. globalViewport.width += this.viewportBorder * 2;
  44617. globalViewport.height += this.viewportBorder * 2;
  44618. position.x += this.viewportBorder;
  44619. position.y += this.viewportBorder;
  44620. this._positionX += this.viewportBorder;
  44621. this._positionY += this.viewportBorder;
  44622. }
  44623. if (position.z > 0) {
  44624. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  44625. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  44626. return true;
  44627. }
  44628. return true;
  44629. }
  44630. return false;
  44631. };
  44632. LensFlareSystem.prototype._isVisible = function () {
  44633. if (!this._isEnabled) {
  44634. return false;
  44635. }
  44636. var emitterPosition = this.getEmitterPosition();
  44637. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  44638. var distance = direction.length();
  44639. direction.normalize();
  44640. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  44641. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  44642. return !pickInfo.hit || pickInfo.distance > distance;
  44643. };
  44644. LensFlareSystem.prototype.render = function () {
  44645. if (!this._effect.isReady())
  44646. return false;
  44647. var engine = this._scene.getEngine();
  44648. var viewport = this._scene.activeCamera.viewport;
  44649. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  44650. // Position
  44651. if (!this.computeEffectivePosition(globalViewport)) {
  44652. return false;
  44653. }
  44654. // Visibility
  44655. if (!this._isVisible()) {
  44656. return false;
  44657. }
  44658. // Intensity
  44659. var awayX;
  44660. var awayY;
  44661. if (this._positionX < this.borderLimit + globalViewport.x) {
  44662. awayX = this.borderLimit + globalViewport.x - this._positionX;
  44663. }
  44664. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  44665. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  44666. }
  44667. else {
  44668. awayX = 0;
  44669. }
  44670. if (this._positionY < this.borderLimit + globalViewport.y) {
  44671. awayY = this.borderLimit + globalViewport.y - this._positionY;
  44672. }
  44673. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  44674. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  44675. }
  44676. else {
  44677. awayY = 0;
  44678. }
  44679. var away = (awayX > awayY) ? awayX : awayY;
  44680. away -= this.viewportBorder;
  44681. if (away > this.borderLimit) {
  44682. away = this.borderLimit;
  44683. }
  44684. var intensity = 1.0 - (away / this.borderLimit);
  44685. if (intensity < 0) {
  44686. return false;
  44687. }
  44688. if (intensity > 1.0) {
  44689. intensity = 1.0;
  44690. }
  44691. if (this.viewportBorder > 0) {
  44692. globalViewport.x += this.viewportBorder;
  44693. globalViewport.y += this.viewportBorder;
  44694. globalViewport.width -= this.viewportBorder * 2;
  44695. globalViewport.height -= this.viewportBorder * 2;
  44696. this._positionX -= this.viewportBorder;
  44697. this._positionY -= this.viewportBorder;
  44698. }
  44699. // Position
  44700. var centerX = globalViewport.x + globalViewport.width / 2;
  44701. var centerY = globalViewport.y + globalViewport.height / 2;
  44702. var distX = centerX - this._positionX;
  44703. var distY = centerY - this._positionY;
  44704. // Effects
  44705. engine.enableEffect(this._effect);
  44706. engine.setState(false);
  44707. engine.setDepthBuffer(false);
  44708. // VBOs
  44709. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  44710. // Flares
  44711. for (var index = 0; index < this.lensFlares.length; index++) {
  44712. var flare = this.lensFlares[index];
  44713. engine.setAlphaMode(flare.alphaMode);
  44714. var x = centerX - (distX * flare.position);
  44715. var y = centerY - (distY * flare.position);
  44716. var cw = flare.size;
  44717. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  44718. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  44719. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  44720. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  44721. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  44722. // Texture
  44723. this._effect.setTexture("textureSampler", flare.texture);
  44724. // Color
  44725. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  44726. // Draw order
  44727. engine.draw(true, 0, 6);
  44728. }
  44729. engine.setDepthBuffer(true);
  44730. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  44731. return true;
  44732. };
  44733. LensFlareSystem.prototype.dispose = function () {
  44734. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  44735. if (vertexBuffer) {
  44736. vertexBuffer.dispose();
  44737. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  44738. }
  44739. if (this._indexBuffer) {
  44740. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  44741. this._indexBuffer = null;
  44742. }
  44743. while (this.lensFlares.length) {
  44744. this.lensFlares[0].dispose();
  44745. }
  44746. // Remove from scene
  44747. var index = this._scene.lensFlareSystems.indexOf(this);
  44748. this._scene.lensFlareSystems.splice(index, 1);
  44749. };
  44750. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  44751. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  44752. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  44753. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  44754. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  44755. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  44756. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  44757. var parsedFlare = parsedLensFlareSystem.flares[index];
  44758. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  44759. }
  44760. return lensFlareSystem;
  44761. };
  44762. LensFlareSystem.prototype.serialize = function () {
  44763. var serializationObject = {};
  44764. serializationObject.id = this.id;
  44765. serializationObject.name = this.name;
  44766. serializationObject.emitterId = this.getEmitter().id;
  44767. serializationObject.borderLimit = this.borderLimit;
  44768. serializationObject.flares = [];
  44769. for (var index = 0; index < this.lensFlares.length; index++) {
  44770. var flare = this.lensFlares[index];
  44771. serializationObject.flares.push({
  44772. size: flare.size,
  44773. position: flare.position,
  44774. color: flare.color.asArray(),
  44775. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  44776. });
  44777. }
  44778. return serializationObject;
  44779. };
  44780. return LensFlareSystem;
  44781. }());
  44782. BABYLON.LensFlareSystem = LensFlareSystem;
  44783. })(BABYLON || (BABYLON = {}));
  44784. var BABYLON;
  44785. (function (BABYLON) {
  44786. // We're mainly based on the logic defined into the FreeCamera code
  44787. var DeviceOrientationCamera = (function (_super) {
  44788. __extends(DeviceOrientationCamera, _super);
  44789. function DeviceOrientationCamera(name, position, scene) {
  44790. _super.call(this, name, position, scene);
  44791. this._quaternionCache = new BABYLON.Quaternion();
  44792. this.inputs.addDeviceOrientation();
  44793. }
  44794. DeviceOrientationCamera.prototype.getTypeName = function () {
  44795. return "DeviceOrientationCamera";
  44796. };
  44797. DeviceOrientationCamera.prototype._checkInputs = function () {
  44798. _super.prototype._checkInputs.call(this);
  44799. this._quaternionCache.copyFrom(this.rotationQuaternion);
  44800. if (this._initialQuaternion) {
  44801. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  44802. }
  44803. };
  44804. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  44805. var _this = this;
  44806. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  44807. //can only work if this camera has a rotation quaternion already.
  44808. if (!this.rotationQuaternion)
  44809. return;
  44810. if (!this._initialQuaternion) {
  44811. this._initialQuaternion = new BABYLON.Quaternion();
  44812. }
  44813. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  44814. ['x', 'y', 'z'].forEach(function (axisName) {
  44815. if (!axis[axisName]) {
  44816. _this._initialQuaternion[axisName] = 0;
  44817. }
  44818. else {
  44819. _this._initialQuaternion[axisName] *= -1;
  44820. }
  44821. });
  44822. this._initialQuaternion.normalize();
  44823. //force rotation update
  44824. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  44825. };
  44826. return DeviceOrientationCamera;
  44827. }(BABYLON.FreeCamera));
  44828. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  44829. })(BABYLON || (BABYLON = {}));
  44830. var BABYLON;
  44831. (function (BABYLON) {
  44832. var VRDeviceOrientationFreeCamera = (function (_super) {
  44833. __extends(VRDeviceOrientationFreeCamera, _super);
  44834. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  44835. if (compensateDistortion === void 0) { compensateDistortion = true; }
  44836. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  44837. _super.call(this, name, position, scene);
  44838. vrCameraMetrics.compensateDistortion = compensateDistortion;
  44839. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  44840. }
  44841. VRDeviceOrientationFreeCamera.prototype.getTypeName = function () {
  44842. return "VRDeviceOrientationFreeCamera";
  44843. };
  44844. return VRDeviceOrientationFreeCamera;
  44845. }(BABYLON.DeviceOrientationCamera));
  44846. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  44847. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  44848. __extends(VRDeviceOrientationArcRotateCamera, _super);
  44849. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  44850. if (compensateDistortion === void 0) { compensateDistortion = true; }
  44851. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  44852. _super.call(this, name, alpha, beta, radius, target, scene);
  44853. vrCameraMetrics.compensateDistortion = compensateDistortion;
  44854. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  44855. this.inputs.addVRDeviceOrientation();
  44856. }
  44857. VRDeviceOrientationArcRotateCamera.prototype.getTypeName = function () {
  44858. return "VRDeviceOrientationArcRotateCamera";
  44859. };
  44860. return VRDeviceOrientationArcRotateCamera;
  44861. }(BABYLON.ArcRotateCamera));
  44862. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  44863. })(BABYLON || (BABYLON = {}));
  44864. var BABYLON;
  44865. (function (BABYLON) {
  44866. // We're mainly based on the logic defined into the FreeCamera code
  44867. var UniversalCamera = (function (_super) {
  44868. __extends(UniversalCamera, _super);
  44869. //-- end properties for backward compatibility for inputs
  44870. function UniversalCamera(name, position, scene) {
  44871. _super.call(this, name, position, scene);
  44872. this.inputs.addGamepad();
  44873. }
  44874. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  44875. //-- Begin properties for backward compatibility for inputs
  44876. get: function () {
  44877. var gamepad = this.inputs.attached["gamepad"];
  44878. if (gamepad)
  44879. return gamepad.gamepadAngularSensibility;
  44880. },
  44881. set: function (value) {
  44882. var gamepad = this.inputs.attached["gamepad"];
  44883. if (gamepad)
  44884. gamepad.gamepadAngularSensibility = value;
  44885. },
  44886. enumerable: true,
  44887. configurable: true
  44888. });
  44889. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  44890. get: function () {
  44891. var gamepad = this.inputs.attached["gamepad"];
  44892. if (gamepad)
  44893. return gamepad.gamepadMoveSensibility;
  44894. },
  44895. set: function (value) {
  44896. var gamepad = this.inputs.attached["gamepad"];
  44897. if (gamepad)
  44898. gamepad.gamepadMoveSensibility = value;
  44899. },
  44900. enumerable: true,
  44901. configurable: true
  44902. });
  44903. UniversalCamera.prototype.getTypeName = function () {
  44904. return "UniversalCamera";
  44905. };
  44906. return UniversalCamera;
  44907. }(BABYLON.TouchCamera));
  44908. BABYLON.UniversalCamera = UniversalCamera;
  44909. })(BABYLON || (BABYLON = {}));
  44910. var BABYLON;
  44911. (function (BABYLON) {
  44912. var Gamepads = (function () {
  44913. function Gamepads(ongamedpadconnected) {
  44914. var _this = this;
  44915. this.babylonGamepads = [];
  44916. this.oneGamepadConnected = false;
  44917. this.isMonitoring = false;
  44918. this.gamepadEventSupported = 'GamepadEvent' in window;
  44919. this.gamepadSupportAvailable = (navigator.getGamepads ||
  44920. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  44921. this._callbackGamepadConnected = ongamedpadconnected;
  44922. if (this.gamepadSupportAvailable) {
  44923. // Checking if the gamepad connected event is supported (like in Firefox)
  44924. if (this.gamepadEventSupported) {
  44925. this._onGamepadConnectedEvent = function (evt) {
  44926. _this._onGamepadConnected(evt);
  44927. };
  44928. this._onGamepadDisonnectedEvent = function (evt) {
  44929. _this._onGamepadDisconnected(evt);
  44930. };
  44931. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  44932. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  44933. }
  44934. else {
  44935. this._startMonitoringGamepads();
  44936. }
  44937. }
  44938. }
  44939. Gamepads.prototype.dispose = function () {
  44940. if (Gamepads.gamepadDOMInfo) {
  44941. document.body.removeChild(Gamepads.gamepadDOMInfo);
  44942. }
  44943. if (this._onGamepadConnectedEvent) {
  44944. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  44945. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  44946. this._onGamepadConnectedEvent = null;
  44947. this._onGamepadDisonnectedEvent = null;
  44948. }
  44949. };
  44950. Gamepads.prototype._onGamepadConnected = function (evt) {
  44951. var newGamepad = this._addNewGamepad(evt.gamepad);
  44952. if (this._callbackGamepadConnected)
  44953. this._callbackGamepadConnected(newGamepad);
  44954. this._startMonitoringGamepads();
  44955. };
  44956. Gamepads.prototype._addNewGamepad = function (gamepad) {
  44957. if (!this.oneGamepadConnected) {
  44958. this.oneGamepadConnected = true;
  44959. if (Gamepads.gamepadDOMInfo) {
  44960. document.body.removeChild(Gamepads.gamepadDOMInfo);
  44961. Gamepads.gamepadDOMInfo = null;
  44962. }
  44963. }
  44964. var newGamepad;
  44965. if (gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  44966. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad);
  44967. }
  44968. else {
  44969. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  44970. }
  44971. this.babylonGamepads.push(newGamepad);
  44972. return newGamepad;
  44973. };
  44974. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  44975. // Remove the gamepad from the list of gamepads to monitor.
  44976. for (var i in this.babylonGamepads) {
  44977. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  44978. this.babylonGamepads.splice(+i, 1);
  44979. break;
  44980. }
  44981. }
  44982. // If no gamepads are left, stop the polling loop.
  44983. if (this.babylonGamepads.length == 0) {
  44984. this._stopMonitoringGamepads();
  44985. }
  44986. };
  44987. Gamepads.prototype._startMonitoringGamepads = function () {
  44988. if (!this.isMonitoring) {
  44989. this.isMonitoring = true;
  44990. this._checkGamepadsStatus();
  44991. }
  44992. };
  44993. Gamepads.prototype._stopMonitoringGamepads = function () {
  44994. this.isMonitoring = false;
  44995. };
  44996. Gamepads.prototype._checkGamepadsStatus = function () {
  44997. var _this = this;
  44998. // updating gamepad objects
  44999. this._updateGamepadObjects();
  45000. for (var i in this.babylonGamepads) {
  45001. this.babylonGamepads[i].update();
  45002. }
  45003. if (this.isMonitoring) {
  45004. if (window.requestAnimationFrame) {
  45005. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45006. }
  45007. else if (window.mozRequestAnimationFrame) {
  45008. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45009. }
  45010. else if (window.webkitRequestAnimationFrame) {
  45011. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  45012. }
  45013. }
  45014. };
  45015. // This function is called only on Chrome, which does not yet support
  45016. // connection/disconnection events, but requires you to monitor
  45017. // an array for changes.
  45018. Gamepads.prototype._updateGamepadObjects = function () {
  45019. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  45020. for (var i = 0; i < gamepads.length; i++) {
  45021. if (gamepads[i]) {
  45022. if (!(gamepads[i].index in this.babylonGamepads)) {
  45023. var newGamepad = this._addNewGamepad(gamepads[i]);
  45024. if (this._callbackGamepadConnected) {
  45025. this._callbackGamepadConnected(newGamepad);
  45026. }
  45027. }
  45028. else {
  45029. this.babylonGamepads[i].browserGamepad = gamepads[i];
  45030. }
  45031. }
  45032. }
  45033. };
  45034. return Gamepads;
  45035. }());
  45036. BABYLON.Gamepads = Gamepads;
  45037. var StickValues = (function () {
  45038. function StickValues(x, y) {
  45039. this.x = x;
  45040. this.y = y;
  45041. }
  45042. return StickValues;
  45043. }());
  45044. BABYLON.StickValues = StickValues;
  45045. var Gamepad = (function () {
  45046. function Gamepad(id, index, browserGamepad) {
  45047. this.id = id;
  45048. this.index = index;
  45049. this.browserGamepad = browserGamepad;
  45050. if (this.browserGamepad.axes.length >= 2) {
  45051. this._leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  45052. }
  45053. if (this.browserGamepad.axes.length >= 4) {
  45054. this._rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  45055. }
  45056. }
  45057. Gamepad.prototype.onleftstickchanged = function (callback) {
  45058. this._onleftstickchanged = callback;
  45059. };
  45060. Gamepad.prototype.onrightstickchanged = function (callback) {
  45061. this._onrightstickchanged = callback;
  45062. };
  45063. Object.defineProperty(Gamepad.prototype, "leftStick", {
  45064. get: function () {
  45065. return this._leftStick;
  45066. },
  45067. set: function (newValues) {
  45068. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  45069. this._onleftstickchanged(newValues);
  45070. }
  45071. this._leftStick = newValues;
  45072. },
  45073. enumerable: true,
  45074. configurable: true
  45075. });
  45076. Object.defineProperty(Gamepad.prototype, "rightStick", {
  45077. get: function () {
  45078. return this._rightStick;
  45079. },
  45080. set: function (newValues) {
  45081. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  45082. this._onrightstickchanged(newValues);
  45083. }
  45084. this._rightStick = newValues;
  45085. },
  45086. enumerable: true,
  45087. configurable: true
  45088. });
  45089. Gamepad.prototype.update = function () {
  45090. if (this._leftStick) {
  45091. this.leftStick = { x: this.browserGamepad.axes[0], y: this.browserGamepad.axes[1] };
  45092. }
  45093. if (this._rightStick) {
  45094. this.rightStick = { x: this.browserGamepad.axes[2], y: this.browserGamepad.axes[3] };
  45095. }
  45096. };
  45097. return Gamepad;
  45098. }());
  45099. BABYLON.Gamepad = Gamepad;
  45100. var GenericPad = (function (_super) {
  45101. __extends(GenericPad, _super);
  45102. function GenericPad(id, index, gamepad) {
  45103. _super.call(this, id, index, gamepad);
  45104. this.id = id;
  45105. this.index = index;
  45106. this.gamepad = gamepad;
  45107. this._buttons = new Array(gamepad.buttons.length);
  45108. }
  45109. GenericPad.prototype.onbuttondown = function (callback) {
  45110. this._onbuttondown = callback;
  45111. };
  45112. GenericPad.prototype.onbuttonup = function (callback) {
  45113. this._onbuttonup = callback;
  45114. };
  45115. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  45116. if (newValue !== currentValue) {
  45117. if (this._onbuttondown && newValue === 1) {
  45118. this._onbuttondown(buttonIndex);
  45119. }
  45120. if (this._onbuttonup && newValue === 0) {
  45121. this._onbuttonup(buttonIndex);
  45122. }
  45123. }
  45124. return newValue;
  45125. };
  45126. GenericPad.prototype.update = function () {
  45127. _super.prototype.update.call(this);
  45128. for (var index = 0; index < this._buttons.length; index++) {
  45129. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  45130. }
  45131. };
  45132. return GenericPad;
  45133. }(Gamepad));
  45134. BABYLON.GenericPad = GenericPad;
  45135. (function (Xbox360Button) {
  45136. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  45137. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  45138. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  45139. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  45140. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  45141. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  45142. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  45143. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  45144. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  45145. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  45146. })(BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  45147. var Xbox360Button = BABYLON.Xbox360Button;
  45148. (function (Xbox360Dpad) {
  45149. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  45150. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  45151. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  45152. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  45153. })(BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  45154. var Xbox360Dpad = BABYLON.Xbox360Dpad;
  45155. var Xbox360Pad = (function (_super) {
  45156. __extends(Xbox360Pad, _super);
  45157. function Xbox360Pad() {
  45158. _super.apply(this, arguments);
  45159. this._leftTrigger = 0;
  45160. this._rightTrigger = 0;
  45161. this._buttonA = 0;
  45162. this._buttonB = 0;
  45163. this._buttonX = 0;
  45164. this._buttonY = 0;
  45165. this._buttonBack = 0;
  45166. this._buttonStart = 0;
  45167. this._buttonLB = 0;
  45168. this._buttonRB = 0;
  45169. this._buttonLeftStick = 0;
  45170. this._buttonRightStick = 0;
  45171. this._dPadUp = 0;
  45172. this._dPadDown = 0;
  45173. this._dPadLeft = 0;
  45174. this._dPadRight = 0;
  45175. }
  45176. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  45177. this._onlefttriggerchanged = callback;
  45178. };
  45179. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  45180. this._onrighttriggerchanged = callback;
  45181. };
  45182. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  45183. get: function () {
  45184. return this._leftTrigger;
  45185. },
  45186. set: function (newValue) {
  45187. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  45188. this._onlefttriggerchanged(newValue);
  45189. }
  45190. this._leftTrigger = newValue;
  45191. },
  45192. enumerable: true,
  45193. configurable: true
  45194. });
  45195. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  45196. get: function () {
  45197. return this._rightTrigger;
  45198. },
  45199. set: function (newValue) {
  45200. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  45201. this._onrighttriggerchanged(newValue);
  45202. }
  45203. this._rightTrigger = newValue;
  45204. },
  45205. enumerable: true,
  45206. configurable: true
  45207. });
  45208. Xbox360Pad.prototype.onbuttondown = function (callback) {
  45209. this._onbuttondown = callback;
  45210. };
  45211. Xbox360Pad.prototype.onbuttonup = function (callback) {
  45212. this._onbuttonup = callback;
  45213. };
  45214. Xbox360Pad.prototype.ondpaddown = function (callback) {
  45215. this._ondpaddown = callback;
  45216. };
  45217. Xbox360Pad.prototype.ondpadup = function (callback) {
  45218. this._ondpadup = callback;
  45219. };
  45220. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  45221. if (newValue !== currentValue) {
  45222. if (this._onbuttondown && newValue === 1) {
  45223. this._onbuttondown(buttonType);
  45224. }
  45225. if (this._onbuttonup && newValue === 0) {
  45226. this._onbuttonup(buttonType);
  45227. }
  45228. }
  45229. return newValue;
  45230. };
  45231. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  45232. if (newValue !== currentValue) {
  45233. if (this._ondpaddown && newValue === 1) {
  45234. this._ondpaddown(buttonType);
  45235. }
  45236. if (this._ondpadup && newValue === 0) {
  45237. this._ondpadup(buttonType);
  45238. }
  45239. }
  45240. return newValue;
  45241. };
  45242. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  45243. get: function () {
  45244. return this._buttonA;
  45245. },
  45246. set: function (value) {
  45247. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  45248. },
  45249. enumerable: true,
  45250. configurable: true
  45251. });
  45252. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  45253. get: function () {
  45254. return this._buttonB;
  45255. },
  45256. set: function (value) {
  45257. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  45258. },
  45259. enumerable: true,
  45260. configurable: true
  45261. });
  45262. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  45263. get: function () {
  45264. return this._buttonX;
  45265. },
  45266. set: function (value) {
  45267. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  45268. },
  45269. enumerable: true,
  45270. configurable: true
  45271. });
  45272. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  45273. get: function () {
  45274. return this._buttonY;
  45275. },
  45276. set: function (value) {
  45277. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  45278. },
  45279. enumerable: true,
  45280. configurable: true
  45281. });
  45282. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  45283. get: function () {
  45284. return this._buttonStart;
  45285. },
  45286. set: function (value) {
  45287. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  45288. },
  45289. enumerable: true,
  45290. configurable: true
  45291. });
  45292. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  45293. get: function () {
  45294. return this._buttonBack;
  45295. },
  45296. set: function (value) {
  45297. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  45298. },
  45299. enumerable: true,
  45300. configurable: true
  45301. });
  45302. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  45303. get: function () {
  45304. return this._buttonLB;
  45305. },
  45306. set: function (value) {
  45307. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  45308. },
  45309. enumerable: true,
  45310. configurable: true
  45311. });
  45312. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  45313. get: function () {
  45314. return this._buttonRB;
  45315. },
  45316. set: function (value) {
  45317. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  45318. },
  45319. enumerable: true,
  45320. configurable: true
  45321. });
  45322. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  45323. get: function () {
  45324. return this._buttonLeftStick;
  45325. },
  45326. set: function (value) {
  45327. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  45328. },
  45329. enumerable: true,
  45330. configurable: true
  45331. });
  45332. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  45333. get: function () {
  45334. return this._buttonRightStick;
  45335. },
  45336. set: function (value) {
  45337. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  45338. },
  45339. enumerable: true,
  45340. configurable: true
  45341. });
  45342. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  45343. get: function () {
  45344. return this._dPadUp;
  45345. },
  45346. set: function (value) {
  45347. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  45348. },
  45349. enumerable: true,
  45350. configurable: true
  45351. });
  45352. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  45353. get: function () {
  45354. return this._dPadDown;
  45355. },
  45356. set: function (value) {
  45357. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  45358. },
  45359. enumerable: true,
  45360. configurable: true
  45361. });
  45362. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  45363. get: function () {
  45364. return this._dPadLeft;
  45365. },
  45366. set: function (value) {
  45367. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  45368. },
  45369. enumerable: true,
  45370. configurable: true
  45371. });
  45372. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  45373. get: function () {
  45374. return this._dPadRight;
  45375. },
  45376. set: function (value) {
  45377. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  45378. },
  45379. enumerable: true,
  45380. configurable: true
  45381. });
  45382. Xbox360Pad.prototype.update = function () {
  45383. _super.prototype.update.call(this);
  45384. this.buttonA = this.browserGamepad.buttons[0].value;
  45385. this.buttonB = this.browserGamepad.buttons[1].value;
  45386. this.buttonX = this.browserGamepad.buttons[2].value;
  45387. this.buttonY = this.browserGamepad.buttons[3].value;
  45388. this.buttonLB = this.browserGamepad.buttons[4].value;
  45389. this.buttonRB = this.browserGamepad.buttons[5].value;
  45390. this.leftTrigger = this.browserGamepad.buttons[6].value;
  45391. this.rightTrigger = this.browserGamepad.buttons[7].value;
  45392. this.buttonBack = this.browserGamepad.buttons[8].value;
  45393. this.buttonStart = this.browserGamepad.buttons[9].value;
  45394. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  45395. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  45396. this.dPadUp = this.browserGamepad.buttons[12].value;
  45397. this.dPadDown = this.browserGamepad.buttons[13].value;
  45398. this.dPadLeft = this.browserGamepad.buttons[14].value;
  45399. this.dPadRight = this.browserGamepad.buttons[15].value;
  45400. };
  45401. return Xbox360Pad;
  45402. }(Gamepad));
  45403. BABYLON.Xbox360Pad = Xbox360Pad;
  45404. })(BABYLON || (BABYLON = {}));
  45405. var BABYLON;
  45406. (function (BABYLON) {
  45407. // We're mainly based on the logic defined into the FreeCamera code
  45408. var GamepadCamera = (function (_super) {
  45409. __extends(GamepadCamera, _super);
  45410. //-- end properties for backward compatibility for inputs
  45411. function GamepadCamera(name, position, scene) {
  45412. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  45413. _super.call(this, name, position, scene);
  45414. }
  45415. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  45416. //-- Begin properties for backward compatibility for inputs
  45417. get: function () {
  45418. var gamepad = this.inputs.attached["gamepad"];
  45419. if (gamepad)
  45420. return gamepad.gamepadAngularSensibility;
  45421. },
  45422. set: function (value) {
  45423. var gamepad = this.inputs.attached["gamepad"];
  45424. if (gamepad)
  45425. gamepad.gamepadAngularSensibility = value;
  45426. },
  45427. enumerable: true,
  45428. configurable: true
  45429. });
  45430. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  45431. get: function () {
  45432. var gamepad = this.inputs.attached["gamepad"];
  45433. if (gamepad)
  45434. return gamepad.gamepadMoveSensibility;
  45435. },
  45436. set: function (value) {
  45437. var gamepad = this.inputs.attached["gamepad"];
  45438. if (gamepad)
  45439. gamepad.gamepadMoveSensibility = value;
  45440. },
  45441. enumerable: true,
  45442. configurable: true
  45443. });
  45444. GamepadCamera.prototype.getTypeName = function () {
  45445. return "GamepadCamera";
  45446. };
  45447. return GamepadCamera;
  45448. }(BABYLON.UniversalCamera));
  45449. BABYLON.GamepadCamera = GamepadCamera;
  45450. })(BABYLON || (BABYLON = {}));
  45451. var BABYLON;
  45452. (function (BABYLON) {
  45453. var Analyser = (function () {
  45454. function Analyser(scene) {
  45455. this.SMOOTHING = 0.75;
  45456. this.FFT_SIZE = 512;
  45457. this.BARGRAPHAMPLITUDE = 256;
  45458. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  45459. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  45460. this._scene = scene;
  45461. this._audioEngine = BABYLON.Engine.audioEngine;
  45462. if (this._audioEngine.canUseWebAudio) {
  45463. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  45464. this._webAudioAnalyser.minDecibels = -140;
  45465. this._webAudioAnalyser.maxDecibels = 0;
  45466. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45467. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  45468. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  45469. }
  45470. }
  45471. Analyser.prototype.getFrequencyBinCount = function () {
  45472. if (this._audioEngine.canUseWebAudio) {
  45473. return this._webAudioAnalyser.frequencyBinCount;
  45474. }
  45475. else {
  45476. return 0;
  45477. }
  45478. };
  45479. Analyser.prototype.getByteFrequencyData = function () {
  45480. if (this._audioEngine.canUseWebAudio) {
  45481. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45482. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45483. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  45484. }
  45485. return this._byteFreqs;
  45486. };
  45487. Analyser.prototype.getByteTimeDomainData = function () {
  45488. if (this._audioEngine.canUseWebAudio) {
  45489. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45490. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45491. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  45492. }
  45493. return this._byteTime;
  45494. };
  45495. Analyser.prototype.getFloatFrequencyData = function () {
  45496. if (this._audioEngine.canUseWebAudio) {
  45497. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  45498. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  45499. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  45500. }
  45501. return this._floatFreqs;
  45502. };
  45503. Analyser.prototype.drawDebugCanvas = function () {
  45504. var _this = this;
  45505. if (this._audioEngine.canUseWebAudio) {
  45506. if (!this._debugCanvas) {
  45507. this._debugCanvas = document.createElement("canvas");
  45508. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  45509. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  45510. this._debugCanvas.style.position = "absolute";
  45511. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  45512. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  45513. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  45514. document.body.appendChild(this._debugCanvas);
  45515. this._registerFunc = function () {
  45516. _this.drawDebugCanvas();
  45517. };
  45518. this._scene.registerBeforeRender(this._registerFunc);
  45519. }
  45520. if (this._registerFunc) {
  45521. var workingArray = this.getByteFrequencyData();
  45522. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  45523. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  45524. // Draw the frequency domain chart.
  45525. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  45526. var value = workingArray[i];
  45527. var percent = value / this.BARGRAPHAMPLITUDE;
  45528. var height = this.DEBUGCANVASSIZE.height * percent;
  45529. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  45530. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  45531. var hue = i / this.getFrequencyBinCount() * 360;
  45532. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  45533. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  45534. }
  45535. }
  45536. }
  45537. };
  45538. Analyser.prototype.stopDebugCanvas = function () {
  45539. if (this._debugCanvas) {
  45540. this._scene.unregisterBeforeRender(this._registerFunc);
  45541. this._registerFunc = null;
  45542. document.body.removeChild(this._debugCanvas);
  45543. this._debugCanvas = null;
  45544. this._debugCanvasContext = null;
  45545. }
  45546. };
  45547. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  45548. if (this._audioEngine.canUseWebAudio) {
  45549. inputAudioNode.connect(this._webAudioAnalyser);
  45550. this._webAudioAnalyser.connect(outputAudioNode);
  45551. }
  45552. };
  45553. Analyser.prototype.dispose = function () {
  45554. if (this._audioEngine.canUseWebAudio) {
  45555. this._webAudioAnalyser.disconnect();
  45556. }
  45557. };
  45558. return Analyser;
  45559. }());
  45560. BABYLON.Analyser = Analyser;
  45561. })(BABYLON || (BABYLON = {}));
  45562. var BABYLON;
  45563. (function (BABYLON) {
  45564. var DepthRenderer = (function () {
  45565. function DepthRenderer(scene, type) {
  45566. var _this = this;
  45567. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  45568. this._viewMatrix = BABYLON.Matrix.Zero();
  45569. this._projectionMatrix = BABYLON.Matrix.Zero();
  45570. this._transformMatrix = BABYLON.Matrix.Zero();
  45571. this._worldViewProjection = BABYLON.Matrix.Zero();
  45572. this._scene = scene;
  45573. var engine = scene.getEngine();
  45574. // Render target
  45575. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  45576. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45577. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45578. this._depthMap.refreshRate = 1;
  45579. this._depthMap.renderParticles = false;
  45580. this._depthMap.renderList = null;
  45581. // set default depth value to 1.0 (far away)
  45582. this._depthMap.onClearObservable.add(function (engine) {
  45583. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  45584. });
  45585. // Custom render function
  45586. var renderSubMesh = function (subMesh) {
  45587. var mesh = subMesh.getRenderingMesh();
  45588. var scene = _this._scene;
  45589. var engine = scene.getEngine();
  45590. // Culling
  45591. engine.setState(subMesh.getMaterial().backFaceCulling);
  45592. // Managing instances
  45593. var batch = mesh._getInstancesRenderList(subMesh._id);
  45594. if (batch.mustReturn) {
  45595. return;
  45596. }
  45597. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  45598. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  45599. engine.enableEffect(_this._effect);
  45600. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  45601. var material = subMesh.getMaterial();
  45602. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  45603. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  45604. // Alpha test
  45605. if (material && material.needAlphaTesting()) {
  45606. var alphaTexture = material.getAlphaTestTexture();
  45607. _this._effect.setTexture("diffuseSampler", alphaTexture);
  45608. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45609. }
  45610. // Bones
  45611. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45612. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45613. }
  45614. // Draw
  45615. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  45616. }
  45617. };
  45618. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  45619. var index;
  45620. for (index = 0; index < opaqueSubMeshes.length; index++) {
  45621. renderSubMesh(opaqueSubMeshes.data[index]);
  45622. }
  45623. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  45624. renderSubMesh(alphaTestSubMeshes.data[index]);
  45625. }
  45626. };
  45627. }
  45628. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  45629. var material = subMesh.getMaterial();
  45630. if (material.disableDepthWrite) {
  45631. return false;
  45632. }
  45633. var defines = [];
  45634. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45635. var mesh = subMesh.getMesh();
  45636. var scene = mesh.getScene();
  45637. // Alpha test
  45638. if (material && material.needAlphaTesting()) {
  45639. defines.push("#define ALPHATEST");
  45640. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45641. attribs.push(BABYLON.VertexBuffer.UVKind);
  45642. defines.push("#define UV1");
  45643. }
  45644. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45645. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45646. defines.push("#define UV2");
  45647. }
  45648. }
  45649. // Bones
  45650. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45651. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45652. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45653. if (mesh.numBoneInfluencers > 4) {
  45654. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45655. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45656. }
  45657. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45658. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45659. }
  45660. else {
  45661. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45662. }
  45663. // Instances
  45664. if (useInstances) {
  45665. defines.push("#define INSTANCES");
  45666. attribs.push("world0");
  45667. attribs.push("world1");
  45668. attribs.push("world2");
  45669. attribs.push("world3");
  45670. }
  45671. // Get correct effect
  45672. var join = defines.join("\n");
  45673. if (this._cachedDefines !== join) {
  45674. this._cachedDefines = join;
  45675. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  45676. }
  45677. return this._effect.isReady();
  45678. };
  45679. DepthRenderer.prototype.getDepthMap = function () {
  45680. return this._depthMap;
  45681. };
  45682. // Methods
  45683. DepthRenderer.prototype.dispose = function () {
  45684. this._depthMap.dispose();
  45685. };
  45686. return DepthRenderer;
  45687. }());
  45688. BABYLON.DepthRenderer = DepthRenderer;
  45689. })(BABYLON || (BABYLON = {}));
  45690. var BABYLON;
  45691. (function (BABYLON) {
  45692. var SSAORenderingPipeline = (function (_super) {
  45693. __extends(SSAORenderingPipeline, _super);
  45694. /**
  45695. * @constructor
  45696. * @param {string} name - The rendering pipeline name
  45697. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  45698. * @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 }
  45699. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  45700. */
  45701. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  45702. var _this = this;
  45703. _super.call(this, scene.getEngine(), name);
  45704. // Members
  45705. /**
  45706. * The PassPostProcess id in the pipeline that contains the original scene color
  45707. * @type {string}
  45708. */
  45709. this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  45710. /**
  45711. * The SSAO PostProcess id in the pipeline
  45712. * @type {string}
  45713. */
  45714. this.SSAORenderEffect = "SSAORenderEffect";
  45715. /**
  45716. * The horizontal blur PostProcess id in the pipeline
  45717. * @type {string}
  45718. */
  45719. this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  45720. /**
  45721. * The vertical blur PostProcess id in the pipeline
  45722. * @type {string}
  45723. */
  45724. this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  45725. /**
  45726. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  45727. * @type {string}
  45728. */
  45729. this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  45730. /**
  45731. * The output strength of the SSAO post-process. Default value is 1.0.
  45732. * @type {number}
  45733. */
  45734. this.totalStrength = 1.0;
  45735. /**
  45736. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  45737. * @type {number}
  45738. */
  45739. this.radius = 0.0001;
  45740. /**
  45741. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  45742. * Must not be equal to fallOff and superior to fallOff.
  45743. * Default value is 0.975
  45744. * @type {number}
  45745. */
  45746. this.area = 0.0075;
  45747. /**
  45748. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  45749. * Must not be equal to area and inferior to area.
  45750. * Default value is 0.0
  45751. * @type {number}
  45752. */
  45753. this.fallOff = 0.000001;
  45754. /**
  45755. * The base color of the SSAO post-process
  45756. * The final result is "base + ssao" between [0, 1]
  45757. * @type {number}
  45758. */
  45759. this.base = 0.5;
  45760. this._firstUpdate = true;
  45761. this._scene = scene;
  45762. // Set up assets
  45763. this._createRandomTexture();
  45764. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  45765. var ssaoRatio = ratio.ssaoRatio || ratio;
  45766. var combineRatio = ratio.combineRatio || ratio;
  45767. this._ratio = {
  45768. ssaoRatio: ssaoRatio,
  45769. combineRatio: combineRatio
  45770. };
  45771. this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  45772. this._createSSAOPostProcess(ssaoRatio);
  45773. this._createBlurPostProcess(ssaoRatio);
  45774. this._createSSAOCombinePostProcess(combineRatio);
  45775. // Set up pipeline
  45776. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  45777. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  45778. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  45779. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  45780. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  45781. // Finish
  45782. scene.postProcessRenderPipelineManager.addPipeline(this);
  45783. if (cameras)
  45784. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  45785. }
  45786. // Public Methods
  45787. /**
  45788. * Returns the horizontal blur PostProcess
  45789. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  45790. */
  45791. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  45792. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  45793. return null;
  45794. };
  45795. /**
  45796. * Returns the vertical blur PostProcess
  45797. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  45798. */
  45799. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  45800. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  45801. return null;
  45802. };
  45803. /**
  45804. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  45805. */
  45806. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  45807. if (disableDepthRender === void 0) { disableDepthRender = false; }
  45808. for (var i = 0; i < this._scene.cameras.length; i++) {
  45809. var camera = this._scene.cameras[i];
  45810. this._originalColorPostProcess.dispose(camera);
  45811. this._ssaoPostProcess.dispose(camera);
  45812. this._blurHPostProcess.dispose(camera);
  45813. this._blurVPostProcess.dispose(camera);
  45814. this._ssaoCombinePostProcess.dispose(camera);
  45815. }
  45816. this._randomTexture.dispose();
  45817. if (disableDepthRender)
  45818. this._scene.disableDepthRenderer();
  45819. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  45820. };
  45821. // Private Methods
  45822. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  45823. var _this = this;
  45824. /*
  45825. var samplerOffsets = [
  45826. -8.0, -6.0, -4.0, -2.0,
  45827. 0.0,
  45828. 2.0, 4.0, 6.0, 8.0
  45829. ];
  45830. */
  45831. var samples = 16;
  45832. var samplerOffsets = [];
  45833. for (var i = -8; i < 8; i++) {
  45834. samplerOffsets.push(i * 2);
  45835. }
  45836. 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");
  45837. this._blurHPostProcess.onApply = function (effect) {
  45838. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  45839. effect.setTexture("depthSampler", _this._depthTexture);
  45840. if (_this._firstUpdate) {
  45841. effect.setArray("samplerOffsets", samplerOffsets);
  45842. }
  45843. };
  45844. 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");
  45845. this._blurVPostProcess.onApply = function (effect) {
  45846. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  45847. effect.setTexture("depthSampler", _this._depthTexture);
  45848. if (_this._firstUpdate) {
  45849. effect.setArray("samplerOffsets", samplerOffsets);
  45850. _this._firstUpdate = false;
  45851. }
  45852. };
  45853. };
  45854. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  45855. var _this = this;
  45856. var numSamples = 16;
  45857. var sampleSphere = [
  45858. 0.5381, 0.1856, -0.4319,
  45859. 0.1379, 0.2486, 0.4430,
  45860. 0.3371, 0.5679, -0.0057,
  45861. -0.6999, -0.0451, -0.0019,
  45862. 0.0689, -0.1598, -0.8547,
  45863. 0.0560, 0.0069, -0.1843,
  45864. -0.0146, 0.1402, 0.0762,
  45865. 0.0100, -0.1924, -0.0344,
  45866. -0.3577, -0.5301, -0.4358,
  45867. -0.3169, 0.1063, 0.0158,
  45868. 0.0103, -0.5869, 0.0046,
  45869. -0.0897, -0.4940, 0.3287,
  45870. 0.7119, -0.0154, -0.0918,
  45871. -0.0533, 0.0596, -0.5411,
  45872. 0.0352, -0.0631, 0.5460,
  45873. -0.4776, 0.2847, -0.0271
  45874. ];
  45875. var samplesFactor = 1.0 / numSamples;
  45876. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  45877. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  45878. "area", "fallOff", "base", "range", "viewport"
  45879. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  45880. var viewport = new BABYLON.Vector2(0, 0);
  45881. this._ssaoPostProcess.onApply = function (effect) {
  45882. if (_this._firstUpdate) {
  45883. effect.setArray3("sampleSphere", sampleSphere);
  45884. effect.setFloat("samplesFactor", samplesFactor);
  45885. effect.setFloat("randTextureTiles", 4.0);
  45886. }
  45887. effect.setFloat("totalStrength", _this.totalStrength);
  45888. effect.setFloat("radius", _this.radius);
  45889. effect.setFloat("area", _this.area);
  45890. effect.setFloat("fallOff", _this.fallOff);
  45891. effect.setFloat("base", _this.base);
  45892. effect.setTexture("textureSampler", _this._depthTexture);
  45893. effect.setTexture("randomSampler", _this._randomTexture);
  45894. };
  45895. };
  45896. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  45897. var _this = this;
  45898. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  45899. this._ssaoCombinePostProcess.onApply = function (effect) {
  45900. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  45901. };
  45902. };
  45903. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  45904. var size = 512;
  45905. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  45906. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  45907. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  45908. var context = this._randomTexture.getContext();
  45909. var rand = function (min, max) {
  45910. return Math.random() * (max - min) + min;
  45911. };
  45912. var randVector = BABYLON.Vector3.Zero();
  45913. for (var x = 0; x < size; x++) {
  45914. for (var y = 0; y < size; y++) {
  45915. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  45916. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  45917. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  45918. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  45919. context.fillRect(x, y, 1, 1);
  45920. }
  45921. }
  45922. this._randomTexture.update(false);
  45923. };
  45924. __decorate([
  45925. BABYLON.serialize()
  45926. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  45927. __decorate([
  45928. BABYLON.serialize()
  45929. ], SSAORenderingPipeline.prototype, "radius", void 0);
  45930. __decorate([
  45931. BABYLON.serialize()
  45932. ], SSAORenderingPipeline.prototype, "area", void 0);
  45933. __decorate([
  45934. BABYLON.serialize()
  45935. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  45936. __decorate([
  45937. BABYLON.serialize()
  45938. ], SSAORenderingPipeline.prototype, "base", void 0);
  45939. __decorate([
  45940. BABYLON.serialize()
  45941. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  45942. return SSAORenderingPipeline;
  45943. }(BABYLON.PostProcessRenderPipeline));
  45944. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  45945. })(BABYLON || (BABYLON = {}));
  45946. var BABYLON;
  45947. (function (BABYLON) {
  45948. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  45949. var VolumetricLightScatteringPostProcess = (function (_super) {
  45950. __extends(VolumetricLightScatteringPostProcess, _super);
  45951. /**
  45952. * @constructor
  45953. * @param {string} name - The post-process name
  45954. * @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)
  45955. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  45956. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  45957. * @param {number} samples - The post-process quality, default 100
  45958. * @param {number} samplingMode - The post-process filtering mode
  45959. * @param {BABYLON.Engine} engine - The babylon engine
  45960. * @param {boolean} reusable - If the post-process is reusable
  45961. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  45962. */
  45963. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  45964. var _this = this;
  45965. if (samples === void 0) { samples = 100; }
  45966. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45967. _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples);
  45968. this._screenCoordinates = BABYLON.Vector2.Zero();
  45969. /**
  45970. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  45971. * @type {Vector3}
  45972. */
  45973. this.customMeshPosition = BABYLON.Vector3.Zero();
  45974. /**
  45975. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  45976. * @type {boolean}
  45977. */
  45978. this.useCustomMeshPosition = false;
  45979. /**
  45980. * If the post-process should inverse the light scattering direction
  45981. * @type {boolean}
  45982. */
  45983. this.invert = true;
  45984. /**
  45985. * Array containing the excluded meshes not rendered in the internal pass
  45986. */
  45987. this.excludedMeshes = new Array();
  45988. /**
  45989. * Controls the overall intensity of the post-process
  45990. * @type {number}
  45991. */
  45992. this.exposure = 0.3;
  45993. /**
  45994. * Dissipates each sample's contribution in range [0, 1]
  45995. * @type {number}
  45996. */
  45997. this.decay = 0.96815;
  45998. /**
  45999. * Controls the overall intensity of each sample
  46000. * @type {number}
  46001. */
  46002. this.weight = 0.58767;
  46003. /**
  46004. * Controls the density of each sample
  46005. * @type {number}
  46006. */
  46007. this.density = 0.926;
  46008. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  46009. var engine = scene.getEngine();
  46010. this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  46011. // Configure mesh
  46012. this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  46013. // Configure
  46014. this._createPass(scene, ratio.passRatio || ratio);
  46015. this.onActivate = function (camera) {
  46016. if (!_this.isSupported) {
  46017. _this.dispose(camera);
  46018. }
  46019. _this.onActivate = null;
  46020. };
  46021. this.onApplyObservable.add(function (effect) {
  46022. _this._updateMeshScreenCoordinates(scene);
  46023. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  46024. effect.setFloat("exposure", _this.exposure);
  46025. effect.setFloat("decay", _this.decay);
  46026. effect.setFloat("weight", _this.weight);
  46027. effect.setFloat("density", _this.density);
  46028. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  46029. });
  46030. }
  46031. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  46032. get: function () {
  46033. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  46034. return false;
  46035. },
  46036. set: function (useDiffuseColor) {
  46037. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  46038. },
  46039. enumerable: true,
  46040. configurable: true
  46041. });
  46042. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  46043. var mesh = subMesh.getMesh();
  46044. // Render this.mesh as default
  46045. if (mesh === this.mesh) {
  46046. return mesh.material.isReady(mesh);
  46047. }
  46048. var defines = [];
  46049. var attribs = [BABYLON.VertexBuffer.PositionKind];
  46050. var material = subMesh.getMaterial();
  46051. var needUV = false;
  46052. // Alpha test
  46053. if (material) {
  46054. if (material.needAlphaTesting()) {
  46055. defines.push("#define ALPHATEST");
  46056. }
  46057. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  46058. attribs.push(BABYLON.VertexBuffer.UVKind);
  46059. defines.push("#define UV1");
  46060. }
  46061. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  46062. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  46063. defines.push("#define UV2");
  46064. }
  46065. }
  46066. // Bones
  46067. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46068. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  46069. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  46070. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  46071. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  46072. }
  46073. else {
  46074. defines.push("#define NUM_BONE_INFLUENCERS 0");
  46075. }
  46076. // Instances
  46077. if (useInstances) {
  46078. defines.push("#define INSTANCES");
  46079. attribs.push("world0");
  46080. attribs.push("world1");
  46081. attribs.push("world2");
  46082. attribs.push("world3");
  46083. }
  46084. // Get correct effect
  46085. var join = defines.join("\n");
  46086. if (this._cachedDefines !== join) {
  46087. this._cachedDefines = join;
  46088. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  46089. }
  46090. return this._volumetricLightScatteringPass.isReady();
  46091. };
  46092. /**
  46093. * Sets the new light position for light scattering effect
  46094. * @param {BABYLON.Vector3} The new custom light position
  46095. */
  46096. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  46097. this.customMeshPosition = position;
  46098. };
  46099. /**
  46100. * Returns the light position for light scattering effect
  46101. * @return {BABYLON.Vector3} The custom light position
  46102. */
  46103. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  46104. return this.customMeshPosition;
  46105. };
  46106. /**
  46107. * Disposes the internal assets and detaches the post-process from the camera
  46108. */
  46109. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  46110. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  46111. if (rttIndex !== -1) {
  46112. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  46113. }
  46114. this._volumetricLightScatteringRTT.dispose();
  46115. _super.prototype.dispose.call(this, camera);
  46116. };
  46117. /**
  46118. * Returns the render target texture used by the post-process
  46119. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  46120. */
  46121. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  46122. return this._volumetricLightScatteringRTT;
  46123. };
  46124. // Private methods
  46125. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  46126. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  46127. return true;
  46128. }
  46129. return false;
  46130. };
  46131. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  46132. var _this = this;
  46133. var engine = scene.getEngine();
  46134. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  46135. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46136. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46137. this._volumetricLightScatteringRTT.renderList = null;
  46138. this._volumetricLightScatteringRTT.renderParticles = false;
  46139. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  46140. // Custom render function for submeshes
  46141. var renderSubMesh = function (subMesh) {
  46142. var mesh = subMesh.getRenderingMesh();
  46143. if (_this._meshExcluded(mesh)) {
  46144. return;
  46145. }
  46146. var scene = mesh.getScene();
  46147. var engine = scene.getEngine();
  46148. // Culling
  46149. engine.setState(subMesh.getMaterial().backFaceCulling);
  46150. // Managing instances
  46151. var batch = mesh._getInstancesRenderList(subMesh._id);
  46152. if (batch.mustReturn) {
  46153. return;
  46154. }
  46155. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  46156. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  46157. var effect = _this._volumetricLightScatteringPass;
  46158. if (mesh === _this.mesh) {
  46159. effect = subMesh.getMaterial().getEffect();
  46160. }
  46161. engine.enableEffect(effect);
  46162. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  46163. if (mesh === _this.mesh) {
  46164. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  46165. }
  46166. else {
  46167. var material = subMesh.getMaterial();
  46168. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  46169. // Alpha test
  46170. if (material && material.needAlphaTesting()) {
  46171. var alphaTexture = material.getAlphaTestTexture();
  46172. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  46173. if (alphaTexture) {
  46174. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  46175. }
  46176. }
  46177. // Bones
  46178. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  46179. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  46180. }
  46181. }
  46182. // Draw
  46183. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  46184. }
  46185. };
  46186. // Render target texture callbacks
  46187. var savedSceneClearColor;
  46188. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  46189. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  46190. savedSceneClearColor = scene.clearColor;
  46191. scene.clearColor = sceneClearColor;
  46192. });
  46193. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  46194. scene.clearColor = savedSceneClearColor;
  46195. });
  46196. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  46197. var engine = scene.getEngine();
  46198. var index;
  46199. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46200. renderSubMesh(opaqueSubMeshes.data[index]);
  46201. }
  46202. engine.setAlphaTesting(true);
  46203. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46204. renderSubMesh(alphaTestSubMeshes.data[index]);
  46205. }
  46206. engine.setAlphaTesting(false);
  46207. if (transparentSubMeshes.length) {
  46208. // Sort sub meshes
  46209. for (index = 0; index < transparentSubMeshes.length; index++) {
  46210. var submesh = transparentSubMeshes.data[index];
  46211. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  46212. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  46213. }
  46214. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  46215. sortedArray.sort(function (a, b) {
  46216. // Alpha index first
  46217. if (a._alphaIndex > b._alphaIndex) {
  46218. return 1;
  46219. }
  46220. if (a._alphaIndex < b._alphaIndex) {
  46221. return -1;
  46222. }
  46223. // Then distance to camera
  46224. if (a._distanceToCamera < b._distanceToCamera) {
  46225. return 1;
  46226. }
  46227. if (a._distanceToCamera > b._distanceToCamera) {
  46228. return -1;
  46229. }
  46230. return 0;
  46231. });
  46232. // Render sub meshes
  46233. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  46234. for (index = 0; index < sortedArray.length; index++) {
  46235. renderSubMesh(sortedArray[index]);
  46236. }
  46237. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46238. }
  46239. };
  46240. };
  46241. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  46242. var transform = scene.getTransformMatrix();
  46243. var meshPosition;
  46244. if (this.useCustomMeshPosition) {
  46245. meshPosition = this.customMeshPosition;
  46246. }
  46247. else if (this.attachedNode) {
  46248. meshPosition = this.attachedNode.position;
  46249. }
  46250. else {
  46251. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  46252. }
  46253. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  46254. this._screenCoordinates.x = pos.x / this._viewPort.width;
  46255. this._screenCoordinates.y = pos.y / this._viewPort.height;
  46256. if (this.invert)
  46257. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  46258. };
  46259. // Static methods
  46260. /**
  46261. * Creates a default mesh for the Volumeric Light Scattering post-process
  46262. * @param {string} The mesh name
  46263. * @param {BABYLON.Scene} The scene where to create the mesh
  46264. * @return {BABYLON.Mesh} the default mesh
  46265. */
  46266. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  46267. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  46268. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  46269. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  46270. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  46271. mesh.material = material;
  46272. return mesh;
  46273. };
  46274. __decorate([
  46275. BABYLON.serializeAsVector3()
  46276. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  46277. __decorate([
  46278. BABYLON.serialize()
  46279. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  46280. __decorate([
  46281. BABYLON.serialize()
  46282. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  46283. __decorate([
  46284. BABYLON.serializeAsMeshReference()
  46285. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  46286. __decorate([
  46287. BABYLON.serialize()
  46288. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  46289. __decorate([
  46290. BABYLON.serialize()
  46291. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  46292. __decorate([
  46293. BABYLON.serialize()
  46294. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  46295. __decorate([
  46296. BABYLON.serialize()
  46297. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  46298. __decorate([
  46299. BABYLON.serialize()
  46300. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  46301. return VolumetricLightScatteringPostProcess;
  46302. }(BABYLON.PostProcess));
  46303. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  46304. })(BABYLON || (BABYLON = {}));
  46305. // BABYLON.JS Chromatic Aberration GLSL Shader
  46306. // Author: Olivier Guyot
  46307. // Separates very slightly R, G and B colors on the edges of the screen
  46308. // Inspired by Francois Tarlier & Martins Upitis
  46309. var BABYLON;
  46310. (function (BABYLON) {
  46311. var LensRenderingPipeline = (function (_super) {
  46312. __extends(LensRenderingPipeline, _super);
  46313. /**
  46314. * @constructor
  46315. *
  46316. * Effect parameters are as follow:
  46317. * {
  46318. * chromatic_aberration: number; // from 0 to x (1 for realism)
  46319. * edge_blur: number; // from 0 to x (1 for realism)
  46320. * distortion: number; // from 0 to x (1 for realism)
  46321. * grain_amount: number; // from 0 to 1
  46322. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  46323. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  46324. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  46325. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  46326. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  46327. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  46328. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  46329. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  46330. * }
  46331. * Note: if an effect parameter is unset, effect is disabled
  46332. *
  46333. * @param {string} name - The rendering pipeline name
  46334. * @param {object} parameters - An object containing all parameters (see above)
  46335. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46336. * @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)
  46337. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46338. */
  46339. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  46340. var _this = this;
  46341. if (ratio === void 0) { ratio = 1.0; }
  46342. _super.call(this, scene.getEngine(), name);
  46343. // Lens effects can be of the following:
  46344. // - chromatic aberration (slight shift of RGB colors)
  46345. // - blur on the edge of the lens
  46346. // - lens distortion
  46347. // - depth-of-field blur & highlights enhancing
  46348. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  46349. // - grain effect (noise or custom texture)
  46350. // Two additional texture samplers are needed:
  46351. // - depth map (for depth-of-field)
  46352. // - grain texture
  46353. /**
  46354. * The chromatic aberration PostProcess id in the pipeline
  46355. * @type {string}
  46356. */
  46357. this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  46358. /**
  46359. * The highlights enhancing PostProcess id in the pipeline
  46360. * @type {string}
  46361. */
  46362. this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  46363. /**
  46364. * The depth-of-field PostProcess id in the pipeline
  46365. * @type {string}
  46366. */
  46367. this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  46368. this._scene = scene;
  46369. // Fetch texture samplers
  46370. this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  46371. if (parameters.grain_texture) {
  46372. this._grainTexture = parameters.grain_texture;
  46373. }
  46374. else {
  46375. this._createGrainTexture();
  46376. }
  46377. // save parameters
  46378. this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  46379. this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  46380. this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  46381. this._distortion = parameters.distortion ? parameters.distortion : 0;
  46382. this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  46383. this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  46384. this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  46385. this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  46386. this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  46387. this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  46388. this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  46389. // Create effects
  46390. this._createChromaticAberrationPostProcess(ratio);
  46391. this._createHighlightsPostProcess(ratio);
  46392. this._createDepthOfFieldPostProcess(ratio / 4);
  46393. // Set up pipeline
  46394. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  46395. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  46396. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  46397. if (this._highlightsGain === -1) {
  46398. this._disableEffect(this.HighlightsEnhancingEffect, null);
  46399. }
  46400. // Finish
  46401. scene.postProcessRenderPipelineManager.addPipeline(this);
  46402. if (cameras) {
  46403. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46404. }
  46405. }
  46406. // public methods (self explanatory)
  46407. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  46408. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  46409. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  46410. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  46411. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  46412. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  46413. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  46414. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  46415. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  46416. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  46417. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  46418. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  46419. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  46420. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  46421. };
  46422. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  46423. this._highlightsPostProcess.updateEffect();
  46424. };
  46425. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  46426. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  46427. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  46428. this._highlightsGain = amount;
  46429. };
  46430. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  46431. if (this._highlightsGain === -1) {
  46432. this._highlightsGain = 1.0;
  46433. }
  46434. this._highlightsThreshold = amount;
  46435. };
  46436. LensRenderingPipeline.prototype.disableHighlights = function () {
  46437. this._highlightsGain = -1;
  46438. };
  46439. /**
  46440. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  46441. */
  46442. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  46443. if (disableDepthRender === void 0) { disableDepthRender = false; }
  46444. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46445. this._chromaticAberrationPostProcess = undefined;
  46446. this._highlightsPostProcess = undefined;
  46447. this._depthOfFieldPostProcess = undefined;
  46448. this._grainTexture.dispose();
  46449. if (disableDepthRender)
  46450. this._scene.disableDepthRenderer();
  46451. };
  46452. // colors shifting and distortion
  46453. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  46454. var _this = this;
  46455. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  46456. [], // samplers
  46457. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46458. this._chromaticAberrationPostProcess.onApply = function (effect) {
  46459. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  46460. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46461. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46462. };
  46463. };
  46464. // highlights enhancing
  46465. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  46466. var _this = this;
  46467. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  46468. [], // samplers
  46469. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  46470. this._highlightsPostProcess.onApply = function (effect) {
  46471. effect.setFloat('gain', _this._highlightsGain);
  46472. effect.setFloat('threshold', _this._highlightsThreshold);
  46473. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  46474. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46475. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46476. };
  46477. };
  46478. // colors shifting and distortion
  46479. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  46480. var _this = this;
  46481. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  46482. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  46483. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  46484. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  46485. this._depthOfFieldPostProcess.onApply = function (effect) {
  46486. effect.setTexture("depthSampler", _this._depthTexture);
  46487. effect.setTexture("grainSampler", _this._grainTexture);
  46488. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  46489. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  46490. effect.setFloat('grain_amount', _this._grainAmount);
  46491. effect.setBool('blur_noise', _this._blurNoise);
  46492. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  46493. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  46494. effect.setFloat('distortion', _this._distortion);
  46495. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  46496. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  46497. effect.setFloat('aperture', _this._dofAperture);
  46498. effect.setFloat('darken', _this._dofDarken);
  46499. effect.setFloat('edge_blur', _this._edgeBlur);
  46500. effect.setBool('highlights', (_this._highlightsGain !== -1));
  46501. effect.setFloat('near', _this._scene.activeCamera.minZ);
  46502. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  46503. };
  46504. };
  46505. // creates a black and white random noise texture, 512x512
  46506. LensRenderingPipeline.prototype._createGrainTexture = function () {
  46507. var size = 512;
  46508. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46509. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46510. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46511. var context = this._grainTexture.getContext();
  46512. var rand = function (min, max) {
  46513. return Math.random() * (max - min) + min;
  46514. };
  46515. var value;
  46516. for (var x = 0; x < size; x++) {
  46517. for (var y = 0; y < size; y++) {
  46518. value = Math.floor(rand(0.42, 0.58) * 255);
  46519. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  46520. context.fillRect(x, y, 1, 1);
  46521. }
  46522. }
  46523. this._grainTexture.update(false);
  46524. };
  46525. return LensRenderingPipeline;
  46526. }(BABYLON.PostProcessRenderPipeline));
  46527. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  46528. })(BABYLON || (BABYLON = {}));
  46529. //
  46530. // This post-process allows the modification of rendered colors by using
  46531. // a 'look-up table' (LUT). This effect is also called Color Grading.
  46532. //
  46533. // The object needs to be provided an url to a texture containing the color
  46534. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  46535. // Use an image editing software to tweak the LUT to match your needs.
  46536. //
  46537. // For an example of a color LUT, see here:
  46538. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  46539. // For explanations on color grading, see here:
  46540. // http://udn.epicgames.com/Three/ColorGrading.html
  46541. //
  46542. var BABYLON;
  46543. (function (BABYLON) {
  46544. var ColorCorrectionPostProcess = (function (_super) {
  46545. __extends(ColorCorrectionPostProcess, _super);
  46546. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  46547. var _this = this;
  46548. _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable);
  46549. this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  46550. this._colorTableTexture.anisotropicFilteringLevel = 1;
  46551. this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46552. this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46553. this.onApply = function (effect) {
  46554. effect.setTexture("colorTable", _this._colorTableTexture);
  46555. };
  46556. }
  46557. return ColorCorrectionPostProcess;
  46558. }(BABYLON.PostProcess));
  46559. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  46560. })(BABYLON || (BABYLON = {}));
  46561. var BABYLON;
  46562. (function (BABYLON) {
  46563. var AnaglyphFreeCamera = (function (_super) {
  46564. __extends(AnaglyphFreeCamera, _super);
  46565. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  46566. _super.call(this, name, position, scene);
  46567. this.interaxialDistance = interaxialDistance;
  46568. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46569. }
  46570. AnaglyphFreeCamera.prototype.getTypeName = function () {
  46571. return "AnaglyphFreeCamera";
  46572. };
  46573. return AnaglyphFreeCamera;
  46574. }(BABYLON.FreeCamera));
  46575. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  46576. var AnaglyphArcRotateCamera = (function (_super) {
  46577. __extends(AnaglyphArcRotateCamera, _super);
  46578. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  46579. _super.call(this, name, alpha, beta, radius, target, scene);
  46580. this.interaxialDistance = interaxialDistance;
  46581. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46582. }
  46583. AnaglyphArcRotateCamera.prototype.getTypeName = function () {
  46584. return "AnaglyphArcRotateCamera";
  46585. };
  46586. return AnaglyphArcRotateCamera;
  46587. }(BABYLON.ArcRotateCamera));
  46588. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  46589. var AnaglyphGamepadCamera = (function (_super) {
  46590. __extends(AnaglyphGamepadCamera, _super);
  46591. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  46592. _super.call(this, name, position, scene);
  46593. this.interaxialDistance = interaxialDistance;
  46594. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46595. }
  46596. AnaglyphGamepadCamera.prototype.getTypeName = function () {
  46597. return "AnaglyphGamepadCamera";
  46598. };
  46599. return AnaglyphGamepadCamera;
  46600. }(BABYLON.GamepadCamera));
  46601. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  46602. var AnaglyphUniversalCamera = (function (_super) {
  46603. __extends(AnaglyphUniversalCamera, _super);
  46604. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  46605. _super.call(this, name, position, scene);
  46606. this.interaxialDistance = interaxialDistance;
  46607. this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  46608. }
  46609. AnaglyphUniversalCamera.prototype.getTypeName = function () {
  46610. return "AnaglyphUniversalCamera";
  46611. };
  46612. return AnaglyphUniversalCamera;
  46613. }(BABYLON.UniversalCamera));
  46614. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  46615. var StereoscopicFreeCamera = (function (_super) {
  46616. __extends(StereoscopicFreeCamera, _super);
  46617. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46618. _super.call(this, name, position, scene);
  46619. this.interaxialDistance = interaxialDistance;
  46620. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46621. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46622. }
  46623. StereoscopicFreeCamera.prototype.getTypeName = function () {
  46624. return "StereoscopicFreeCamera";
  46625. };
  46626. return StereoscopicFreeCamera;
  46627. }(BABYLON.FreeCamera));
  46628. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  46629. var StereoscopicArcRotateCamera = (function (_super) {
  46630. __extends(StereoscopicArcRotateCamera, _super);
  46631. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  46632. _super.call(this, name, alpha, beta, radius, target, scene);
  46633. this.interaxialDistance = interaxialDistance;
  46634. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46635. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46636. }
  46637. StereoscopicArcRotateCamera.prototype.getTypeName = function () {
  46638. return "StereoscopicArcRotateCamera";
  46639. };
  46640. return StereoscopicArcRotateCamera;
  46641. }(BABYLON.ArcRotateCamera));
  46642. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  46643. var StereoscopicGamepadCamera = (function (_super) {
  46644. __extends(StereoscopicGamepadCamera, _super);
  46645. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46646. _super.call(this, name, position, scene);
  46647. this.interaxialDistance = interaxialDistance;
  46648. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46649. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46650. }
  46651. StereoscopicGamepadCamera.prototype.getTypeName = function () {
  46652. return "StereoscopicGamepadCamera";
  46653. };
  46654. return StereoscopicGamepadCamera;
  46655. }(BABYLON.GamepadCamera));
  46656. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  46657. var StereoscopicUniversalCamera = (function (_super) {
  46658. __extends(StereoscopicUniversalCamera, _super);
  46659. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  46660. _super.call(this, name, position, scene);
  46661. this.interaxialDistance = interaxialDistance;
  46662. this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  46663. this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  46664. }
  46665. StereoscopicUniversalCamera.prototype.getTypeName = function () {
  46666. return "StereoscopicUniversalCamera";
  46667. };
  46668. return StereoscopicUniversalCamera;
  46669. }(BABYLON.UniversalCamera));
  46670. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  46671. })(BABYLON || (BABYLON = {}));
  46672. var BABYLON;
  46673. (function (BABYLON) {
  46674. var HDRRenderingPipeline = (function (_super) {
  46675. __extends(HDRRenderingPipeline, _super);
  46676. /**
  46677. * @constructor
  46678. * @param {string} name - The rendering pipeline name
  46679. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  46680. * @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)
  46681. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  46682. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  46683. */
  46684. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  46685. var _this = this;
  46686. if (originalPostProcess === void 0) { originalPostProcess = null; }
  46687. _super.call(this, scene.getEngine(), name);
  46688. /**
  46689. * Public members
  46690. */
  46691. // Gaussian Blur
  46692. /**
  46693. * Gaussian blur coefficient
  46694. * @type {number}
  46695. */
  46696. this.gaussCoeff = 0.3;
  46697. /**
  46698. * Gaussian blur mean
  46699. * @type {number}
  46700. */
  46701. this.gaussMean = 1.0;
  46702. /**
  46703. * Gaussian blur standard deviation
  46704. * @type {number}
  46705. */
  46706. this.gaussStandDev = 0.8;
  46707. /**
  46708. * Gaussian blur multiplier. Multiplies the blur effect
  46709. * @type {number}
  46710. */
  46711. this.gaussMultiplier = 4.0;
  46712. // HDR
  46713. /**
  46714. * Exposure, controls the overall intensity of the pipeline
  46715. * @type {number}
  46716. */
  46717. this.exposure = 1.0;
  46718. /**
  46719. * Minimum luminance that the post-process can output. Luminance is >= 0
  46720. * @type {number}
  46721. */
  46722. this.minimumLuminance = 1.0;
  46723. /**
  46724. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  46725. * @type {number}
  46726. */
  46727. this.maximumLuminance = 1e20;
  46728. /**
  46729. * Increase rate for luminance: eye adaptation speed to dark
  46730. * @type {number}
  46731. */
  46732. this.luminanceIncreaserate = 0.5;
  46733. /**
  46734. * Decrease rate for luminance: eye adaptation speed to bright
  46735. * @type {number}
  46736. */
  46737. this.luminanceDecreaseRate = 0.5;
  46738. // Bright pass
  46739. /**
  46740. * Minimum luminance needed to compute HDR
  46741. * @type {number}
  46742. */
  46743. this.brightThreshold = 0.8;
  46744. this._needUpdate = true;
  46745. this._scene = scene;
  46746. // Bright pass
  46747. this._createBrightPassPostProcess(scene, ratio);
  46748. // Down sample X4
  46749. this._createDownSampleX4PostProcess(scene, ratio);
  46750. // Create gaussian blur post-processes
  46751. this._createGaussianBlurPostProcess(scene, ratio);
  46752. // Texture adder
  46753. this._createTextureAdderPostProcess(scene, ratio);
  46754. // Luminance generator
  46755. this._createLuminanceGeneratorPostProcess(scene);
  46756. // HDR
  46757. this._createHDRPostProcess(scene, ratio);
  46758. // Pass postprocess
  46759. if (originalPostProcess === null) {
  46760. this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  46761. }
  46762. else {
  46763. this._originalPostProcess = originalPostProcess;
  46764. }
  46765. // Configure pipeline
  46766. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  46767. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  46768. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  46769. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  46770. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  46771. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  46772. var addDownSamplerPostProcess = function (id) {
  46773. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  46774. };
  46775. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46776. addDownSamplerPostProcess(i);
  46777. }
  46778. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  46779. // Finish
  46780. scene.postProcessRenderPipelineManager.addPipeline(this);
  46781. if (cameras !== null) {
  46782. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  46783. }
  46784. this.update();
  46785. }
  46786. /**
  46787. * Tells the pipeline to update its post-processes
  46788. */
  46789. HDRRenderingPipeline.prototype.update = function () {
  46790. this._needUpdate = true;
  46791. };
  46792. /**
  46793. * Returns the current calculated luminance
  46794. */
  46795. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  46796. return this._hdrCurrentLuminance;
  46797. };
  46798. /**
  46799. * Returns the currently drawn luminance
  46800. */
  46801. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  46802. return this._hdrOutputLuminance;
  46803. };
  46804. /**
  46805. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  46806. */
  46807. HDRRenderingPipeline.prototype.dispose = function () {
  46808. this._originalPostProcess = undefined;
  46809. this._brightPassPostProcess = undefined;
  46810. this._downSampleX4PostProcess = undefined;
  46811. this._guassianBlurHPostProcess = undefined;
  46812. this._guassianBlurVPostProcess = undefined;
  46813. this._textureAdderPostProcess = undefined;
  46814. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  46815. this._downSamplePostProcesses[i] = undefined;
  46816. }
  46817. this._hdrPostProcess = undefined;
  46818. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  46819. };
  46820. /**
  46821. * Creates the HDR post-process and computes the luminance adaptation
  46822. */
  46823. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  46824. var _this = this;
  46825. var hdrLastLuminance = 0.0;
  46826. this._hdrOutputLuminance = -1.0;
  46827. this._hdrCurrentLuminance = 1.0;
  46828. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  46829. this._hdrPostProcess.onApply = function (effect) {
  46830. if (_this._hdrOutputLuminance < 0.0) {
  46831. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46832. }
  46833. else {
  46834. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  46835. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  46836. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  46837. }
  46838. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  46839. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  46840. }
  46841. else {
  46842. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  46843. }
  46844. }
  46845. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  46846. hdrLastLuminance += scene.getEngine().getDeltaTime();
  46847. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46848. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46849. effect.setFloat("exposure", _this.exposure);
  46850. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  46851. _this._needUpdate = false;
  46852. };
  46853. };
  46854. /**
  46855. * Texture Adder post-process
  46856. */
  46857. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  46858. var _this = this;
  46859. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  46860. this._textureAdderPostProcess.onApply = function (effect) {
  46861. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  46862. };
  46863. };
  46864. /**
  46865. * Down sample X4 post-process
  46866. */
  46867. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  46868. var _this = this;
  46869. var downSampleX4Offsets = new Array(32);
  46870. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  46871. this._downSampleX4PostProcess.onApply = function (effect) {
  46872. if (_this._needUpdate) {
  46873. var id = 0;
  46874. for (var i = -2; i < 2; i++) {
  46875. for (var j = -2; j < 2; j++) {
  46876. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  46877. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  46878. id += 2;
  46879. }
  46880. }
  46881. }
  46882. effect.setArray2("dsOffsets", downSampleX4Offsets);
  46883. };
  46884. };
  46885. /**
  46886. * Bright pass post-process
  46887. */
  46888. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  46889. var _this = this;
  46890. var brightOffsets = new Array(8);
  46891. var brightPassCallback = function (effect) {
  46892. if (_this._needUpdate) {
  46893. var sU = (1.0 / _this._brightPassPostProcess.width);
  46894. var sV = (1.0 / _this._brightPassPostProcess.height);
  46895. brightOffsets[0] = -0.5 * sU;
  46896. brightOffsets[1] = 0.5 * sV;
  46897. brightOffsets[2] = 0.5 * sU;
  46898. brightOffsets[3] = 0.5 * sV;
  46899. brightOffsets[4] = -0.5 * sU;
  46900. brightOffsets[5] = -0.5 * sV;
  46901. brightOffsets[6] = 0.5 * sU;
  46902. brightOffsets[7] = -0.5 * sV;
  46903. }
  46904. effect.setArray2("dsOffsets", brightOffsets);
  46905. effect.setFloat("brightThreshold", _this.brightThreshold);
  46906. };
  46907. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  46908. this._brightPassPostProcess.onApply = brightPassCallback;
  46909. };
  46910. /**
  46911. * Luminance generator. Creates the luminance post-process and down sample post-processes
  46912. */
  46913. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  46914. var _this = this;
  46915. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  46916. var luminanceOffsets = new Array(8);
  46917. var downSampleOffsets = new Array(18);
  46918. var halfDestPixelSize;
  46919. this._downSamplePostProcesses = new Array(lumSteps);
  46920. // Utils for luminance
  46921. var luminanceUpdateSourceOffsets = function (width, height) {
  46922. var sU = (1.0 / width);
  46923. var sV = (1.0 / height);
  46924. luminanceOffsets[0] = -0.5 * sU;
  46925. luminanceOffsets[1] = 0.5 * sV;
  46926. luminanceOffsets[2] = 0.5 * sU;
  46927. luminanceOffsets[3] = 0.5 * sV;
  46928. luminanceOffsets[4] = -0.5 * sU;
  46929. luminanceOffsets[5] = -0.5 * sV;
  46930. luminanceOffsets[6] = 0.5 * sU;
  46931. luminanceOffsets[7] = -0.5 * sV;
  46932. };
  46933. var luminanceUpdateDestOffsets = function (width, height) {
  46934. var id = 0;
  46935. for (var x = -1; x < 2; x++) {
  46936. for (var y = -1; y < 2; y++) {
  46937. downSampleOffsets[id] = (x) / width;
  46938. downSampleOffsets[id + 1] = (y) / height;
  46939. id += 2;
  46940. }
  46941. }
  46942. };
  46943. // Luminance callback
  46944. var luminanceCallback = function (effect) {
  46945. if (_this._needUpdate) {
  46946. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  46947. }
  46948. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  46949. effect.setArray2("lumOffsets", luminanceOffsets);
  46950. };
  46951. // Down sample callbacks
  46952. var downSampleCallback = function (indice) {
  46953. var i = indice;
  46954. return function (effect) {
  46955. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  46956. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  46957. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  46958. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  46959. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  46960. effect.setArray2("dsOffsets", downSampleOffsets);
  46961. };
  46962. };
  46963. var downSampleAfterRenderCallback = function (effect) {
  46964. // Unpack result
  46965. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  46966. 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);
  46967. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  46968. };
  46969. // Create luminance post-process
  46970. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  46971. 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);
  46972. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  46973. // Create down sample post-processes
  46974. for (var i = lumSteps - 2; i >= 0; i--) {
  46975. var length = Math.pow(3, i);
  46976. ratio = { width: length, height: length };
  46977. var defines = "#define DOWN_SAMPLE\n";
  46978. if (i === 0) {
  46979. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  46980. }
  46981. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  46982. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  46983. if (i === 0) {
  46984. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  46985. }
  46986. }
  46987. };
  46988. /**
  46989. * Gaussian blur post-processes. Horizontal and Vertical
  46990. */
  46991. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  46992. var _this = this;
  46993. var blurOffsetsW = new Array(9);
  46994. var blurOffsetsH = new Array(9);
  46995. var blurWeights = new Array(9);
  46996. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  46997. // Utils for gaussian blur
  46998. var calculateBlurOffsets = function (height) {
  46999. var lastOutputDimensions = {
  47000. width: scene.getEngine().getRenderWidth(),
  47001. height: scene.getEngine().getRenderHeight()
  47002. };
  47003. for (var i = 0; i < 9; i++) {
  47004. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  47005. if (height) {
  47006. blurOffsetsH[i] = value;
  47007. }
  47008. else {
  47009. blurOffsetsW[i] = value;
  47010. }
  47011. }
  47012. };
  47013. var calculateWeights = function () {
  47014. var x = 0.0;
  47015. for (var i = 0; i < 9; i++) {
  47016. x = (i - 4.0) / 4.0;
  47017. 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));
  47018. }
  47019. };
  47020. // Callback
  47021. var gaussianBlurCallback = function (height) {
  47022. return function (effect) {
  47023. if (_this._needUpdate) {
  47024. calculateWeights();
  47025. calculateBlurOffsets(height);
  47026. }
  47027. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  47028. effect.setArray("blurWeights", blurWeights);
  47029. effect.setFloat("multiplier", _this.gaussMultiplier);
  47030. };
  47031. };
  47032. // Create horizontal gaussian blur post-processes
  47033. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  47034. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  47035. // Create vertical gaussian blur post-process
  47036. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  47037. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  47038. };
  47039. // Luminance generator
  47040. HDRRenderingPipeline.LUM_STEPS = 6;
  47041. return HDRRenderingPipeline;
  47042. }(BABYLON.PostProcessRenderPipeline));
  47043. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  47044. })(BABYLON || (BABYLON = {}));
  47045. var BABYLON;
  47046. (function (BABYLON) {
  47047. var FaceAdjacencies = (function () {
  47048. function FaceAdjacencies() {
  47049. this.edges = new Array();
  47050. this.edgesConnectedCount = 0;
  47051. }
  47052. return FaceAdjacencies;
  47053. }());
  47054. var EdgesRenderer = (function () {
  47055. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  47056. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  47057. if (epsilon === void 0) { epsilon = 0.95; }
  47058. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  47059. this.edgesWidthScalerForOrthographic = 1000.0;
  47060. this.edgesWidthScalerForPerspective = 50.0;
  47061. this._linesPositions = new Array();
  47062. this._linesNormals = new Array();
  47063. this._linesIndices = new Array();
  47064. this._buffers = {};
  47065. this._checkVerticesInsteadOfIndices = false;
  47066. this._source = source;
  47067. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  47068. this._epsilon = epsilon;
  47069. this._prepareRessources();
  47070. this._generateEdgesLines();
  47071. }
  47072. EdgesRenderer.prototype._prepareRessources = function () {
  47073. if (this._lineShader) {
  47074. return;
  47075. }
  47076. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  47077. attributes: ["position", "normal"],
  47078. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  47079. });
  47080. this._lineShader.disableDepthWrite = true;
  47081. this._lineShader.backFaceCulling = false;
  47082. };
  47083. EdgesRenderer.prototype.dispose = function () {
  47084. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  47085. if (buffer) {
  47086. buffer.dispose();
  47087. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  47088. }
  47089. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  47090. if (buffer) {
  47091. buffer.dispose();
  47092. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  47093. }
  47094. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  47095. this._lineShader.dispose();
  47096. };
  47097. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  47098. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  47099. return 0;
  47100. }
  47101. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  47102. return 1;
  47103. }
  47104. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  47105. return 2;
  47106. }
  47107. return -1;
  47108. };
  47109. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  47110. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  47111. return 0;
  47112. }
  47113. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  47114. return 1;
  47115. }
  47116. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  47117. return 2;
  47118. }
  47119. return -1;
  47120. };
  47121. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  47122. var needToCreateLine;
  47123. if (edge === undefined) {
  47124. needToCreateLine = true;
  47125. }
  47126. else {
  47127. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  47128. needToCreateLine = dotProduct < this._epsilon;
  47129. }
  47130. if (needToCreateLine) {
  47131. var offset = this._linesPositions.length / 3;
  47132. var normal = p0.subtract(p1);
  47133. normal.normalize();
  47134. // Positions
  47135. this._linesPositions.push(p0.x);
  47136. this._linesPositions.push(p0.y);
  47137. this._linesPositions.push(p0.z);
  47138. this._linesPositions.push(p0.x);
  47139. this._linesPositions.push(p0.y);
  47140. this._linesPositions.push(p0.z);
  47141. this._linesPositions.push(p1.x);
  47142. this._linesPositions.push(p1.y);
  47143. this._linesPositions.push(p1.z);
  47144. this._linesPositions.push(p1.x);
  47145. this._linesPositions.push(p1.y);
  47146. this._linesPositions.push(p1.z);
  47147. // Normals
  47148. this._linesNormals.push(p1.x);
  47149. this._linesNormals.push(p1.y);
  47150. this._linesNormals.push(p1.z);
  47151. this._linesNormals.push(-1);
  47152. this._linesNormals.push(p1.x);
  47153. this._linesNormals.push(p1.y);
  47154. this._linesNormals.push(p1.z);
  47155. this._linesNormals.push(1);
  47156. this._linesNormals.push(p0.x);
  47157. this._linesNormals.push(p0.y);
  47158. this._linesNormals.push(p0.z);
  47159. this._linesNormals.push(-1);
  47160. this._linesNormals.push(p0.x);
  47161. this._linesNormals.push(p0.y);
  47162. this._linesNormals.push(p0.z);
  47163. this._linesNormals.push(1);
  47164. // Indices
  47165. this._linesIndices.push(offset);
  47166. this._linesIndices.push(offset + 1);
  47167. this._linesIndices.push(offset + 2);
  47168. this._linesIndices.push(offset);
  47169. this._linesIndices.push(offset + 2);
  47170. this._linesIndices.push(offset + 3);
  47171. }
  47172. };
  47173. EdgesRenderer.prototype._generateEdgesLines = function () {
  47174. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47175. var indices = this._source.getIndices();
  47176. // First let's find adjacencies
  47177. var adjacencies = new Array();
  47178. var faceNormals = new Array();
  47179. var index;
  47180. var faceAdjacencies;
  47181. // Prepare faces
  47182. for (index = 0; index < indices.length; index += 3) {
  47183. faceAdjacencies = new FaceAdjacencies();
  47184. var p0Index = indices[index];
  47185. var p1Index = indices[index + 1];
  47186. var p2Index = indices[index + 2];
  47187. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  47188. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  47189. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  47190. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  47191. faceNormal.normalize();
  47192. faceNormals.push(faceNormal);
  47193. adjacencies.push(faceAdjacencies);
  47194. }
  47195. // Scan
  47196. for (index = 0; index < adjacencies.length; index++) {
  47197. faceAdjacencies = adjacencies[index];
  47198. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  47199. var otherFaceAdjacencies = adjacencies[otherIndex];
  47200. if (faceAdjacencies.edgesConnectedCount === 3) {
  47201. break;
  47202. }
  47203. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  47204. continue;
  47205. }
  47206. var otherP0 = indices[otherIndex * 3];
  47207. var otherP1 = indices[otherIndex * 3 + 1];
  47208. var otherP2 = indices[otherIndex * 3 + 2];
  47209. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  47210. var otherEdgeIndex;
  47211. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  47212. continue;
  47213. }
  47214. switch (edgeIndex) {
  47215. case 0:
  47216. if (this._checkVerticesInsteadOfIndices) {
  47217. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47218. }
  47219. else {
  47220. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  47221. }
  47222. break;
  47223. case 1:
  47224. if (this._checkVerticesInsteadOfIndices) {
  47225. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47226. }
  47227. else {
  47228. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  47229. }
  47230. break;
  47231. case 2:
  47232. if (this._checkVerticesInsteadOfIndices) {
  47233. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  47234. }
  47235. else {
  47236. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  47237. }
  47238. break;
  47239. }
  47240. if (otherEdgeIndex === -1) {
  47241. continue;
  47242. }
  47243. faceAdjacencies.edges[edgeIndex] = otherIndex;
  47244. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  47245. faceAdjacencies.edgesConnectedCount++;
  47246. otherFaceAdjacencies.edgesConnectedCount++;
  47247. if (faceAdjacencies.edgesConnectedCount === 3) {
  47248. break;
  47249. }
  47250. }
  47251. }
  47252. }
  47253. // Create lines
  47254. for (index = 0; index < adjacencies.length; index++) {
  47255. // 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
  47256. var current = adjacencies[index];
  47257. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  47258. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  47259. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  47260. }
  47261. // Merge into a single mesh
  47262. var engine = this._source.getScene().getEngine();
  47263. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  47264. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  47265. this._ib = engine.createIndexBuffer(this._linesIndices);
  47266. this._indicesCount = this._linesIndices.length;
  47267. };
  47268. EdgesRenderer.prototype.render = function () {
  47269. if (!this._lineShader.isReady()) {
  47270. return;
  47271. }
  47272. var scene = this._source.getScene();
  47273. var engine = scene.getEngine();
  47274. this._lineShader._preBind();
  47275. // VBOs
  47276. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  47277. scene.resetCachedMaterial();
  47278. this._lineShader.setColor4("color", this._source.edgesColor);
  47279. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  47280. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  47281. }
  47282. else {
  47283. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  47284. }
  47285. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  47286. this._lineShader.bind(this._source.getWorldMatrix());
  47287. // Draw order
  47288. engine.draw(true, 0, this._indicesCount);
  47289. this._lineShader.unbind();
  47290. engine.setDepthWrite(true);
  47291. };
  47292. return EdgesRenderer;
  47293. }());
  47294. BABYLON.EdgesRenderer = EdgesRenderer;
  47295. })(BABYLON || (BABYLON = {}));
  47296. var BABYLON;
  47297. (function (BABYLON) {
  47298. (function (TonemappingOperator) {
  47299. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  47300. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  47301. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  47302. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  47303. })(BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  47304. var TonemappingOperator = BABYLON.TonemappingOperator;
  47305. ;
  47306. var TonemapPostProcess = (function (_super) {
  47307. __extends(TonemapPostProcess, _super);
  47308. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  47309. var _this = this;
  47310. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47311. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  47312. _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat);
  47313. this._operator = _operator;
  47314. this.exposureAdjustment = exposureAdjustment;
  47315. var defines = "#define ";
  47316. if (this._operator === TonemappingOperator.Hable)
  47317. defines += "HABLE_TONEMAPPING";
  47318. else if (this._operator === TonemappingOperator.Reinhard)
  47319. defines += "REINHARD_TONEMAPPING";
  47320. else if (this._operator === TonemappingOperator.HejiDawson)
  47321. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  47322. else if (this._operator === TonemappingOperator.Photographic)
  47323. defines += "PHOTOGRAPHIC_TONEMAPPING";
  47324. //sadly a second call to create the effect.
  47325. this.updateEffect(defines);
  47326. this.onApply = function (effect) {
  47327. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  47328. };
  47329. }
  47330. return TonemapPostProcess;
  47331. }(BABYLON.PostProcess));
  47332. BABYLON.TonemapPostProcess = TonemapPostProcess;
  47333. })(BABYLON || (BABYLON = {}));
  47334. var BABYLON;
  47335. (function (BABYLON) {
  47336. var ReflectionProbe = (function () {
  47337. function ReflectionProbe(name, size, scene, generateMipMaps) {
  47338. var _this = this;
  47339. if (generateMipMaps === void 0) { generateMipMaps = true; }
  47340. this.name = name;
  47341. this._viewMatrix = BABYLON.Matrix.Identity();
  47342. this._target = BABYLON.Vector3.Zero();
  47343. this._add = BABYLON.Vector3.Zero();
  47344. this.invertYAxis = false;
  47345. this.position = BABYLON.Vector3.Zero();
  47346. this._scene = scene;
  47347. this._scene.reflectionProbes.push(this);
  47348. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  47349. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  47350. switch (faceIndex) {
  47351. case 0:
  47352. _this._add.copyFromFloats(1, 0, 0);
  47353. break;
  47354. case 1:
  47355. _this._add.copyFromFloats(-1, 0, 0);
  47356. break;
  47357. case 2:
  47358. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  47359. break;
  47360. case 3:
  47361. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  47362. break;
  47363. case 4:
  47364. _this._add.copyFromFloats(0, 0, 1);
  47365. break;
  47366. case 5:
  47367. _this._add.copyFromFloats(0, 0, -1);
  47368. break;
  47369. }
  47370. if (_this._attachedMesh) {
  47371. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  47372. }
  47373. _this.position.addToRef(_this._add, _this._target);
  47374. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  47375. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  47376. });
  47377. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  47378. scene.updateTransformMatrix(true);
  47379. });
  47380. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  47381. }
  47382. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  47383. get: function () {
  47384. return this._renderTargetTexture.refreshRate;
  47385. },
  47386. set: function (value) {
  47387. this._renderTargetTexture.refreshRate = value;
  47388. },
  47389. enumerable: true,
  47390. configurable: true
  47391. });
  47392. ReflectionProbe.prototype.getScene = function () {
  47393. return this._scene;
  47394. };
  47395. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  47396. get: function () {
  47397. return this._renderTargetTexture;
  47398. },
  47399. enumerable: true,
  47400. configurable: true
  47401. });
  47402. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  47403. get: function () {
  47404. return this._renderTargetTexture.renderList;
  47405. },
  47406. enumerable: true,
  47407. configurable: true
  47408. });
  47409. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  47410. this._attachedMesh = mesh;
  47411. };
  47412. ReflectionProbe.prototype.dispose = function () {
  47413. var index = this._scene.reflectionProbes.indexOf(this);
  47414. if (index !== -1) {
  47415. // Remove from the scene if found
  47416. this._scene.reflectionProbes.splice(index, 1);
  47417. }
  47418. if (this._renderTargetTexture) {
  47419. this._renderTargetTexture.dispose();
  47420. this._renderTargetTexture = null;
  47421. }
  47422. };
  47423. return ReflectionProbe;
  47424. }());
  47425. BABYLON.ReflectionProbe = ReflectionProbe;
  47426. })(BABYLON || (BABYLON = {}));
  47427. var BABYLON;
  47428. (function (BABYLON) {
  47429. var SolidParticle = (function () {
  47430. /**
  47431. * Creates a Solid Particle object.
  47432. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  47433. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  47434. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  47435. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  47436. * `shapeId` (integer) is the model shape identifier in the SPS.
  47437. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  47438. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  47439. */
  47440. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  47441. this.idx = 0; // particle global index
  47442. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  47443. this.position = BABYLON.Vector3.Zero(); // position
  47444. this.rotation = BABYLON.Vector3.Zero(); // rotation
  47445. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  47446. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  47447. this.velocity = BABYLON.Vector3.Zero(); // velocity
  47448. this.alive = true; // alive
  47449. this.isVisible = true; // visibility
  47450. this._pos = 0; // index of this particle in the global "positions" array
  47451. this.shapeId = 0; // model shape id
  47452. this.idxInShape = 0; // index of the particle in its shape id
  47453. this.idx = particleIndex;
  47454. this._pos = positionIndex;
  47455. this._model = model;
  47456. this.shapeId = shapeId;
  47457. this.idxInShape = idxInShape;
  47458. this._sps = sps;
  47459. if (modelBoundingInfo) {
  47460. this._modelBoundingInfo = modelBoundingInfo;
  47461. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  47462. }
  47463. }
  47464. Object.defineProperty(SolidParticle.prototype, "scale", {
  47465. /**
  47466. * legacy support, changed scale to scaling
  47467. */
  47468. get: function () {
  47469. return this.scaling;
  47470. },
  47471. set: function (scale) {
  47472. this.scaling = scale;
  47473. },
  47474. enumerable: true,
  47475. configurable: true
  47476. });
  47477. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  47478. /**
  47479. * legacy support, changed quaternion to rotationQuaternion
  47480. */
  47481. get: function () {
  47482. return this.rotationQuaternion;
  47483. },
  47484. set: function (q) {
  47485. this.rotationQuaternion = q;
  47486. },
  47487. enumerable: true,
  47488. configurable: true
  47489. });
  47490. /**
  47491. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  47492. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  47493. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  47494. */
  47495. SolidParticle.prototype.intersectsMesh = function (target) {
  47496. if (!this._boundingInfo || !target._boundingInfo) {
  47497. return false;
  47498. }
  47499. if (this._sps._bSphereOnly) {
  47500. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  47501. }
  47502. return this._boundingInfo.intersects(target._boundingInfo, false);
  47503. };
  47504. return SolidParticle;
  47505. }());
  47506. BABYLON.SolidParticle = SolidParticle;
  47507. var ModelShape = (function () {
  47508. /**
  47509. * 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.
  47510. * SPS internal tool, don't use it manually.
  47511. */
  47512. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  47513. this.shapeID = id;
  47514. this._shape = shape;
  47515. this._shapeUV = shapeUV;
  47516. this._positionFunction = posFunction;
  47517. this._vertexFunction = vtxFunction;
  47518. }
  47519. return ModelShape;
  47520. }());
  47521. BABYLON.ModelShape = ModelShape;
  47522. })(BABYLON || (BABYLON = {}));
  47523. var BABYLON;
  47524. (function (BABYLON) {
  47525. /**
  47526. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  47527. */
  47528. var SolidParticleSystem = (function () {
  47529. /**
  47530. * Creates a SPS (Solid Particle System) object.
  47531. * `name` (String) is the SPS name, this will be the underlying mesh name.
  47532. * `scene` (Scene) is the scene in which the SPS is added.
  47533. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  47534. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  47535. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  47536. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  47537. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  47538. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  47539. */
  47540. function SolidParticleSystem(name, scene, options) {
  47541. // public members
  47542. /**
  47543. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  47544. * Example : var p = SPS.particles[i];
  47545. */
  47546. this.particles = new Array();
  47547. /**
  47548. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  47549. */
  47550. this.nbParticles = 0;
  47551. /**
  47552. * If the particles must ever face the camera (default false). Useful for planar particles.
  47553. */
  47554. this.billboard = false;
  47555. /**
  47556. * Recompute normals when adding a shape
  47557. */
  47558. this.recomputeNormals = true;
  47559. /**
  47560. * This a counter ofr your own usage. It's not set by any SPS functions.
  47561. */
  47562. this.counter = 0;
  47563. /**
  47564. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  47565. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  47566. */
  47567. this.vars = {};
  47568. this._positions = new Array();
  47569. this._indices = new Array();
  47570. this._normals = new Array();
  47571. this._colors = new Array();
  47572. this._uvs = new Array();
  47573. this._index = 0; // indices index
  47574. this._updatable = true;
  47575. this._pickable = false;
  47576. this._isVisibilityBoxLocked = false;
  47577. this._alwaysVisible = false;
  47578. this._shapeCounter = 0;
  47579. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  47580. this._color = new BABYLON.Color4(0, 0, 0, 0);
  47581. this._computeParticleColor = true;
  47582. this._computeParticleTexture = true;
  47583. this._computeParticleRotation = true;
  47584. this._computeParticleVertex = false;
  47585. this._computeBoundingBox = false;
  47586. this._cam_axisZ = BABYLON.Vector3.Zero();
  47587. this._cam_axisY = BABYLON.Vector3.Zero();
  47588. this._cam_axisX = BABYLON.Vector3.Zero();
  47589. this._axisX = BABYLON.Axis.X;
  47590. this._axisY = BABYLON.Axis.Y;
  47591. this._axisZ = BABYLON.Axis.Z;
  47592. this._camDir = BABYLON.Vector3.Zero();
  47593. this._rotMatrix = new BABYLON.Matrix();
  47594. this._invertMatrix = new BABYLON.Matrix();
  47595. this._rotated = BABYLON.Vector3.Zero();
  47596. this._quaternion = new BABYLON.Quaternion();
  47597. this._vertex = BABYLON.Vector3.Zero();
  47598. this._normal = BABYLON.Vector3.Zero();
  47599. this._yaw = 0.0;
  47600. this._pitch = 0.0;
  47601. this._roll = 0.0;
  47602. this._halfroll = 0.0;
  47603. this._halfpitch = 0.0;
  47604. this._halfyaw = 0.0;
  47605. this._sinRoll = 0.0;
  47606. this._cosRoll = 0.0;
  47607. this._sinPitch = 0.0;
  47608. this._cosPitch = 0.0;
  47609. this._sinYaw = 0.0;
  47610. this._cosYaw = 0.0;
  47611. this._w = 0.0;
  47612. this._minimum = BABYLON.Tmp.Vector3[0];
  47613. this._maximum = BABYLON.Tmp.Vector3[1];
  47614. this._scale = BABYLON.Tmp.Vector3[2];
  47615. this._translation = BABYLON.Tmp.Vector3[3];
  47616. this._minBbox = BABYLON.Tmp.Vector3[4];
  47617. this._maxBbox = BABYLON.Tmp.Vector3[5];
  47618. this._particlesIntersect = false;
  47619. this._bSphereOnly = false;
  47620. this._bSphereRadiusFactor = 1.0;
  47621. this.name = name;
  47622. this._scene = scene;
  47623. this._camera = scene.activeCamera;
  47624. this._pickable = options ? options.isPickable : false;
  47625. this._particlesIntersect = options ? options.particleIntersection : false;
  47626. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  47627. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  47628. if (options && options.updatable) {
  47629. this._updatable = options.updatable;
  47630. }
  47631. else {
  47632. this._updatable = true;
  47633. }
  47634. if (this._pickable) {
  47635. this.pickedParticles = [];
  47636. }
  47637. }
  47638. /**
  47639. * Builds the SPS underlying mesh. Returns a standard Mesh.
  47640. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  47641. */
  47642. SolidParticleSystem.prototype.buildMesh = function () {
  47643. if (this.nbParticles === 0) {
  47644. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  47645. this.addShape(triangle, 1);
  47646. triangle.dispose();
  47647. }
  47648. this._positions32 = new Float32Array(this._positions);
  47649. this._uvs32 = new Float32Array(this._uvs);
  47650. this._colors32 = new Float32Array(this._colors);
  47651. if (this.recomputeNormals) {
  47652. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  47653. }
  47654. this._normals32 = new Float32Array(this._normals);
  47655. this._fixedNormal32 = new Float32Array(this._normals);
  47656. var vertexData = new BABYLON.VertexData();
  47657. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  47658. vertexData.indices = this._indices;
  47659. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  47660. if (this._uvs32) {
  47661. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  47662. ;
  47663. }
  47664. if (this._colors32) {
  47665. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  47666. }
  47667. var mesh = new BABYLON.Mesh(this.name, this._scene);
  47668. vertexData.applyToMesh(mesh, this._updatable);
  47669. this.mesh = mesh;
  47670. this.mesh.isPickable = this._pickable;
  47671. // free memory
  47672. this._positions = null;
  47673. this._normals = null;
  47674. this._uvs = null;
  47675. this._colors = null;
  47676. if (!this._updatable) {
  47677. this.particles.length = 0;
  47678. }
  47679. return mesh;
  47680. };
  47681. /**
  47682. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  47683. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  47684. * Thus the particles generated from `digest()` have their property `position` set yet.
  47685. * `mesh` ( Mesh ) is the mesh to be digested
  47686. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  47687. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  47688. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  47689. */
  47690. SolidParticleSystem.prototype.digest = function (mesh, options) {
  47691. var size = (options && options.facetNb) || 1;
  47692. var number = (options && options.number);
  47693. var delta = (options && options.delta) || 0;
  47694. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47695. var meshInd = mesh.getIndices();
  47696. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47697. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47698. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47699. var f = 0; // facet counter
  47700. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  47701. // compute size from number
  47702. if (number) {
  47703. number = (number > totalFacets) ? totalFacets : number;
  47704. size = Math.round(totalFacets / number);
  47705. delta = 0;
  47706. }
  47707. else {
  47708. size = (size > totalFacets) ? totalFacets : size;
  47709. }
  47710. var facetPos = []; // submesh positions
  47711. var facetInd = []; // submesh indices
  47712. var facetUV = []; // submesh UV
  47713. var facetCol = []; // submesh colors
  47714. var barycenter = BABYLON.Tmp.Vector3[0];
  47715. var rand;
  47716. var sizeO = size;
  47717. while (f < totalFacets) {
  47718. size = sizeO + Math.floor((1 + delta) * Math.random());
  47719. if (f > totalFacets - size) {
  47720. size = totalFacets - f;
  47721. }
  47722. // reset temp arrays
  47723. facetPos.length = 0;
  47724. facetInd.length = 0;
  47725. facetUV.length = 0;
  47726. facetCol.length = 0;
  47727. // iterate over "size" facets
  47728. var fi = 0;
  47729. for (var j = f * 3; j < (f + size) * 3; j++) {
  47730. facetInd.push(fi);
  47731. var i = meshInd[j];
  47732. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  47733. if (meshUV) {
  47734. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  47735. }
  47736. if (meshCol) {
  47737. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  47738. }
  47739. fi++;
  47740. }
  47741. // create a model shape for each single particle
  47742. var idx = this.nbParticles;
  47743. var shape = this._posToShape(facetPos);
  47744. var shapeUV = this._uvsToShapeUV(facetUV);
  47745. // compute the barycenter of the shape
  47746. var v;
  47747. for (v = 0; v < shape.length; v++) {
  47748. barycenter.addInPlace(shape[v]);
  47749. }
  47750. barycenter.scaleInPlace(1 / shape.length);
  47751. // shift the shape from its barycenter to the origin
  47752. for (v = 0; v < shape.length; v++) {
  47753. shape[v].subtractInPlace(barycenter);
  47754. }
  47755. var bInfo;
  47756. if (this._particlesIntersect) {
  47757. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  47758. }
  47759. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  47760. // add the particle in the SPS
  47761. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  47762. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  47763. // initialize the particle position
  47764. this.particles[this.nbParticles].position.addInPlace(barycenter);
  47765. this._index += shape.length;
  47766. idx++;
  47767. this.nbParticles++;
  47768. this._shapeCounter++;
  47769. f += size;
  47770. }
  47771. return this;
  47772. };
  47773. //reset copy
  47774. SolidParticleSystem.prototype._resetCopy = function () {
  47775. this._copy.position.x = 0;
  47776. this._copy.position.y = 0;
  47777. this._copy.position.z = 0;
  47778. this._copy.rotation.x = 0;
  47779. this._copy.rotation.y = 0;
  47780. this._copy.rotation.z = 0;
  47781. this._copy.rotationQuaternion = null;
  47782. this._copy.scaling.x = 1;
  47783. this._copy.scaling.y = 1;
  47784. this._copy.scaling.z = 1;
  47785. this._copy.uvs.x = 0;
  47786. this._copy.uvs.y = 0;
  47787. this._copy.uvs.z = 1;
  47788. this._copy.uvs.w = 1;
  47789. this._copy.color = null;
  47790. };
  47791. // _meshBuilder : inserts the shape model in the global SPS mesh
  47792. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  47793. var i;
  47794. var u = 0;
  47795. var c = 0;
  47796. var n = 0;
  47797. this._resetCopy();
  47798. if (options && options.positionFunction) {
  47799. options.positionFunction(this._copy, idx, idxInShape);
  47800. }
  47801. if (this._copy.rotationQuaternion) {
  47802. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47803. }
  47804. else {
  47805. this._yaw = this._copy.rotation.y;
  47806. this._pitch = this._copy.rotation.x;
  47807. this._roll = this._copy.rotation.z;
  47808. this._quaternionRotationYPR();
  47809. }
  47810. this._quaternionToRotationMatrix();
  47811. for (i = 0; i < shape.length; i++) {
  47812. this._vertex.x = shape[i].x;
  47813. this._vertex.y = shape[i].y;
  47814. this._vertex.z = shape[i].z;
  47815. if (options && options.vertexFunction) {
  47816. options.vertexFunction(this._copy, this._vertex, i);
  47817. }
  47818. this._vertex.x *= this._copy.scaling.x;
  47819. this._vertex.y *= this._copy.scaling.y;
  47820. this._vertex.z *= this._copy.scaling.z;
  47821. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47822. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  47823. if (meshUV) {
  47824. 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);
  47825. u += 2;
  47826. }
  47827. if (this._copy.color) {
  47828. this._color = this._copy.color;
  47829. }
  47830. else if (meshCol && meshCol[c] !== undefined) {
  47831. this._color.r = meshCol[c];
  47832. this._color.g = meshCol[c + 1];
  47833. this._color.b = meshCol[c + 2];
  47834. this._color.a = meshCol[c + 3];
  47835. }
  47836. else {
  47837. this._color.r = 1;
  47838. this._color.g = 1;
  47839. this._color.b = 1;
  47840. this._color.a = 1;
  47841. }
  47842. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  47843. c += 4;
  47844. if (!this.recomputeNormals && meshNor) {
  47845. this._normal.x = meshNor[n];
  47846. this._normal.y = meshNor[n + 1];
  47847. this._normal.z = meshNor[n + 2];
  47848. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  47849. normals.push(this._normal.x, this._normal.y, this._normal.z);
  47850. n += 3;
  47851. }
  47852. }
  47853. for (i = 0; i < meshInd.length; i++) {
  47854. indices.push(p + meshInd[i]);
  47855. }
  47856. if (this._pickable) {
  47857. var nbfaces = meshInd.length / 3;
  47858. for (i = 0; i < nbfaces; i++) {
  47859. this.pickedParticles.push({ idx: idx, faceId: i });
  47860. }
  47861. }
  47862. };
  47863. // returns a shape array from positions array
  47864. SolidParticleSystem.prototype._posToShape = function (positions) {
  47865. var shape = [];
  47866. for (var i = 0; i < positions.length; i += 3) {
  47867. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  47868. }
  47869. return shape;
  47870. };
  47871. // returns a shapeUV array from a Vector4 uvs
  47872. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  47873. var shapeUV = [];
  47874. if (uvs) {
  47875. for (var i = 0; i < uvs.length; i++)
  47876. shapeUV.push(uvs[i]);
  47877. }
  47878. return shapeUV;
  47879. };
  47880. // adds a new particle object in the particles array
  47881. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  47882. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  47883. };
  47884. /**
  47885. * Adds some particles to the SPS from the model shape. Returns the shape id.
  47886. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  47887. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  47888. * `nb` (positive integer) the number of particles to be created from this model
  47889. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  47890. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  47891. */
  47892. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  47893. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  47894. var meshInd = mesh.getIndices();
  47895. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  47896. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  47897. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  47898. var bbInfo;
  47899. if (this._particlesIntersect) {
  47900. bbInfo = mesh.getBoundingInfo();
  47901. }
  47902. var shape = this._posToShape(meshPos);
  47903. var shapeUV = this._uvsToShapeUV(meshUV);
  47904. var posfunc = options ? options.positionFunction : null;
  47905. var vtxfunc = options ? options.vertexFunction : null;
  47906. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  47907. // particles
  47908. var idx = this.nbParticles;
  47909. for (var i = 0; i < nb; i++) {
  47910. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  47911. if (this._updatable) {
  47912. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  47913. }
  47914. this._index += shape.length;
  47915. idx++;
  47916. }
  47917. this.nbParticles += nb;
  47918. this._shapeCounter++;
  47919. return this._shapeCounter - 1;
  47920. };
  47921. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  47922. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  47923. this._resetCopy();
  47924. if (particle._model._positionFunction) {
  47925. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  47926. }
  47927. if (this._copy.rotationQuaternion) {
  47928. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  47929. }
  47930. else {
  47931. this._yaw = this._copy.rotation.y;
  47932. this._pitch = this._copy.rotation.x;
  47933. this._roll = this._copy.rotation.z;
  47934. this._quaternionRotationYPR();
  47935. }
  47936. this._quaternionToRotationMatrix();
  47937. this._shape = particle._model._shape;
  47938. for (var pt = 0; pt < this._shape.length; pt++) {
  47939. this._vertex.x = this._shape[pt].x;
  47940. this._vertex.y = this._shape[pt].y;
  47941. this._vertex.z = this._shape[pt].z;
  47942. if (particle._model._vertexFunction) {
  47943. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  47944. }
  47945. this._vertex.x *= this._copy.scaling.x;
  47946. this._vertex.y *= this._copy.scaling.y;
  47947. this._vertex.z *= this._copy.scaling.z;
  47948. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  47949. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  47950. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  47951. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  47952. }
  47953. particle.position.x = 0.0;
  47954. particle.position.y = 0.0;
  47955. particle.position.z = 0.0;
  47956. particle.rotation.x = 0.0;
  47957. particle.rotation.y = 0.0;
  47958. particle.rotation.z = 0.0;
  47959. particle.rotationQuaternion = null;
  47960. particle.scaling.x = 1.0;
  47961. particle.scaling.y = 1.0;
  47962. particle.scaling.z = 1.0;
  47963. };
  47964. /**
  47965. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  47966. */
  47967. SolidParticleSystem.prototype.rebuildMesh = function () {
  47968. for (var p = 0; p < this.particles.length; p++) {
  47969. this._rebuildParticle(this.particles[p]);
  47970. }
  47971. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  47972. };
  47973. /**
  47974. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  47975. * This method calls `updateParticle()` for each particle of the SPS.
  47976. * For an animated SPS, it is usually called within the render loop.
  47977. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  47978. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  47979. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  47980. */
  47981. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  47982. if (start === void 0) { start = 0; }
  47983. if (end === void 0) { end = this.nbParticles - 1; }
  47984. if (update === void 0) { update = true; }
  47985. if (!this._updatable) {
  47986. return;
  47987. }
  47988. // custom beforeUpdate
  47989. this.beforeUpdateParticles(start, end, update);
  47990. this._cam_axisX.x = 1.0;
  47991. this._cam_axisX.y = 0.0;
  47992. this._cam_axisX.z = 0.0;
  47993. this._cam_axisY.x = 0.0;
  47994. this._cam_axisY.y = 1.0;
  47995. this._cam_axisY.z = 0.0;
  47996. this._cam_axisZ.x = 0.0;
  47997. this._cam_axisZ.y = 0.0;
  47998. this._cam_axisZ.z = 1.0;
  47999. // if the particles will always face the camera
  48000. if (this.billboard) {
  48001. // compute the camera position and un-rotate it by the current mesh rotation
  48002. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  48003. this._quaternionToRotationMatrix();
  48004. this._rotMatrix.invertToRef(this._invertMatrix);
  48005. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  48006. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  48007. this._cam_axisZ.normalize();
  48008. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  48009. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  48010. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  48011. this._cam_axisY.normalize();
  48012. this._cam_axisX.normalize();
  48013. }
  48014. }
  48015. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  48016. var idx = 0;
  48017. var index = 0;
  48018. var colidx = 0;
  48019. var colorIndex = 0;
  48020. var uvidx = 0;
  48021. var uvIndex = 0;
  48022. var pt = 0;
  48023. if (this._computeBoundingBox) {
  48024. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  48025. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  48026. }
  48027. // particle loop
  48028. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  48029. for (var p = start; p <= end; p++) {
  48030. this._particle = this.particles[p];
  48031. this._shape = this._particle._model._shape;
  48032. this._shapeUV = this._particle._model._shapeUV;
  48033. // call to custom user function to update the particle properties
  48034. this.updateParticle(this._particle);
  48035. if (this._particle.isVisible) {
  48036. // particle rotation matrix
  48037. if (this.billboard) {
  48038. this._particle.rotation.x = 0.0;
  48039. this._particle.rotation.y = 0.0;
  48040. }
  48041. if (this._computeParticleRotation || this.billboard) {
  48042. if (this._particle.rotationQuaternion) {
  48043. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  48044. }
  48045. else {
  48046. this._yaw = this._particle.rotation.y;
  48047. this._pitch = this._particle.rotation.x;
  48048. this._roll = this._particle.rotation.z;
  48049. this._quaternionRotationYPR();
  48050. }
  48051. this._quaternionToRotationMatrix();
  48052. }
  48053. // particle vertex loop
  48054. for (pt = 0; pt < this._shape.length; pt++) {
  48055. idx = index + pt * 3;
  48056. colidx = colorIndex + pt * 4;
  48057. uvidx = uvIndex + pt * 2;
  48058. this._vertex.x = this._shape[pt].x;
  48059. this._vertex.y = this._shape[pt].y;
  48060. this._vertex.z = this._shape[pt].z;
  48061. if (this._computeParticleVertex) {
  48062. this.updateParticleVertex(this._particle, this._vertex, pt);
  48063. }
  48064. // positions
  48065. this._vertex.x *= this._particle.scaling.x;
  48066. this._vertex.y *= this._particle.scaling.y;
  48067. this._vertex.z *= this._particle.scaling.z;
  48068. 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];
  48069. 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;
  48070. 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;
  48071. 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;
  48072. 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;
  48073. 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;
  48074. 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;
  48075. if (this._computeBoundingBox) {
  48076. if (this._positions32[idx] < this._minimum.x) {
  48077. this._minimum.x = this._positions32[idx];
  48078. }
  48079. if (this._positions32[idx] > this._maximum.x) {
  48080. this._maximum.x = this._positions32[idx];
  48081. }
  48082. if (this._positions32[idx + 1] < this._minimum.y) {
  48083. this._minimum.y = this._positions32[idx + 1];
  48084. }
  48085. if (this._positions32[idx + 1] > this._maximum.y) {
  48086. this._maximum.y = this._positions32[idx + 1];
  48087. }
  48088. if (this._positions32[idx + 2] < this._minimum.z) {
  48089. this._minimum.z = this._positions32[idx + 2];
  48090. }
  48091. if (this._positions32[idx + 2] > this._maximum.z) {
  48092. this._maximum.z = this._positions32[idx + 2];
  48093. }
  48094. }
  48095. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  48096. if (!this._computeParticleVertex) {
  48097. this._normal.x = this._fixedNormal32[idx];
  48098. this._normal.y = this._fixedNormal32[idx + 1];
  48099. this._normal.z = this._fixedNormal32[idx + 2];
  48100. 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];
  48101. 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;
  48102. 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;
  48103. 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;
  48104. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  48105. 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;
  48106. 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;
  48107. }
  48108. if (this._computeParticleColor) {
  48109. this._colors32[colidx] = this._particle.color.r;
  48110. this._colors32[colidx + 1] = this._particle.color.g;
  48111. this._colors32[colidx + 2] = this._particle.color.b;
  48112. this._colors32[colidx + 3] = this._particle.color.a;
  48113. }
  48114. if (this._computeParticleTexture) {
  48115. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  48116. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  48117. }
  48118. }
  48119. }
  48120. else {
  48121. for (pt = 0; pt < this._shape.length; pt++) {
  48122. idx = index + pt * 3;
  48123. colidx = colorIndex + pt * 4;
  48124. uvidx = uvIndex + pt * 2;
  48125. this._positions32[idx] = this._camera.position.x;
  48126. this._positions32[idx + 1] = this._camera.position.y;
  48127. this._positions32[idx + 2] = this._camera.position.z;
  48128. this._normals32[idx] = 0.0;
  48129. this._normals32[idx + 1] = 0.0;
  48130. this._normals32[idx + 2] = 0.0;
  48131. if (this._computeParticleColor) {
  48132. this._colors32[colidx] = this._particle.color.r;
  48133. this._colors32[colidx + 1] = this._particle.color.g;
  48134. this._colors32[colidx + 2] = this._particle.color.b;
  48135. this._colors32[colidx + 3] = this._particle.color.a;
  48136. }
  48137. if (this._computeParticleTexture) {
  48138. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  48139. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  48140. }
  48141. }
  48142. }
  48143. // if the particle intersections must be computed : update the bbInfo
  48144. if (this._particlesIntersect) {
  48145. var bInfo = this._particle._boundingInfo;
  48146. var bBox = bInfo.boundingBox;
  48147. var bSphere = bInfo.boundingSphere;
  48148. if (!this._bSphereOnly) {
  48149. // place, scale and rotate the particle bbox within the SPS local system, then update it
  48150. for (var b = 0; b < bBox.vectors.length; b++) {
  48151. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  48152. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  48153. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  48154. 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];
  48155. 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;
  48156. 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;
  48157. 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;
  48158. 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;
  48159. 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;
  48160. 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;
  48161. }
  48162. bBox._update(this.mesh._worldMatrix);
  48163. }
  48164. // place and scale the particle bouding sphere in the SPS local system, then update it
  48165. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  48166. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  48167. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  48168. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  48169. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  48170. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  48171. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  48172. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  48173. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  48174. 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));
  48175. bSphere._update(this.mesh._worldMatrix);
  48176. }
  48177. // increment indexes for the next particle
  48178. index = idx + 3;
  48179. colorIndex = colidx + 4;
  48180. uvIndex = uvidx + 2;
  48181. }
  48182. // if the VBO must be updated
  48183. if (update) {
  48184. if (this._computeParticleColor) {
  48185. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  48186. }
  48187. if (this._computeParticleTexture) {
  48188. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  48189. }
  48190. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  48191. if (!this.mesh.areNormalsFrozen) {
  48192. if (this._computeParticleVertex) {
  48193. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  48194. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  48195. for (var i = 0; i < this._normals32.length; i++) {
  48196. this._fixedNormal32[i] = this._normals32[i];
  48197. }
  48198. }
  48199. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  48200. }
  48201. }
  48202. if (this._computeBoundingBox) {
  48203. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  48204. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  48205. }
  48206. this.afterUpdateParticles(start, end, update);
  48207. };
  48208. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  48209. this._halfroll = this._roll * 0.5;
  48210. this._halfpitch = this._pitch * 0.5;
  48211. this._halfyaw = this._yaw * 0.5;
  48212. this._sinRoll = Math.sin(this._halfroll);
  48213. this._cosRoll = Math.cos(this._halfroll);
  48214. this._sinPitch = Math.sin(this._halfpitch);
  48215. this._cosPitch = Math.cos(this._halfpitch);
  48216. this._sinYaw = Math.sin(this._halfyaw);
  48217. this._cosYaw = Math.cos(this._halfyaw);
  48218. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  48219. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  48220. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  48221. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  48222. };
  48223. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  48224. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  48225. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  48226. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  48227. this._rotMatrix.m[3] = 0;
  48228. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  48229. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  48230. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  48231. this._rotMatrix.m[7] = 0;
  48232. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  48233. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  48234. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  48235. this._rotMatrix.m[11] = 0;
  48236. this._rotMatrix.m[12] = 0;
  48237. this._rotMatrix.m[13] = 0;
  48238. this._rotMatrix.m[14] = 0;
  48239. this._rotMatrix.m[15] = 1.0;
  48240. };
  48241. /**
  48242. * Disposes the SPS
  48243. */
  48244. SolidParticleSystem.prototype.dispose = function () {
  48245. this.mesh.dispose();
  48246. this.vars = null;
  48247. // drop references to internal big arrays for the GC
  48248. this._positions = null;
  48249. this._indices = null;
  48250. this._normals = null;
  48251. this._uvs = null;
  48252. this._colors = null;
  48253. this._positions32 = null;
  48254. this._normals32 = null;
  48255. this._fixedNormal32 = null;
  48256. this._uvs32 = null;
  48257. this._colors32 = null;
  48258. this.pickedParticles = null;
  48259. };
  48260. /**
  48261. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  48262. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48263. */
  48264. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  48265. if (!this._isVisibilityBoxLocked) {
  48266. this.mesh.refreshBoundingInfo();
  48267. }
  48268. };
  48269. /**
  48270. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  48271. * @param size the size (float) of the visibility box
  48272. * note : this doesn't lock the SPS mesh bounding box.
  48273. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48274. */
  48275. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  48276. var vis = size / 2;
  48277. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  48278. };
  48279. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  48280. // getter and setter
  48281. get: function () {
  48282. return this._alwaysVisible;
  48283. },
  48284. /**
  48285. * Sets the SPS as always visible or not
  48286. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48287. */
  48288. set: function (val) {
  48289. this._alwaysVisible = val;
  48290. this.mesh.alwaysSelectAsActiveMesh = val;
  48291. },
  48292. enumerable: true,
  48293. configurable: true
  48294. });
  48295. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  48296. get: function () {
  48297. return this._isVisibilityBoxLocked;
  48298. },
  48299. /**
  48300. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  48301. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  48302. */
  48303. set: function (val) {
  48304. this._isVisibilityBoxLocked = val;
  48305. this.mesh.getBoundingInfo().isLocked = val;
  48306. },
  48307. enumerable: true,
  48308. configurable: true
  48309. });
  48310. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  48311. // getters
  48312. get: function () {
  48313. return this._computeParticleRotation;
  48314. },
  48315. // Optimizer setters
  48316. /**
  48317. * Tells to `setParticles()` to compute the particle rotations or not.
  48318. * Default value : true. The SPS is faster when it's set to false.
  48319. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  48320. */
  48321. set: function (val) {
  48322. this._computeParticleRotation = val;
  48323. },
  48324. enumerable: true,
  48325. configurable: true
  48326. });
  48327. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  48328. get: function () {
  48329. return this._computeParticleColor;
  48330. },
  48331. /**
  48332. * Tells to `setParticles()` to compute the particle colors or not.
  48333. * Default value : true. The SPS is faster when it's set to false.
  48334. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  48335. */
  48336. set: function (val) {
  48337. this._computeParticleColor = val;
  48338. },
  48339. enumerable: true,
  48340. configurable: true
  48341. });
  48342. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  48343. get: function () {
  48344. return this._computeParticleTexture;
  48345. },
  48346. /**
  48347. * Tells to `setParticles()` to compute the particle textures or not.
  48348. * Default value : true. The SPS is faster when it's set to false.
  48349. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  48350. */
  48351. set: function (val) {
  48352. this._computeParticleTexture = val;
  48353. },
  48354. enumerable: true,
  48355. configurable: true
  48356. });
  48357. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  48358. get: function () {
  48359. return this._computeParticleVertex;
  48360. },
  48361. /**
  48362. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  48363. * Default value : false. The SPS is faster when it's set to false.
  48364. * Note : the particle custom vertex positions aren't stored values.
  48365. */
  48366. set: function (val) {
  48367. this._computeParticleVertex = val;
  48368. },
  48369. enumerable: true,
  48370. configurable: true
  48371. });
  48372. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  48373. get: function () {
  48374. return this._computeBoundingBox;
  48375. },
  48376. /**
  48377. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  48378. */
  48379. set: function (val) {
  48380. this._computeBoundingBox = val;
  48381. },
  48382. enumerable: true,
  48383. configurable: true
  48384. });
  48385. // =======================================================================
  48386. // Particle behavior logic
  48387. // these following methods may be overwritten by the user to fit his needs
  48388. /**
  48389. * This function does nothing. It may be overwritten to set all the particle first values.
  48390. * The SPS doesn't call this function, you may have to call it by your own.
  48391. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48392. */
  48393. SolidParticleSystem.prototype.initParticles = function () {
  48394. };
  48395. /**
  48396. * This function does nothing. It may be overwritten to recycle a particle.
  48397. * The SPS doesn't call this function, you may have to call it by your own.
  48398. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48399. */
  48400. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  48401. return particle;
  48402. };
  48403. /**
  48404. * Updates a particle : this function should be overwritten by the user.
  48405. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  48406. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  48407. * ex : just set a particle position or velocity and recycle conditions
  48408. */
  48409. SolidParticleSystem.prototype.updateParticle = function (particle) {
  48410. return particle;
  48411. };
  48412. /**
  48413. * Updates a vertex of a particle : it can be overwritten by the user.
  48414. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  48415. * @param particle the current particle
  48416. * @param vertex the current index of the current particle
  48417. * @param pt the index of the current vertex in the particle shape
  48418. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  48419. * ex : just set a vertex particle position
  48420. */
  48421. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  48422. return vertex;
  48423. };
  48424. /**
  48425. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  48426. * This does nothing and may be overwritten by the user.
  48427. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48428. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48429. * @param update the boolean update value actually passed to setParticles()
  48430. */
  48431. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  48432. };
  48433. /**
  48434. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  48435. * This will be passed three parameters.
  48436. * This does nothing and may be overwritten by the user.
  48437. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48438. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  48439. * @param update the boolean update value actually passed to setParticles()
  48440. */
  48441. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  48442. };
  48443. return SolidParticleSystem;
  48444. }());
  48445. BABYLON.SolidParticleSystem = SolidParticleSystem;
  48446. })(BABYLON || (BABYLON = {}));
  48447. var BABYLON;
  48448. (function (BABYLON) {
  48449. var Internals;
  48450. (function (Internals) {
  48451. var FileFaceOrientation = (function () {
  48452. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  48453. this.name = name;
  48454. this.worldAxisForNormal = worldAxisForNormal;
  48455. this.worldAxisForFileX = worldAxisForFileX;
  48456. this.worldAxisForFileY = worldAxisForFileY;
  48457. }
  48458. return FileFaceOrientation;
  48459. }());
  48460. ;
  48461. /**
  48462. * Helper class dealing with the extraction of spherical polynomial dataArray
  48463. * from a cube map.
  48464. */
  48465. var CubeMapToSphericalPolynomialTools = (function () {
  48466. function CubeMapToSphericalPolynomialTools() {
  48467. }
  48468. /**
  48469. * Converts a cubemap to the according Spherical Polynomial data.
  48470. * This extracts the first 3 orders only as they are the only one used in the lighting.
  48471. *
  48472. * @param cubeInfo The Cube map to extract the information from.
  48473. * @return The Spherical Polynomial data.
  48474. */
  48475. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  48476. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  48477. var totalSolidAngle = 0.0;
  48478. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  48479. var du = 2.0 / cubeInfo.size;
  48480. var dv = du;
  48481. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  48482. var minUV = du * 0.5 - 1.0;
  48483. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  48484. var fileFace = this.FileFaces[faceIndex];
  48485. var dataArray = cubeInfo[fileFace.name];
  48486. var v = minUV;
  48487. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  48488. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  48489. // Because SP is still linear, so summation is fine in that basis.
  48490. for (var y = 0; y < cubeInfo.size; y++) {
  48491. var u = minUV;
  48492. for (var x = 0; x < cubeInfo.size; x++) {
  48493. // World direction (not normalised)
  48494. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  48495. worldDirection.normalize();
  48496. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  48497. if (1) {
  48498. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  48499. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  48500. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  48501. var color = new BABYLON.Color3(r, g, b);
  48502. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48503. }
  48504. else {
  48505. if (faceIndex == 0) {
  48506. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48507. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48508. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48509. }
  48510. else if (faceIndex == 1) {
  48511. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48512. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48513. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48514. }
  48515. else if (faceIndex == 2) {
  48516. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48517. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48518. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48519. }
  48520. else if (faceIndex == 3) {
  48521. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48522. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48523. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  48524. }
  48525. else if (faceIndex == 4) {
  48526. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  48527. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  48528. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48529. }
  48530. else if (faceIndex == 5) {
  48531. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  48532. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  48533. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  48534. }
  48535. 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]);
  48536. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  48537. }
  48538. totalSolidAngle += deltaSolidAngle;
  48539. u += du;
  48540. }
  48541. v += dv;
  48542. }
  48543. }
  48544. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  48545. var correction = correctSolidAngle / totalSolidAngle;
  48546. sphericalHarmonics.scale(correction);
  48547. // Additionally scale by pi -- audit needed
  48548. sphericalHarmonics.scale(1.0 / Math.PI);
  48549. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  48550. };
  48551. CubeMapToSphericalPolynomialTools.FileFaces = [
  48552. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  48553. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  48554. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  48555. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  48556. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  48557. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  48558. ];
  48559. return CubeMapToSphericalPolynomialTools;
  48560. }());
  48561. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  48562. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48563. })(BABYLON || (BABYLON = {}));
  48564. var BABYLON;
  48565. (function (BABYLON) {
  48566. var Internals;
  48567. (function (Internals) {
  48568. /**
  48569. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  48570. */
  48571. var PanoramaToCubeMapTools = (function () {
  48572. function PanoramaToCubeMapTools() {
  48573. }
  48574. /**
  48575. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  48576. *
  48577. * @param float32Array The source data.
  48578. * @param inputWidth The width of the input panorama.
  48579. * @param inputhHeight The height of the input panorama.
  48580. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  48581. * @return The cubemap data
  48582. */
  48583. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  48584. if (!float32Array) {
  48585. throw "ConvertPanoramaToCubemap: input cannot be null";
  48586. }
  48587. if (float32Array.length != inputWidth * inputHeight * 3) {
  48588. throw "ConvertPanoramaToCubemap: input size is wrong";
  48589. }
  48590. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  48591. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  48592. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  48593. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  48594. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  48595. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  48596. return {
  48597. front: textureFront,
  48598. back: textureBack,
  48599. left: textureLeft,
  48600. right: textureRight,
  48601. up: textureUp,
  48602. down: textureDown,
  48603. size: size
  48604. };
  48605. };
  48606. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  48607. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  48608. var textureArray = new Float32Array(buffer);
  48609. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  48610. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  48611. var dy = 1 / texSize;
  48612. var fy = 0;
  48613. for (var y = 0; y < texSize; y++) {
  48614. var xv1 = faceData[0];
  48615. var xv2 = faceData[2];
  48616. for (var x = 0; x < texSize; x++) {
  48617. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  48618. v.normalize();
  48619. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  48620. // 3 channels per pixels
  48621. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  48622. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  48623. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  48624. xv1 = xv1.add(rotDX1);
  48625. xv2 = xv2.add(rotDX2);
  48626. }
  48627. fy += dy;
  48628. }
  48629. return textureArray;
  48630. };
  48631. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  48632. var theta = Math.atan2(vDir.z, vDir.x);
  48633. var phi = Math.acos(vDir.y);
  48634. while (theta < -Math.PI)
  48635. theta += 2 * Math.PI;
  48636. while (theta > Math.PI)
  48637. theta -= 2 * Math.PI;
  48638. var dx = theta / Math.PI;
  48639. var dy = phi / Math.PI;
  48640. // recenter.
  48641. dx = dx * 0.5 + 0.5;
  48642. var px = Math.round(dx * inputWidth);
  48643. if (px < 0)
  48644. px = 0;
  48645. else if (px >= inputWidth)
  48646. px = inputWidth - 1;
  48647. var py = Math.round(dy * inputHeight);
  48648. if (py < 0)
  48649. py = 0;
  48650. else if (py >= inputHeight)
  48651. py = inputHeight - 1;
  48652. var inputY = (inputHeight - py - 1);
  48653. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  48654. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  48655. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  48656. return {
  48657. r: r,
  48658. g: g,
  48659. b: b
  48660. };
  48661. };
  48662. PanoramaToCubeMapTools.FACE_FRONT = [
  48663. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48664. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48665. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48666. new BABYLON.Vector3(1.0, 1.0, -1.0)
  48667. ];
  48668. PanoramaToCubeMapTools.FACE_BACK = [
  48669. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48670. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48671. new BABYLON.Vector3(1.0, 1.0, 1.0),
  48672. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  48673. ];
  48674. PanoramaToCubeMapTools.FACE_RIGHT = [
  48675. new BABYLON.Vector3(1.0, -1.0, -1.0),
  48676. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48677. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48678. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48679. ];
  48680. PanoramaToCubeMapTools.FACE_LEFT = [
  48681. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48682. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48683. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48684. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  48685. ];
  48686. PanoramaToCubeMapTools.FACE_DOWN = [
  48687. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  48688. new BABYLON.Vector3(1.0, 1.0, -1.0),
  48689. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  48690. new BABYLON.Vector3(1.0, 1.0, 1.0)
  48691. ];
  48692. PanoramaToCubeMapTools.FACE_UP = [
  48693. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  48694. new BABYLON.Vector3(1.0, -1.0, 1.0),
  48695. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  48696. new BABYLON.Vector3(1.0, -1.0, -1.0)
  48697. ];
  48698. return PanoramaToCubeMapTools;
  48699. }());
  48700. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  48701. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48702. })(BABYLON || (BABYLON = {}));
  48703. var BABYLON;
  48704. (function (BABYLON) {
  48705. var Internals;
  48706. (function (Internals) {
  48707. ;
  48708. /**
  48709. * This groups tools to convert HDR texture to native colors array.
  48710. */
  48711. var HDRTools = (function () {
  48712. function HDRTools() {
  48713. }
  48714. HDRTools.Ldexp = function (mantissa, exponent) {
  48715. if (exponent > 1023) {
  48716. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  48717. }
  48718. if (exponent < -1074) {
  48719. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  48720. }
  48721. return mantissa * Math.pow(2, exponent);
  48722. };
  48723. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  48724. if (exponent > 0) {
  48725. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  48726. float32array[index + 0] = red * exponent;
  48727. float32array[index + 1] = green * exponent;
  48728. float32array[index + 2] = blue * exponent;
  48729. }
  48730. else {
  48731. float32array[index + 0] = 0;
  48732. float32array[index + 1] = 0;
  48733. float32array[index + 2] = 0;
  48734. }
  48735. };
  48736. HDRTools.readStringLine = function (uint8array, startIndex) {
  48737. var line = "";
  48738. var character = "";
  48739. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  48740. character = String.fromCharCode(uint8array[i]);
  48741. if (character == "\n") {
  48742. break;
  48743. }
  48744. line += character;
  48745. }
  48746. return line;
  48747. };
  48748. /**
  48749. * Reads header information from an RGBE texture stored in a native array.
  48750. * More information on this format are available here:
  48751. * https://en.wikipedia.org/wiki/RGBE_image_format
  48752. *
  48753. * @param uint8array The binary file stored in native array.
  48754. * @return The header information.
  48755. */
  48756. HDRTools.RGBE_ReadHeader = function (uint8array) {
  48757. var height = 0;
  48758. var width = 0;
  48759. var line = this.readStringLine(uint8array, 0);
  48760. if (line[0] != '#' || line[1] != '?') {
  48761. throw "Bad HDR Format.";
  48762. }
  48763. var endOfHeader = false;
  48764. var findFormat = false;
  48765. var lineIndex = 0;
  48766. do {
  48767. lineIndex += (line.length + 1);
  48768. line = this.readStringLine(uint8array, lineIndex);
  48769. if (line == "FORMAT=32-bit_rle_rgbe") {
  48770. findFormat = true;
  48771. }
  48772. else if (line.length == 0) {
  48773. endOfHeader = true;
  48774. }
  48775. } while (!endOfHeader);
  48776. if (!findFormat) {
  48777. throw "HDR Bad header format, unsupported FORMAT";
  48778. }
  48779. lineIndex += (line.length + 1);
  48780. line = this.readStringLine(uint8array, lineIndex);
  48781. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  48782. var match = sizeRegexp.exec(line);
  48783. // TODO. Support +Y and -X if needed.
  48784. if (match.length < 3) {
  48785. throw "HDR Bad header format, no size";
  48786. }
  48787. width = parseInt(match[2]);
  48788. height = parseInt(match[1]);
  48789. if (width < 8 || width > 0x7fff) {
  48790. throw "HDR Bad header format, unsupported size";
  48791. }
  48792. lineIndex += (line.length + 1);
  48793. return {
  48794. height: height,
  48795. width: width,
  48796. dataPosition: lineIndex
  48797. };
  48798. };
  48799. /**
  48800. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  48801. * This RGBE texture needs to store the information as a panorama.
  48802. *
  48803. * More information on this format are available here:
  48804. * https://en.wikipedia.org/wiki/RGBE_image_format
  48805. *
  48806. * @param buffer The binary file stored in an array buffer.
  48807. * @param size The expected size of the extracted cubemap.
  48808. * @return The Cube Map information.
  48809. */
  48810. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  48811. var uint8array = new Uint8Array(buffer);
  48812. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  48813. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48814. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  48815. return cubeMapData;
  48816. };
  48817. /**
  48818. * Returns the pixels data extracted from an RGBE texture.
  48819. * This pixels will be stored left to right up to down in the R G B order in one array.
  48820. *
  48821. * More information on this format are available here:
  48822. * https://en.wikipedia.org/wiki/RGBE_image_format
  48823. *
  48824. * @param uint8array The binary file stored in an array buffer.
  48825. * @param hdrInfo The header information of the file.
  48826. * @return The pixels data in RGB right to left up to down order.
  48827. */
  48828. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  48829. // Keep for multi format supports.
  48830. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  48831. };
  48832. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  48833. var num_scanlines = hdrInfo.height;
  48834. var scanline_width = hdrInfo.width;
  48835. var a, b, c, d, count;
  48836. var dataIndex = hdrInfo.dataPosition;
  48837. var index = 0, endIndex = 0, i = 0;
  48838. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  48839. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  48840. // 3 channels of 4 bytes per pixel in float.
  48841. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  48842. var resultArray = new Float32Array(resultBuffer);
  48843. // read in each successive scanline
  48844. while (num_scanlines > 0) {
  48845. a = uint8array[dataIndex++];
  48846. b = uint8array[dataIndex++];
  48847. c = uint8array[dataIndex++];
  48848. d = uint8array[dataIndex++];
  48849. if (a != 2 || b != 2 || (c & 0x80)) {
  48850. // this file is not run length encoded
  48851. throw "HDR Bad header format, not RLE";
  48852. }
  48853. if (((c << 8) | d) != scanline_width) {
  48854. throw "HDR Bad header format, wrong scan line width";
  48855. }
  48856. index = 0;
  48857. // read each of the four channels for the scanline into the buffer
  48858. for (i = 0; i < 4; i++) {
  48859. endIndex = (i + 1) * scanline_width;
  48860. while (index < endIndex) {
  48861. a = uint8array[dataIndex++];
  48862. b = uint8array[dataIndex++];
  48863. if (a > 128) {
  48864. // a run of the same value
  48865. count = a - 128;
  48866. if ((count == 0) || (count > endIndex - index)) {
  48867. throw "HDR Bad Format, bad scanline data (run)";
  48868. }
  48869. while (count-- > 0) {
  48870. scanLineArray[index++] = b;
  48871. }
  48872. }
  48873. else {
  48874. // a non-run
  48875. count = a;
  48876. if ((count == 0) || (count > endIndex - index)) {
  48877. throw "HDR Bad Format, bad scanline data (non-run)";
  48878. }
  48879. scanLineArray[index++] = b;
  48880. if (--count > 0) {
  48881. for (var j = 0; j < count; j++) {
  48882. scanLineArray[index++] = uint8array[dataIndex++];
  48883. }
  48884. }
  48885. }
  48886. }
  48887. }
  48888. // now convert data from buffer into floats
  48889. for (i = 0; i < scanline_width; i++) {
  48890. a = scanLineArray[i];
  48891. b = scanLineArray[i + scanline_width];
  48892. c = scanLineArray[i + 2 * scanline_width];
  48893. d = scanLineArray[i + 3 * scanline_width];
  48894. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  48895. }
  48896. num_scanlines--;
  48897. }
  48898. return resultArray;
  48899. };
  48900. return HDRTools;
  48901. }());
  48902. Internals.HDRTools = HDRTools;
  48903. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48904. })(BABYLON || (BABYLON = {}));
  48905. //_______________________________________________________________
  48906. // Extracted from CubeMapGen:
  48907. // https://code.google.com/archive/p/cubemapgen/
  48908. //
  48909. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  48910. //_______________________________________________________________
  48911. var BABYLON;
  48912. (function (BABYLON) {
  48913. var Internals;
  48914. (function (Internals) {
  48915. /**
  48916. * The bounding box information used during the conversion process.
  48917. */
  48918. var CMGBoundinBox = (function () {
  48919. function CMGBoundinBox() {
  48920. this.min = new BABYLON.Vector3(0, 0, 0);
  48921. this.max = new BABYLON.Vector3(0, 0, 0);
  48922. this.clear();
  48923. }
  48924. CMGBoundinBox.prototype.clear = function () {
  48925. this.min.x = CMGBoundinBox.MAX;
  48926. this.min.y = CMGBoundinBox.MAX;
  48927. this.min.z = CMGBoundinBox.MAX;
  48928. this.max.x = CMGBoundinBox.MIN;
  48929. this.max.y = CMGBoundinBox.MIN;
  48930. this.max.z = CMGBoundinBox.MIN;
  48931. };
  48932. CMGBoundinBox.prototype.augment = function (x, y, z) {
  48933. this.min.x = Math.min(this.min.x, x);
  48934. this.min.y = Math.min(this.min.y, y);
  48935. this.min.z = Math.min(this.min.z, z);
  48936. this.max.x = Math.max(this.max.x, x);
  48937. this.max.y = Math.max(this.max.y, y);
  48938. this.max.z = Math.max(this.max.z, z);
  48939. };
  48940. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  48941. this.min.x = Math.max(this.min.x, x);
  48942. this.min.y = Math.max(this.min.y, y);
  48943. this.min.z = Math.max(this.min.z, z);
  48944. };
  48945. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  48946. this.max.x = Math.min(this.max.x, x);
  48947. this.max.y = Math.min(this.max.y, y);
  48948. this.max.z = Math.min(this.max.z, z);
  48949. };
  48950. CMGBoundinBox.prototype.empty = function () {
  48951. if ((this.min.x > this.max.y) ||
  48952. (this.min.y > this.max.y) ||
  48953. (this.min.z > this.max.y)) {
  48954. return true;
  48955. }
  48956. else {
  48957. return false;
  48958. }
  48959. };
  48960. CMGBoundinBox.MAX = Number.MAX_VALUE;
  48961. CMGBoundinBox.MIN = Number.MIN_VALUE;
  48962. return CMGBoundinBox;
  48963. }());
  48964. /**
  48965. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  48966. * required by the glossinees of a material.
  48967. *
  48968. * This only supports the cosine drop power as well as Warp fixup generation method.
  48969. *
  48970. * This is using the process from CubeMapGen described here:
  48971. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  48972. */
  48973. var PMREMGenerator = (function () {
  48974. /**
  48975. * Constructor of the generator.
  48976. *
  48977. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  48978. * @param inputSize The size of the cubemap faces
  48979. * @param outputSize The size of the output cubemap faces
  48980. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  48981. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  48982. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  48983. * @param specularPower The max specular level of the desired cubemap
  48984. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  48985. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  48986. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  48987. */
  48988. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  48989. this.input = input;
  48990. this.inputSize = inputSize;
  48991. this.outputSize = outputSize;
  48992. this.maxNumMipLevels = maxNumMipLevels;
  48993. this.numChannels = numChannels;
  48994. this.isFloat = isFloat;
  48995. this.specularPower = specularPower;
  48996. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  48997. this.excludeBase = excludeBase;
  48998. this.fixup = fixup;
  48999. this._outputSurface = [];
  49000. this._numMipLevels = 0;
  49001. }
  49002. /**
  49003. * Launches the filter process and return the result.
  49004. *
  49005. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  49006. */
  49007. PMREMGenerator.prototype.filterCubeMap = function () {
  49008. // Init cubemap processor
  49009. this.init();
  49010. // Filters the cubemap
  49011. this.filterCubeMapMipChain();
  49012. // Returns the filtered mips.
  49013. return this._outputSurface;
  49014. };
  49015. PMREMGenerator.prototype.init = function () {
  49016. var i;
  49017. var j;
  49018. var mipLevelSize;
  49019. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  49020. if (this.maxNumMipLevels == 0) {
  49021. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  49022. }
  49023. //first miplevel size
  49024. mipLevelSize = this.outputSize;
  49025. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  49026. for (j = 0; j < this.maxNumMipLevels; j++) {
  49027. this._outputSurface.length++;
  49028. this._outputSurface[j] = [];
  49029. //Iterate over faces for output images
  49030. for (i = 0; i < 6; i++) {
  49031. this._outputSurface[j].length++;
  49032. // Initializes a new array for the output.
  49033. if (this.isFloat) {
  49034. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  49035. }
  49036. else {
  49037. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  49038. }
  49039. }
  49040. //next mip level is half size
  49041. mipLevelSize >>= 1;
  49042. this._numMipLevels++;
  49043. //terminate if mip chain becomes too small
  49044. if (mipLevelSize == 0) {
  49045. this.maxNumMipLevels = j;
  49046. return;
  49047. }
  49048. }
  49049. };
  49050. //--------------------------------------------------------------------------------------
  49051. //Cube map filtering and mip chain generation.
  49052. // the cube map filtereing is specified using a number of parameters:
  49053. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  49054. // indicates the region of the hemisphere to filter over for each tap.
  49055. //
  49056. // Note that the top mip level is also a filtered version of the original input images
  49057. // as well in order to create mip chains for diffuse environment illumination.
  49058. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  49059. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  49060. //
  49061. // Then the mip angle used to genreate the next level of the mip chain from the first level
  49062. // is a_InitialMipAngle
  49063. //
  49064. // The angle for the subsequent levels of the mip chain are specified by their parents
  49065. // filtering angle and a per-level scale and bias
  49066. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  49067. //
  49068. //--------------------------------------------------------------------------------------
  49069. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  49070. // First, take count of the lighting model to modify SpecularPower
  49071. // 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;
  49072. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  49073. //Cone angle start (for generating subsequent mip levels)
  49074. var currentSpecularPower = this.specularPower;
  49075. //Build filter lookup tables based on the source miplevel size
  49076. this.precomputeFilterLookupTables(this.inputSize);
  49077. // Note that we need to filter the first level before generating mipmap
  49078. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  49079. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  49080. // TODO : Write a function to copy and scale the base mipmap in output
  49081. // I am just lazy here and just put a high specular power value, and do some if.
  49082. if (this.excludeBase && (levelIndex == 0)) {
  49083. // 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).
  49084. currentSpecularPower = 100000.0;
  49085. }
  49086. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  49087. var srcCubeImage = this.input;
  49088. var dstCubeImage = this._outputSurface[levelIndex];
  49089. var dstSize = this.outputSize >> levelIndex;
  49090. // Compute required angle.
  49091. var angle = this.getBaseFilterAngle(currentSpecularPower);
  49092. // filter cube surfaces
  49093. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  49094. // fix seams
  49095. if (this.fixup) {
  49096. this.fixupCubeEdges(dstCubeImage, dstSize);
  49097. }
  49098. // Decrease the specular power to generate the mipmap chain
  49099. // TODO : Use another method for Exclude (see first comment at start of the function
  49100. if (this.excludeBase && (levelIndex == 0)) {
  49101. currentSpecularPower = this.specularPower;
  49102. }
  49103. currentSpecularPower *= this.cosinePowerDropPerMip;
  49104. }
  49105. };
  49106. //--------------------------------------------------------------------------------------
  49107. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  49108. // It allow to optimize the texel to access base on the specular power.
  49109. //--------------------------------------------------------------------------------------
  49110. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  49111. // We want to find the alpha such that:
  49112. // cos(alpha)^cosinePower = epsilon
  49113. // That's: acos(epsilon^(1/cosinePower))
  49114. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  49115. var angle = 180.0;
  49116. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  49117. angle *= 180.0 / Math.PI; // Convert to degree
  49118. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  49119. return angle;
  49120. };
  49121. //--------------------------------------------------------------------------------------
  49122. //Builds the following lookup tables prior to filtering:
  49123. // -normalizer cube map
  49124. // -tap weight lookup table
  49125. //
  49126. //--------------------------------------------------------------------------------------
  49127. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  49128. var srcTexelAngle;
  49129. var iCubeFace;
  49130. //clear pre-existing normalizer cube map
  49131. this._normCubeMap = [];
  49132. //Normalized vectors per cubeface and per-texel solid angle
  49133. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  49134. };
  49135. //--------------------------------------------------------------------------------------
  49136. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  49137. //
  49138. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  49139. //
  49140. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  49141. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  49142. // below
  49143. //--------------------------------------------------------------------------------------
  49144. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  49145. var iCubeFace;
  49146. var u;
  49147. var v;
  49148. //iterate over cube faces
  49149. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49150. //First three channels for norm cube, and last channel for solid angle
  49151. this._normCubeMap.push(new Float32Array(size * size * 4));
  49152. //fast texture walk, build normalizer cube map
  49153. var facesData = this.input[iCubeFace];
  49154. for (v = 0; v < size; v++) {
  49155. for (u = 0; u < size; u++) {
  49156. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  49157. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  49158. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  49159. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  49160. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  49161. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  49162. }
  49163. }
  49164. }
  49165. };
  49166. //--------------------------------------------------------------------------------------
  49167. // Convert cubemap face texel coordinates and face idx to 3D vector
  49168. // note the U and V coords are integer coords and range from 0 to size-1
  49169. // this routine can be used to generate a normalizer cube map
  49170. //--------------------------------------------------------------------------------------
  49171. // SL BEGIN
  49172. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  49173. var nvcU;
  49174. var nvcV;
  49175. var tempVec;
  49176. // Change from original AMD code
  49177. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  49178. // + 0.5f is for texel center addressing
  49179. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  49180. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  49181. // warp fixup
  49182. if (fixup && size > 1) {
  49183. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  49184. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  49185. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  49186. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  49187. }
  49188. // Get current vector
  49189. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  49190. // U contribution
  49191. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  49192. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  49193. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  49194. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  49195. // V contribution and Sum
  49196. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  49197. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  49198. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  49199. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  49200. //add face axis
  49201. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  49202. PMREMGenerator._vectorTemp.x += faceAxis[0];
  49203. PMREMGenerator._vectorTemp.y += faceAxis[1];
  49204. PMREMGenerator._vectorTemp.z += faceAxis[2];
  49205. //normalize vector
  49206. PMREMGenerator._vectorTemp.normalize();
  49207. return PMREMGenerator._vectorTemp;
  49208. };
  49209. //--------------------------------------------------------------------------------------
  49210. // Convert 3D vector to cubemap face texel coordinates and face idx
  49211. // note the U and V coords are integer coords and range from 0 to size-1
  49212. // this routine can be used to generate a normalizer cube map
  49213. //
  49214. // returns face IDX and texel coords
  49215. //--------------------------------------------------------------------------------------
  49216. // SL BEGIN
  49217. /*
  49218. Mapping Texture Coordinates to Cube Map Faces
  49219. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  49220. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  49221. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  49222. map arrangement in Pixar's RenderMan package.
  49223. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  49224. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  49225. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  49226. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  49227. the major axis direction). The target column in the table below explains how the major axis direction
  49228. maps to the 2D image of a particular cube map target.
  49229. major axis
  49230. direction target sc tc ma
  49231. ---------- --------------------------------- --- --- ---
  49232. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  49233. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  49234. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  49235. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  49236. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  49237. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  49238. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  49239. an updated (s,t) is calculated as follows
  49240. s = ( sc/|ma| + 1 ) / 2
  49241. t = ( tc/|ma| + 1 ) / 2
  49242. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  49243. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  49244. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  49245. */
  49246. // Note this method return U and V in range from 0 to size-1
  49247. // SL END
  49248. // Store the information in vector3 for convenience (faceindex, u, v)
  49249. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  49250. var maxCoord;
  49251. var faceIdx;
  49252. //absolute value 3
  49253. var absX = Math.abs(x);
  49254. var absY = Math.abs(y);
  49255. var absZ = Math.abs(z);
  49256. if (absX >= absY && absX >= absZ) {
  49257. maxCoord = absX;
  49258. if (x >= 0) {
  49259. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  49260. }
  49261. else {
  49262. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  49263. }
  49264. }
  49265. else if (absY >= absX && absY >= absZ) {
  49266. maxCoord = absY;
  49267. if (y >= 0) {
  49268. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  49269. }
  49270. else {
  49271. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  49272. }
  49273. }
  49274. else {
  49275. maxCoord = absZ;
  49276. if (z >= 0) {
  49277. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  49278. }
  49279. else {
  49280. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  49281. }
  49282. }
  49283. //divide through by max coord so face vector lies on cube face
  49284. var scale = 1 / maxCoord;
  49285. x *= scale;
  49286. y *= scale;
  49287. z *= scale;
  49288. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  49289. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  49290. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  49291. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  49292. // Modify original AMD code to return value from 0 to Size - 1
  49293. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  49294. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  49295. PMREMGenerator._vectorTemp.x = faceIdx;
  49296. PMREMGenerator._vectorTemp.y = u;
  49297. PMREMGenerator._vectorTemp.z = v;
  49298. return PMREMGenerator._vectorTemp;
  49299. };
  49300. //--------------------------------------------------------------------------------------
  49301. //Original code from Ignacio CastaÒo
  49302. // This formula is from Manne ÷hrstrˆm's thesis.
  49303. // Take two coordiantes in the range [-1, 1] that define a portion of a
  49304. // cube face and return the area of the projection of that portion on the
  49305. // surface of the sphere.
  49306. //--------------------------------------------------------------------------------------
  49307. PMREMGenerator.prototype.areaElement = function (x, y) {
  49308. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  49309. };
  49310. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  49311. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  49312. // (+ 0.5f is for texel center addressing)
  49313. u = (2.0 * (u + 0.5) / size) - 1.0;
  49314. v = (2.0 * (v + 0.5) / size) - 1.0;
  49315. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  49316. var invResolution = 1.0 / size;
  49317. // U and V are the -1..1 texture coordinate on the current face.
  49318. // Get projected area for this texel
  49319. var x0 = u - invResolution;
  49320. var y0 = v - invResolution;
  49321. var x1 = u + invResolution;
  49322. var y1 = v + invResolution;
  49323. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  49324. return solidAngle;
  49325. };
  49326. //--------------------------------------------------------------------------------------
  49327. //The key to the speed of these filtering routines is to quickly define a per-face
  49328. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  49329. // Later these pixels are selectively processed based on their dot products to see if
  49330. // they reside within the filtering cone.
  49331. //
  49332. //This is done by computing the smallest per-texel angle to get a conservative estimate
  49333. // of the number of texels needed to be covered in width and height order to filter the
  49334. // region. the bounding box for the center taps face is defined first, and if the
  49335. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  49336. // defined next
  49337. //--------------------------------------------------------------------------------------
  49338. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  49339. // note that pixels within these regions may be rejected
  49340. // based on the anlge
  49341. var iCubeFace;
  49342. var u;
  49343. var v;
  49344. // bounding box per face to specify region to process
  49345. var filterExtents = [];
  49346. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49347. filterExtents.push(new CMGBoundinBox());
  49348. }
  49349. // min angle a src texel can cover (in degrees)
  49350. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  49351. // angle about center tap to define filter cone
  49352. // filter angle is 1/2 the cone angle
  49353. var filterAngle = filterConeAngle / 2.0;
  49354. //ensure filter angle is larger than a texel
  49355. if (filterAngle < srcTexelAngle) {
  49356. filterAngle = srcTexelAngle;
  49357. }
  49358. //ensure filter cone is always smaller than the hemisphere
  49359. if (filterAngle > 90.0) {
  49360. filterAngle = 90.0;
  49361. }
  49362. // the maximum number of texels in 1D the filter cone angle will cover
  49363. // used to determine bounding box size for filter extents
  49364. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  49365. // ensure conservative region always covers at least one texel
  49366. if (filterSize < 1) {
  49367. filterSize = 1;
  49368. }
  49369. // dotProdThresh threshold based on cone angle to determine whether or not taps
  49370. // reside within the cone angle
  49371. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  49372. // process required faces
  49373. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  49374. //iterate over dst cube map face texel
  49375. for (v = 0; v < dstSize; v++) {
  49376. for (u = 0; u < dstSize; u++) {
  49377. //get center tap direction
  49378. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  49379. //clear old per-face filter extents
  49380. this.clearFilterExtents(filterExtents);
  49381. //define per-face filter extents
  49382. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  49383. //perform filtering of src faces using filter extents
  49384. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  49385. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  49386. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  49387. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  49388. }
  49389. }
  49390. }
  49391. };
  49392. //--------------------------------------------------------------------------------------
  49393. //Clear filter extents for the 6 cube map faces
  49394. //--------------------------------------------------------------------------------------
  49395. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  49396. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  49397. filterExtents[iCubeFaces].clear();
  49398. }
  49399. };
  49400. //--------------------------------------------------------------------------------------
  49401. //Define per-face bounding box filter extents
  49402. //
  49403. // These define conservative texel regions in each of the faces the filter can possibly
  49404. // process. When the pixels in the regions are actually processed, the dot product
  49405. // between the tap vector and the center tap vector is used to determine the weight of
  49406. // the tap and whether or not the tap is within the cone.
  49407. //
  49408. //--------------------------------------------------------------------------------------
  49409. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  49410. //neighboring face and bleed over amount, and width of BBOX for
  49411. // left, right, top, and bottom edges of this face
  49412. var bleedOverAmount = [0, 0, 0, 0];
  49413. var bleedOverBBoxMin = [0, 0, 0, 0];
  49414. var bleedOverBBoxMax = [0, 0, 0, 0];
  49415. var neighborFace;
  49416. var neighborEdge;
  49417. var oppositeFaceIdx;
  49418. //get face idx, and u, v info from center tap dir
  49419. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  49420. var faceIdx = result.x;
  49421. var u = result.y;
  49422. var v = result.z;
  49423. //define bbox size within face
  49424. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  49425. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  49426. filterExtents[faceIdx].clampMin(0, 0, 0);
  49427. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  49428. //u and v extent in face corresponding to center tap
  49429. var minU = filterExtents[faceIdx].min.x;
  49430. var minV = filterExtents[faceIdx].min.y;
  49431. var maxU = filterExtents[faceIdx].max.x;
  49432. var maxV = filterExtents[faceIdx].max.y;
  49433. //bleed over amounts for face across u=0 edge (left)
  49434. bleedOverAmount[0] = (bboxSize - u);
  49435. bleedOverBBoxMin[0] = minV;
  49436. bleedOverBBoxMax[0] = maxV;
  49437. //bleed over amounts for face across u=1 edge (right)
  49438. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  49439. bleedOverBBoxMin[1] = minV;
  49440. bleedOverBBoxMax[1] = maxV;
  49441. //bleed over to face across v=0 edge (up)
  49442. bleedOverAmount[2] = (bboxSize - v);
  49443. bleedOverBBoxMin[2] = minU;
  49444. bleedOverBBoxMax[2] = maxU;
  49445. //bleed over to face across v=1 edge (down)
  49446. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  49447. bleedOverBBoxMin[3] = minU;
  49448. bleedOverBBoxMax[3] = maxU;
  49449. //compute bleed over regions in neighboring faces
  49450. for (var i = 0; i < 4; i++) {
  49451. if (bleedOverAmount[i] > 0) {
  49452. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  49453. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  49454. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  49455. // be flipped: the cases are
  49456. // if a left edge mates with a left or bottom edge on the neighbor
  49457. // if a top edge mates with a top or right edge on the neighbor
  49458. // if a right edge mates with a right or top edge on the neighbor
  49459. // if a bottom edge mates with a bottom or left edge on the neighbor
  49460. //Seeing as the edges are enumerated as follows
  49461. // left =0
  49462. // right =1
  49463. // top =2
  49464. // bottom =3
  49465. //
  49466. // so if the edge enums are the same, or the sum of the enums == 3,
  49467. // the bbox needs to be flipped
  49468. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  49469. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  49470. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  49471. }
  49472. //The way the bounding box is extended onto the neighboring face
  49473. // depends on which edge of neighboring face abuts with this one
  49474. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  49475. case PMREMGenerator.CP_EDGE_LEFT:
  49476. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  49477. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  49478. break;
  49479. case PMREMGenerator.CP_EDGE_RIGHT:
  49480. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  49481. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  49482. break;
  49483. case PMREMGenerator.CP_EDGE_TOP:
  49484. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  49485. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  49486. break;
  49487. case PMREMGenerator.CP_EDGE_BOTTOM:
  49488. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  49489. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  49490. break;
  49491. }
  49492. //clamp filter extents in non-center tap faces to remain within surface
  49493. filterExtents[neighborFace].clampMin(0, 0, 0);
  49494. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  49495. }
  49496. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  49497. // from the center tap face, then process the opposite face entirely for now.
  49498. //Note that the cases in which this happens, what usually happens is that
  49499. // more than one edge bleeds onto the opposite face, and the bounding box
  49500. // encompasses the entire cube map face.
  49501. if (bleedOverAmount[i] > srcSize) {
  49502. //determine opposite face
  49503. switch (faceIdx) {
  49504. case PMREMGenerator.CP_FACE_X_POS:
  49505. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  49506. break;
  49507. case PMREMGenerator.CP_FACE_X_NEG:
  49508. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  49509. break;
  49510. case PMREMGenerator.CP_FACE_Y_POS:
  49511. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  49512. break;
  49513. case PMREMGenerator.CP_FACE_Y_NEG:
  49514. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  49515. break;
  49516. case PMREMGenerator.CP_FACE_Z_POS:
  49517. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  49518. break;
  49519. case PMREMGenerator.CP_FACE_Z_NEG:
  49520. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  49521. break;
  49522. default:
  49523. break;
  49524. }
  49525. //just encompass entire face for now
  49526. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  49527. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  49528. }
  49529. }
  49530. };
  49531. //--------------------------------------------------------------------------------------
  49532. //ProcessFilterExtents
  49533. // Process bounding box in each cube face
  49534. //
  49535. //--------------------------------------------------------------------------------------
  49536. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  49537. //accumulators are 64-bit floats in order to have the precision needed
  49538. // over a summation of a large number of pixels
  49539. var dstAccum = [0, 0, 0, 0];
  49540. var weightAccum = 0;
  49541. var k = 0;
  49542. var nSrcChannels = this.numChannels;
  49543. // norm cube map and srcCubeMap have same face width
  49544. var faceWidth = srcSize;
  49545. //amount to add to pointer to move to next scanline in images
  49546. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  49547. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  49548. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  49549. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  49550. // iterate over cubefaces
  49551. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  49552. //if bbox is non empty
  49553. if (!filterExtents[iFaceIdx].empty()) {
  49554. var uStart = filterExtents[iFaceIdx].min.x;
  49555. var vStart = filterExtents[iFaceIdx].min.y;
  49556. var uEnd = filterExtents[iFaceIdx].max.x;
  49557. var vEnd = filterExtents[iFaceIdx].max.y;
  49558. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  49559. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  49560. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  49561. for (var v = vStart; v <= vEnd; v++) {
  49562. var normCubeRowWalk = 0;
  49563. var srcCubeRowWalk = 0;
  49564. for (var u = uStart; u <= uEnd; u++) {
  49565. //pointer to direction in cube map associated with texel
  49566. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  49567. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  49568. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  49569. //check dot product to see if texel is within cone
  49570. var tapDotProd = texelVectX * centerTapDir.x +
  49571. texelVectY * centerTapDir.y +
  49572. texelVectZ * centerTapDir.z;
  49573. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  49574. //solid angle stored in 4th channel of normalizer/solid angle cube map
  49575. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  49576. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  49577. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  49578. // so just adding one to specularpower do the trick.
  49579. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  49580. //iterate over channels
  49581. for (k = 0; k < nSrcChannels; k++) {
  49582. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  49583. srcCubeRowWalk++;
  49584. }
  49585. weightAccum += weight; //accumulate weight
  49586. }
  49587. else {
  49588. //step across source pixel
  49589. srcCubeRowWalk += nSrcChannels;
  49590. }
  49591. normCubeRowWalk += 4; // 4 channels per norm cube map.
  49592. }
  49593. startIndexNormCubeMap += normCubePitch;
  49594. startIndexSrcCubeMap += srcCubePitch;
  49595. }
  49596. }
  49597. }
  49598. //divide through by weights if weight is non zero
  49599. if (weightAccum != 0.0) {
  49600. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  49601. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  49602. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  49603. if (this.numChannels > 3) {
  49604. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  49605. }
  49606. }
  49607. else {
  49608. // otherwise sample nearest
  49609. // get face idx and u, v texel coordinate in face
  49610. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  49611. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  49612. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  49613. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  49614. if (this.numChannels > 3) {
  49615. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  49616. }
  49617. }
  49618. return PMREMGenerator._vectorTemp;
  49619. };
  49620. //--------------------------------------------------------------------------------------
  49621. // Fixup cube edges
  49622. //
  49623. // average texels on cube map faces across the edges
  49624. // WARP/BENT Method Only.
  49625. //--------------------------------------------------------------------------------------
  49626. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  49627. var k;
  49628. var j;
  49629. var i;
  49630. var iFace;
  49631. var iCorner = 0;
  49632. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  49633. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  49634. // note that if functionality to filter across the three texels for each corner, then
  49635. //indexed by corner and face idx. the array contains the face the start points belongs to.
  49636. var cornerPtr = [
  49637. [[], [], []],
  49638. [[], [], []],
  49639. [[], [], []],
  49640. [[], [], []],
  49641. [[], [], []],
  49642. [[], [], []],
  49643. [[], [], []],
  49644. [[], [], []]
  49645. ];
  49646. //if there is no fixup, or fixup width = 0, do nothing
  49647. if (cubeMapSize < 1) {
  49648. return;
  49649. }
  49650. //special case 1x1 cubemap, average face colors
  49651. if (cubeMapSize == 1) {
  49652. //iterate over channels
  49653. for (k = 0; k < this.numChannels; k++) {
  49654. var accum = 0.0;
  49655. //iterate over faces to accumulate face colors
  49656. for (iFace = 0; iFace < 6; iFace++) {
  49657. accum += cubeMap[iFace][k];
  49658. }
  49659. //compute average over 6 face colors
  49660. accum /= 6.0;
  49661. //iterate over faces to distribute face colors
  49662. for (iFace = 0; iFace < 6; iFace++) {
  49663. cubeMap[iFace][k] = accum;
  49664. }
  49665. }
  49666. return;
  49667. }
  49668. //iterate over faces to collect list of corner texel pointers
  49669. for (iFace = 0; iFace < 6; iFace++) {
  49670. //the 4 corner pointers for this face
  49671. faceCornerStartIndicies[0] = [iFace, 0];
  49672. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  49673. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  49674. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  49675. //iterate over face corners to collect cube corner pointers
  49676. for (iCorner = 0; iCorner < 4; iCorner++) {
  49677. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  49678. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  49679. cornerNumPtrs[corner]++;
  49680. }
  49681. }
  49682. //iterate over corners to average across corner tap values
  49683. for (iCorner = 0; iCorner < 8; iCorner++) {
  49684. for (k = 0; k < this.numChannels; k++) {
  49685. var cornerTapAccum = 0.0;
  49686. //iterate over corner texels and average results
  49687. for (i = 0; i < 3; i++) {
  49688. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  49689. }
  49690. //divide by 3 to compute average of corner tap values
  49691. cornerTapAccum *= (1.0 / 3.0);
  49692. //iterate over corner texels and average results
  49693. for (i = 0; i < 3; i++) {
  49694. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  49695. }
  49696. }
  49697. }
  49698. //iterate over the twelve edges of the cube to average across edges
  49699. for (i = 0; i < 12; i++) {
  49700. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  49701. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  49702. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  49703. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  49704. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  49705. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  49706. var edgeWalk = 0;
  49707. var neighborEdgeWalk = 0;
  49708. //Determine walking pointers based on edge type
  49709. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  49710. switch (edge) {
  49711. case PMREMGenerator.CP_EDGE_LEFT:
  49712. // no change to faceEdgeStartPtr
  49713. edgeWalk = this.numChannels * cubeMapSize;
  49714. break;
  49715. case PMREMGenerator.CP_EDGE_RIGHT:
  49716. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49717. edgeWalk = this.numChannels * cubeMapSize;
  49718. break;
  49719. case PMREMGenerator.CP_EDGE_TOP:
  49720. // no change to faceEdgeStartPtr
  49721. edgeWalk = this.numChannels;
  49722. break;
  49723. case PMREMGenerator.CP_EDGE_BOTTOM:
  49724. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  49725. edgeWalk = this.numChannels;
  49726. break;
  49727. }
  49728. //For certain types of edge abutments, the neighbor edge walk needs to
  49729. // be flipped: the cases are
  49730. // if a left edge mates with a left or bottom edge on the neighbor
  49731. // if a top edge mates with a top or right edge on the neighbor
  49732. // if a right edge mates with a right or top edge on the neighbor
  49733. // if a bottom edge mates with a bottom or left edge on the neighbor
  49734. //Seeing as the edges are enumerated as follows
  49735. // left =0
  49736. // right =1
  49737. // top =2
  49738. // bottom =3
  49739. //
  49740. //If the edge enums are the same, or the sum of the enums == 3,
  49741. // the neighbor edge walk needs to be flipped
  49742. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  49743. switch (neighborEdge) {
  49744. case PMREMGenerator.CP_EDGE_LEFT:
  49745. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  49746. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  49747. break;
  49748. case PMREMGenerator.CP_EDGE_RIGHT:
  49749. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  49750. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  49751. break;
  49752. case PMREMGenerator.CP_EDGE_TOP:
  49753. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49754. neighborEdgeWalk = -this.numChannels;
  49755. break;
  49756. case PMREMGenerator.CP_EDGE_BOTTOM:
  49757. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  49758. neighborEdgeWalk = -this.numChannels;
  49759. break;
  49760. }
  49761. }
  49762. else {
  49763. //swapped direction neighbor edge walk
  49764. switch (neighborEdge) {
  49765. case PMREMGenerator.CP_EDGE_LEFT:
  49766. //no change to neighborEdgeStartPtr for this case since it points
  49767. // to the upper left corner already
  49768. neighborEdgeWalk = this.numChannels * cubeMapSize;
  49769. break;
  49770. case PMREMGenerator.CP_EDGE_RIGHT:
  49771. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  49772. neighborEdgeWalk = this.numChannels * cubeMapSize;
  49773. break;
  49774. case PMREMGenerator.CP_EDGE_TOP:
  49775. //no change to neighborEdgeStartPtr for this case since it points
  49776. // to the upper left corner already
  49777. neighborEdgeWalk = this.numChannels;
  49778. break;
  49779. case PMREMGenerator.CP_EDGE_BOTTOM:
  49780. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  49781. neighborEdgeWalk = this.numChannels;
  49782. break;
  49783. }
  49784. }
  49785. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  49786. //nearby neighborhood
  49787. //step ahead one texel on edge
  49788. edgeStartIndex += edgeWalk;
  49789. neighborEdgeStartIndex += neighborEdgeWalk;
  49790. // note that this loop does not process the corner texels, since they have already been
  49791. // averaged across faces across earlier
  49792. for (j = 1; j < (cubeMapSize - 1); j++) {
  49793. //for each set of taps along edge, average them
  49794. // and rewrite the results into the edges
  49795. for (k = 0; k < this.numChannels; k++) {
  49796. var edgeTap = cubeMap[face][edgeStartIndex + k];
  49797. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  49798. //compute average of tap intensity values
  49799. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  49800. //propagate average of taps to edge taps
  49801. cubeMap[face][edgeStartIndex + k] = avgTap;
  49802. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  49803. }
  49804. edgeStartIndex += edgeWalk;
  49805. neighborEdgeStartIndex += neighborEdgeWalk;
  49806. }
  49807. }
  49808. };
  49809. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  49810. PMREMGenerator.CP_UDIR = 0;
  49811. PMREMGenerator.CP_VDIR = 1;
  49812. PMREMGenerator.CP_FACEAXIS = 2;
  49813. //used to index cube faces
  49814. PMREMGenerator.CP_FACE_X_POS = 0;
  49815. PMREMGenerator.CP_FACE_X_NEG = 1;
  49816. PMREMGenerator.CP_FACE_Y_POS = 2;
  49817. PMREMGenerator.CP_FACE_Y_NEG = 3;
  49818. PMREMGenerator.CP_FACE_Z_POS = 4;
  49819. PMREMGenerator.CP_FACE_Z_NEG = 5;
  49820. //used to index image edges
  49821. // NOTE.. the actual number corresponding to the edge is important
  49822. // do not change these, or the code will break
  49823. //
  49824. // CP_EDGE_LEFT is u = 0
  49825. // CP_EDGE_RIGHT is u = width-1
  49826. // CP_EDGE_TOP is v = 0
  49827. // CP_EDGE_BOTTOM is v = height-1
  49828. PMREMGenerator.CP_EDGE_LEFT = 0;
  49829. PMREMGenerator.CP_EDGE_RIGHT = 1;
  49830. PMREMGenerator.CP_EDGE_TOP = 2;
  49831. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  49832. //corners of CUBE map (P or N specifys if it corresponds to the
  49833. // positive or negative direction each of X, Y, and Z
  49834. PMREMGenerator.CP_CORNER_NNN = 0;
  49835. PMREMGenerator.CP_CORNER_NNP = 1;
  49836. PMREMGenerator.CP_CORNER_NPN = 2;
  49837. PMREMGenerator.CP_CORNER_NPP = 3;
  49838. PMREMGenerator.CP_CORNER_PNN = 4;
  49839. PMREMGenerator.CP_CORNER_PNP = 5;
  49840. PMREMGenerator.CP_CORNER_PPN = 6;
  49841. PMREMGenerator.CP_CORNER_PPP = 7;
  49842. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  49843. //3x2 matrices that map cube map indexing vectors in 3d
  49844. // (after face selection and divide through by the
  49845. // _ABSOLUTE VALUE_ of the max coord)
  49846. // into NVC space
  49847. //Note this currently assumes the D3D cube face ordering and orientation
  49848. PMREMGenerator._sgFace2DMapping = [
  49849. //XPOS face
  49850. [[0, 0, -1],
  49851. [0, -1, 0],
  49852. [1, 0, 0]],
  49853. //XNEG face
  49854. [[0, 0, 1],
  49855. [0, -1, 0],
  49856. [-1, 0, 0]],
  49857. //YPOS face
  49858. [[1, 0, 0],
  49859. [0, 0, 1],
  49860. [0, 1, 0]],
  49861. //YNEG face
  49862. [[1, 0, 0],
  49863. [0, 0, -1],
  49864. [0, -1, 0]],
  49865. //ZPOS face
  49866. [[1, 0, 0],
  49867. [0, -1, 0],
  49868. [0, 0, 1]],
  49869. //ZNEG face
  49870. [[-1, 0, 0],
  49871. [0, -1, 0],
  49872. [0, 0, -1]],
  49873. ];
  49874. //------------------------------------------------------------------------------
  49875. // D3D cube map face specification
  49876. // mapping from 3D x,y,z cube map lookup coordinates
  49877. // to 2D within face u,v coordinates
  49878. //
  49879. // --------------------> U direction
  49880. // | (within-face texture space)
  49881. // | _____
  49882. // | | |
  49883. // | | +Y |
  49884. // | _____|_____|_____ _____
  49885. // | | | | | |
  49886. // | | -X | +Z | +X | -Z |
  49887. // | |_____|_____|_____|_____|
  49888. // | | |
  49889. // | | -Y |
  49890. // | |_____|
  49891. // |
  49892. // v V direction
  49893. // (within-face texture space)
  49894. //------------------------------------------------------------------------------
  49895. //Information about neighbors and how texture coorrdinates change across faces
  49896. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  49897. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  49898. //Note this currently assumes the D3D cube face ordering and orientation
  49899. PMREMGenerator._sgCubeNgh = [
  49900. //XPOS face
  49901. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49902. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49903. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49904. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  49905. //XNEG face
  49906. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49907. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  49908. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  49909. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  49910. //YPOS face
  49911. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  49912. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  49913. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  49914. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  49915. //YNEG face
  49916. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  49917. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49918. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49919. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  49920. //ZPOS face
  49921. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49922. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  49923. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49924. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  49925. //ZNEG face
  49926. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49927. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49928. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  49929. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  49930. ];
  49931. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  49932. // this table is used to average over the edges.
  49933. PMREMGenerator._sgCubeEdgeList = [
  49934. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  49935. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  49936. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  49937. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49938. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  49939. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  49940. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  49941. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  49942. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  49943. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  49944. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  49945. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  49946. ];
  49947. //Information about which of the 8 cube corners are correspond to the
  49948. // the 4 corners in each cube face
  49949. // the order is upper left, upper right, lower left, lower right
  49950. PMREMGenerator._sgCubeCornerList = [
  49951. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  49952. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  49953. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  49954. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  49955. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  49956. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  49957. ];
  49958. return PMREMGenerator;
  49959. }());
  49960. Internals.PMREMGenerator = PMREMGenerator;
  49961. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  49962. })(BABYLON || (BABYLON = {}));
  49963. var BABYLON;
  49964. (function (BABYLON) {
  49965. /**
  49966. * This represents a texture coming from an HDR input.
  49967. *
  49968. * The only supported format is currently panorama picture stored in RGBE format.
  49969. * Example of such files can be found on HDRLib: http://hdrlib.com/
  49970. */
  49971. var HDRCubeTexture = (function (_super) {
  49972. __extends(HDRCubeTexture, _super);
  49973. /**
  49974. * Instantiates an HDRTexture from the following parameters.
  49975. *
  49976. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  49977. * @param scene The scene the texture will be used in
  49978. * @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.
  49979. * @param noMipmap Forces to not generate the mipmap if true
  49980. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  49981. * @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)
  49982. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  49983. */
  49984. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  49985. if (noMipmap === void 0) { noMipmap = false; }
  49986. if (generateHarmonics === void 0) { generateHarmonics = true; }
  49987. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  49988. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  49989. _super.call(this, scene);
  49990. this._useInGammaSpace = false;
  49991. this._generateHarmonics = true;
  49992. this._isBABYLONPreprocessed = false;
  49993. /**
  49994. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  49995. */
  49996. this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  49997. /**
  49998. * The spherical polynomial data extracted from the texture.
  49999. */
  50000. this.sphericalPolynomial = null;
  50001. /**
  50002. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  50003. * This is usefull at run time to apply the good shader.
  50004. */
  50005. this.isPMREM = false;
  50006. if (!url) {
  50007. return;
  50008. }
  50009. this.name = url;
  50010. this.url = url;
  50011. this.hasAlpha = false;
  50012. this.isCube = true;
  50013. this._textureMatrix = BABYLON.Matrix.Identity();
  50014. if (size) {
  50015. this._isBABYLONPreprocessed = false;
  50016. this._noMipmap = noMipmap;
  50017. this._size = size;
  50018. this._useInGammaSpace = useInGammaSpace;
  50019. this._usePMREMGenerator = usePMREMGenerator &&
  50020. scene.getEngine().getCaps().textureLOD &&
  50021. this.getScene().getEngine().getCaps().textureFloat &&
  50022. !this._useInGammaSpace;
  50023. }
  50024. else {
  50025. this._isBABYLONPreprocessed = true;
  50026. this._noMipmap = false;
  50027. this._useInGammaSpace = false;
  50028. this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  50029. this.getScene().getEngine().getCaps().textureFloat &&
  50030. !this._useInGammaSpace;
  50031. }
  50032. this.isPMREM = this._usePMREMGenerator;
  50033. this._texture = this._getFromCache(url, this._noMipmap);
  50034. if (!this._texture) {
  50035. if (!scene.useDelayedTextureLoading) {
  50036. this.loadTexture();
  50037. }
  50038. else {
  50039. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50040. }
  50041. }
  50042. }
  50043. /**
  50044. * Occurs when the file is a preprocessed .babylon.hdr file.
  50045. */
  50046. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  50047. var _this = this;
  50048. var mipLevels = 0;
  50049. var floatArrayView = null;
  50050. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  50051. var mips = [];
  50052. var startIndex = 30;
  50053. for (var level = 0; level < mipLevels; level++) {
  50054. mips.push([]);
  50055. // Fill each pixel of the mip level.
  50056. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  50057. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50058. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  50059. mips[level].push(faceData);
  50060. startIndex += faceSize;
  50061. }
  50062. }
  50063. return mips;
  50064. } : null;
  50065. var callback = function (buffer) {
  50066. // Create Native Array Views
  50067. var intArrayView = new Int32Array(buffer);
  50068. floatArrayView = new Float32Array(buffer);
  50069. // Fill header.
  50070. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  50071. _this._size = intArrayView[1]; // CubeMap max mip face size.
  50072. // Update Texture Information.
  50073. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  50074. // Fill polynomial information.
  50075. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  50076. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  50077. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  50078. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  50079. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  50080. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  50081. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  50082. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  50083. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  50084. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  50085. // Fill pixel data.
  50086. mipLevels = intArrayView[29]; // Number of mip levels.
  50087. var startIndex = 30;
  50088. var data = [];
  50089. var faceSize = Math.pow(_this._size, 2) * 3;
  50090. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50091. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  50092. startIndex += faceSize;
  50093. }
  50094. var results = [];
  50095. var byteArray = null;
  50096. // Push each faces.
  50097. for (var k = 0; k < 6; k++) {
  50098. var dataFace = null;
  50099. // If special cases.
  50100. if (!mipmapGenerator) {
  50101. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  50102. dataFace = data[j];
  50103. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  50104. // 3 channels of 1 bytes per pixel in bytes.
  50105. var byteBuffer = new ArrayBuffer(faceSize);
  50106. byteArray = new Uint8Array(byteBuffer);
  50107. }
  50108. for (var i = 0; i < _this._size * _this._size; i++) {
  50109. // Put in gamma space if requested.
  50110. if (_this._useInGammaSpace) {
  50111. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  50112. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  50113. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  50114. }
  50115. // Convert to int texture for fallback.
  50116. if (byteArray) {
  50117. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  50118. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  50119. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  50120. // May use luminance instead if the result is not accurate.
  50121. var max = Math.max(Math.max(r, g), b);
  50122. if (max > 255) {
  50123. var scale = 255 / max;
  50124. r *= scale;
  50125. g *= scale;
  50126. b *= scale;
  50127. }
  50128. byteArray[(i * 3) + 0] = r;
  50129. byteArray[(i * 3) + 1] = g;
  50130. byteArray[(i * 3) + 2] = b;
  50131. }
  50132. }
  50133. }
  50134. else {
  50135. dataFace = data[k];
  50136. }
  50137. // Fill the array accordingly.
  50138. if (byteArray) {
  50139. results.push(byteArray);
  50140. }
  50141. else {
  50142. results.push(dataFace);
  50143. }
  50144. }
  50145. return results;
  50146. };
  50147. 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);
  50148. };
  50149. /**
  50150. * Occurs when the file is raw .hdr file.
  50151. */
  50152. HDRCubeTexture.prototype.loadHDRTexture = function () {
  50153. var _this = this;
  50154. var callback = function (buffer) {
  50155. // Extract the raw linear data.
  50156. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  50157. // Generate harmonics if needed.
  50158. if (_this._generateHarmonics) {
  50159. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  50160. }
  50161. var results = [];
  50162. var byteArray = null;
  50163. // Push each faces.
  50164. for (var j = 0; j < 6; j++) {
  50165. // Create uintarray fallback.
  50166. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  50167. // 3 channels of 1 bytes per pixel in bytes.
  50168. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  50169. byteArray = new Uint8Array(byteBuffer);
  50170. }
  50171. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  50172. // If special cases.
  50173. if (_this._useInGammaSpace || byteArray) {
  50174. for (var i = 0; i < _this._size * _this._size; i++) {
  50175. // Put in gamma space if requested.
  50176. if (_this._useInGammaSpace) {
  50177. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  50178. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  50179. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  50180. }
  50181. // Convert to int texture for fallback.
  50182. if (byteArray) {
  50183. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  50184. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  50185. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  50186. // May use luminance instead if the result is not accurate.
  50187. var max = Math.max(Math.max(r, g), b);
  50188. if (max > 255) {
  50189. var scale = 255 / max;
  50190. r *= scale;
  50191. g *= scale;
  50192. b *= scale;
  50193. }
  50194. byteArray[(i * 3) + 0] = r;
  50195. byteArray[(i * 3) + 1] = g;
  50196. byteArray[(i * 3) + 2] = b;
  50197. }
  50198. }
  50199. }
  50200. if (byteArray) {
  50201. results.push(byteArray);
  50202. }
  50203. else {
  50204. results.push(dataFace);
  50205. }
  50206. }
  50207. return results;
  50208. };
  50209. var mipmapGenerator = null;
  50210. if (!this._noMipmap &&
  50211. this._usePMREMGenerator) {
  50212. mipmapGenerator = function (data) {
  50213. // Custom setup of the generator matching with the PBR shader values.
  50214. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  50215. return generator.filterCubeMap();
  50216. };
  50217. }
  50218. 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);
  50219. };
  50220. /**
  50221. * Starts the loading process of the texture.
  50222. */
  50223. HDRCubeTexture.prototype.loadTexture = function () {
  50224. if (this._isBABYLONPreprocessed) {
  50225. this.loadBabylonTexture();
  50226. }
  50227. else {
  50228. this.loadHDRTexture();
  50229. }
  50230. };
  50231. HDRCubeTexture.prototype.clone = function () {
  50232. var size = this._isBABYLONPreprocessed ? null : this._size;
  50233. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  50234. // Base texture
  50235. newTexture.level = this.level;
  50236. newTexture.wrapU = this.wrapU;
  50237. newTexture.wrapV = this.wrapV;
  50238. newTexture.coordinatesIndex = this.coordinatesIndex;
  50239. newTexture.coordinatesMode = this.coordinatesMode;
  50240. return newTexture;
  50241. };
  50242. // Methods
  50243. HDRCubeTexture.prototype.delayLoad = function () {
  50244. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50245. return;
  50246. }
  50247. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50248. this._texture = this._getFromCache(this.url, this._noMipmap);
  50249. if (!this._texture) {
  50250. this.loadTexture();
  50251. }
  50252. };
  50253. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  50254. return this._textureMatrix;
  50255. };
  50256. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50257. var texture = null;
  50258. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  50259. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  50260. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  50261. texture.name = parsedTexture.name;
  50262. texture.hasAlpha = parsedTexture.hasAlpha;
  50263. texture.level = parsedTexture.level;
  50264. texture.coordinatesMode = parsedTexture.coordinatesMode;
  50265. }
  50266. return texture;
  50267. };
  50268. HDRCubeTexture.prototype.serialize = function () {
  50269. if (!this.name) {
  50270. return null;
  50271. }
  50272. var serializationObject = {};
  50273. serializationObject.name = this.name;
  50274. serializationObject.hasAlpha = this.hasAlpha;
  50275. serializationObject.isCube = true;
  50276. serializationObject.level = this.level;
  50277. serializationObject.size = this._size;
  50278. serializationObject.coordinatesMode = this.coordinatesMode;
  50279. serializationObject.useInGammaSpace = this._useInGammaSpace;
  50280. serializationObject.generateHarmonics = this._generateHarmonics;
  50281. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  50282. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  50283. serializationObject.customType = "BABYLON.HDRCubeTexture";
  50284. return serializationObject;
  50285. };
  50286. /**
  50287. * Saves as a file the data contained in the texture in a binary format.
  50288. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  50289. * as the spherical used in the lighting.
  50290. * @param url The HDR file url.
  50291. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  50292. * @param onError Method called if any error happens during download.
  50293. * @return The packed binary data.
  50294. */
  50295. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  50296. if (onError === void 0) { onError = null; }
  50297. var callback = function (buffer) {
  50298. var data = new Blob([buffer], { type: 'application/octet-stream' });
  50299. // Returns a URL you can use as a href.
  50300. var objUrl = window.URL.createObjectURL(data);
  50301. // Simulates a link to it and click to dowload.
  50302. var a = document.createElement("a");
  50303. document.body.appendChild(a);
  50304. a.style.display = "none";
  50305. a.href = objUrl;
  50306. a.download = "envmap.babylon.hdr";
  50307. a.click();
  50308. };
  50309. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  50310. };
  50311. /**
  50312. * Serializes the data contained in the texture in a binary format.
  50313. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  50314. * as the spherical used in the lighting.
  50315. * @param url The HDR file url.
  50316. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  50317. * @param onError Method called if any error happens during download.
  50318. * @return The packed binary data.
  50319. */
  50320. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  50321. if (onError === void 0) { onError = null; }
  50322. // Needs the url tho create the texture.
  50323. if (!url) {
  50324. return null;
  50325. }
  50326. // Check Power of two size.
  50327. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  50328. return null;
  50329. }
  50330. var getDataCallback = function (dataBuffer) {
  50331. // Extract the raw linear data.
  50332. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  50333. // Generate harmonics if needed.
  50334. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  50335. // Generate seamless faces
  50336. var mipGeneratorArray = [];
  50337. // Data are known to be in +X +Y +Z -X -Y -Z
  50338. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  50339. mipGeneratorArray.push(cubeData.right); // +X
  50340. mipGeneratorArray.push(cubeData.left); // -X
  50341. mipGeneratorArray.push(cubeData.up); // +Y
  50342. mipGeneratorArray.push(cubeData.down); // -Y
  50343. mipGeneratorArray.push(cubeData.front); // +Z
  50344. mipGeneratorArray.push(cubeData.back); // -Z
  50345. // Custom setup of the generator matching with the PBR shader values.
  50346. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  50347. var mippedData = generator.filterCubeMap();
  50348. // Compute required byte length.
  50349. var byteLength = 1 * 4; // Raw Data Version int32.
  50350. byteLength += 4; // CubeMap max mip face size int32.
  50351. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  50352. // Add data size.
  50353. byteLength += 4; // Number of mip levels int32.
  50354. for (var level = 0; level < mippedData.length; level++) {
  50355. var mipSize = size >> level;
  50356. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  50357. }
  50358. // Prepare binary structure.
  50359. var buffer = new ArrayBuffer(byteLength);
  50360. var intArrayView = new Int32Array(buffer);
  50361. var floatArrayView = new Float32Array(buffer);
  50362. // Fill header.
  50363. intArrayView[0] = 1; // Version 1.
  50364. intArrayView[1] = size; // CubeMap max mip face size.
  50365. // Fill polynomial information.
  50366. sphericalPolynomial.x.toArray(floatArrayView, 2);
  50367. sphericalPolynomial.y.toArray(floatArrayView, 5);
  50368. sphericalPolynomial.z.toArray(floatArrayView, 8);
  50369. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  50370. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  50371. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  50372. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  50373. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  50374. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  50375. // Fill pixel data.
  50376. intArrayView[29] = mippedData.length; // Number of mip levels.
  50377. var startIndex = 30;
  50378. for (var level = 0; level < mippedData.length; level++) {
  50379. // Fill each pixel of the mip level.
  50380. var faceSize = Math.pow(size >> level, 2) * 3;
  50381. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50382. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  50383. startIndex += faceSize;
  50384. }
  50385. }
  50386. // Callback.
  50387. callback(buffer);
  50388. };
  50389. // Download and process.
  50390. BABYLON.Tools.LoadFile(url, function (data) {
  50391. getDataCallback(data);
  50392. }, null, null, true, onError);
  50393. };
  50394. HDRCubeTexture._facesMapping = [
  50395. "right",
  50396. "up",
  50397. "front",
  50398. "left",
  50399. "down",
  50400. "back"
  50401. ];
  50402. return HDRCubeTexture;
  50403. }(BABYLON.BaseTexture));
  50404. BABYLON.HDRCubeTexture = HDRCubeTexture;
  50405. })(BABYLON || (BABYLON = {}));
  50406. var BABYLON;
  50407. (function (BABYLON) {
  50408. var Debug;
  50409. (function (Debug) {
  50410. /**
  50411. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  50412. */
  50413. var SkeletonViewer = (function () {
  50414. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  50415. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  50416. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  50417. this.skeleton = skeleton;
  50418. this.mesh = mesh;
  50419. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  50420. this.renderingGroupId = renderingGroupId;
  50421. this.color = BABYLON.Color3.White();
  50422. this._debugLines = [];
  50423. this._isEnabled = false;
  50424. this._scene = scene;
  50425. this.update();
  50426. this._renderFunction = this.update.bind(this);
  50427. }
  50428. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  50429. get: function () {
  50430. return this._isEnabled;
  50431. },
  50432. set: function (value) {
  50433. if (this._isEnabled === value) {
  50434. return;
  50435. }
  50436. this._isEnabled = value;
  50437. if (value) {
  50438. this._scene.registerBeforeRender(this._renderFunction);
  50439. }
  50440. else {
  50441. this._scene.unregisterBeforeRender(this._renderFunction);
  50442. }
  50443. },
  50444. enumerable: true,
  50445. configurable: true
  50446. });
  50447. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  50448. if (x === void 0) { x = 0; }
  50449. if (y === void 0) { y = 0; }
  50450. if (z === void 0) { z = 0; }
  50451. var tmat = BABYLON.Tmp.Matrix[0];
  50452. var parentBone = bone.getParent();
  50453. tmat.copyFrom(bone.getLocalMatrix());
  50454. if (x !== 0 || y !== 0 || z !== 0) {
  50455. var tmat2 = BABYLON.Tmp.Matrix[1];
  50456. BABYLON.Matrix.IdentityToRef(tmat2);
  50457. tmat2.m[12] = x;
  50458. tmat2.m[13] = y;
  50459. tmat2.m[14] = z;
  50460. tmat2.multiplyToRef(tmat, tmat);
  50461. }
  50462. if (parentBone) {
  50463. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  50464. }
  50465. tmat.multiplyToRef(meshMat, tmat);
  50466. position.x = tmat.m[12];
  50467. position.y = tmat.m[13];
  50468. position.z = tmat.m[14];
  50469. };
  50470. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  50471. var len = bones.length;
  50472. for (var i = 0; i < len; i++) {
  50473. var bone = bones[i];
  50474. var points = this._debugLines[i];
  50475. if (!points) {
  50476. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50477. this._debugLines[i] = points;
  50478. }
  50479. this._getBonePosition(points[0], bone, meshMat);
  50480. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  50481. }
  50482. };
  50483. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  50484. var len = bones.length;
  50485. var boneNum = 0;
  50486. for (var i = len - 1; i >= 0; i--) {
  50487. var childBone = bones[i];
  50488. var parentBone = childBone.getParent();
  50489. if (!parentBone) {
  50490. continue;
  50491. }
  50492. var points = this._debugLines[boneNum];
  50493. if (!points) {
  50494. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  50495. this._debugLines[boneNum] = points;
  50496. }
  50497. this._getBonePosition(points[0], childBone, meshMat);
  50498. this._getBonePosition(points[1], parentBone, meshMat);
  50499. boneNum++;
  50500. }
  50501. };
  50502. SkeletonViewer.prototype.update = function () {
  50503. if (this.autoUpdateBonesMatrices) {
  50504. this._updateBoneMatrix(this.skeleton.bones[0]);
  50505. }
  50506. if (this.skeleton.bones[0].length === undefined) {
  50507. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  50508. }
  50509. else {
  50510. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  50511. }
  50512. if (!this._debugMesh) {
  50513. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  50514. this._debugMesh.renderingGroupId = this.renderingGroupId;
  50515. }
  50516. else {
  50517. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  50518. }
  50519. this._debugMesh.color = this.color;
  50520. };
  50521. SkeletonViewer.prototype._updateBoneMatrix = function (bone) {
  50522. if (bone.getParent()) {
  50523. bone.getLocalMatrix().multiplyToRef(bone.getParent().getAbsoluteTransform(), bone.getAbsoluteTransform());
  50524. }
  50525. var children = bone.children;
  50526. var len = children.length;
  50527. for (var i = 0; i < len; i++) {
  50528. this._updateBoneMatrix(children[i]);
  50529. }
  50530. };
  50531. SkeletonViewer.prototype.dispose = function () {
  50532. if (this._debugMesh) {
  50533. this.isEnabled = false;
  50534. this._debugMesh.dispose();
  50535. this._debugMesh = null;
  50536. }
  50537. };
  50538. return SkeletonViewer;
  50539. }());
  50540. Debug.SkeletonViewer = SkeletonViewer;
  50541. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  50542. })(BABYLON || (BABYLON = {}));
  50543. var BABYLON;
  50544. (function (BABYLON) {
  50545. /**
  50546. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  50547. * It can help converting any input color in a desired output one. This can then be used to create effects
  50548. * from sepia, black and white to sixties or futuristic rendering...
  50549. *
  50550. * The only supported format is currently 3dl.
  50551. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  50552. */
  50553. var ColorGradingTexture = (function (_super) {
  50554. __extends(ColorGradingTexture, _super);
  50555. /**
  50556. * Instantiates a ColorGradingTexture from the following parameters.
  50557. *
  50558. * @param url The location of the color gradind data (currently only supporting 3dl)
  50559. * @param scene The scene the texture will be used in
  50560. */
  50561. function ColorGradingTexture(url, scene) {
  50562. _super.call(this, scene);
  50563. if (!url) {
  50564. return;
  50565. }
  50566. this._textureMatrix = BABYLON.Matrix.Identity();
  50567. this.name = url;
  50568. this.url = url;
  50569. this.hasAlpha = false;
  50570. this.isCube = false;
  50571. this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50572. this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  50573. this.anisotropicFilteringLevel = 1;
  50574. this._texture = this._getFromCache(url, true);
  50575. if (!this._texture) {
  50576. if (!scene.useDelayedTextureLoading) {
  50577. this.loadTexture();
  50578. }
  50579. else {
  50580. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  50581. }
  50582. }
  50583. }
  50584. /**
  50585. * Returns the texture matrix used in most of the material.
  50586. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  50587. */
  50588. ColorGradingTexture.prototype.getTextureMatrix = function () {
  50589. return this._textureMatrix;
  50590. };
  50591. /**
  50592. * Occurs when the file being loaded is a .3dl LUT file.
  50593. */
  50594. ColorGradingTexture.prototype.load3dlTexture = function () {
  50595. var _this = this;
  50596. var mipLevels = 0;
  50597. var floatArrayView = null;
  50598. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  50599. this._texture = texture;
  50600. var callback = function (text) {
  50601. var data;
  50602. var tempData;
  50603. var line;
  50604. var lines = text.split('\n');
  50605. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  50606. var maxColor = 0;
  50607. for (var i = 0; i < lines.length; i++) {
  50608. line = lines[i];
  50609. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  50610. continue;
  50611. if (line.indexOf('#') === 0)
  50612. continue;
  50613. var words = line.split(" ");
  50614. if (size === 0) {
  50615. // Number of space + one
  50616. size = words.length;
  50617. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  50618. tempData = new Float32Array(size * size * size * 4);
  50619. continue;
  50620. }
  50621. if (size != 0) {
  50622. var r = Math.max(parseInt(words[0]), 0);
  50623. var g = Math.max(parseInt(words[1]), 0);
  50624. var b = Math.max(parseInt(words[2]), 0);
  50625. maxColor = Math.max(r, maxColor);
  50626. maxColor = Math.max(g, maxColor);
  50627. maxColor = Math.max(b, maxColor);
  50628. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  50629. tempData[pixelStorageIndex + 0] = r;
  50630. tempData[pixelStorageIndex + 1] = g;
  50631. tempData[pixelStorageIndex + 2] = b;
  50632. tempData[pixelStorageIndex + 3] = 0;
  50633. pixelIndexSlice++;
  50634. if (pixelIndexSlice % size == 0) {
  50635. pixelIndexH++;
  50636. pixelIndexSlice = 0;
  50637. if (pixelIndexH % size == 0) {
  50638. pixelIndexW++;
  50639. pixelIndexH = 0;
  50640. }
  50641. }
  50642. }
  50643. }
  50644. for (var i = 0; i < tempData.length; i++) {
  50645. var value = tempData[i];
  50646. data[i] = (value / maxColor * 255);
  50647. }
  50648. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  50649. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  50650. };
  50651. BABYLON.Tools.LoadFile(this.url, callback);
  50652. return this._texture;
  50653. };
  50654. /**
  50655. * Starts the loading process of the texture.
  50656. */
  50657. ColorGradingTexture.prototype.loadTexture = function () {
  50658. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  50659. this.load3dlTexture();
  50660. }
  50661. };
  50662. /**
  50663. * Clones the color gradind texture.
  50664. */
  50665. ColorGradingTexture.prototype.clone = function () {
  50666. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  50667. // Base texture
  50668. newTexture.level = this.level;
  50669. return newTexture;
  50670. };
  50671. /**
  50672. * Called during delayed load for textures.
  50673. */
  50674. ColorGradingTexture.prototype.delayLoad = function () {
  50675. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  50676. return;
  50677. }
  50678. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  50679. this._texture = this._getFromCache(this.url, true);
  50680. if (!this._texture) {
  50681. this.loadTexture();
  50682. }
  50683. };
  50684. /**
  50685. * Binds the color grading to the shader.
  50686. * @param colorGrading The texture to bind
  50687. * @param effect The effect to bind to
  50688. */
  50689. ColorGradingTexture.Bind = function (colorGrading, effect) {
  50690. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  50691. var x = colorGrading.level; // Texture Level
  50692. var y = colorGrading.getSize().height; // Texture Size example with 8
  50693. var z = y - 1.0; // SizeMinusOne 8 - 1
  50694. var w = 1 / y; // Space of 1 slice 1 / 8
  50695. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  50696. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  50697. 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
  50698. 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
  50699. 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
  50700. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  50701. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  50702. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  50703. };
  50704. /**
  50705. * Prepare the list of uniforms associated with the ColorGrading effects.
  50706. * @param uniformsList The list of uniforms used in the effect
  50707. * @param samplersList The list of samplers used in the effect
  50708. */
  50709. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  50710. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  50711. samplersList.push("cameraColorGrading2DSampler");
  50712. };
  50713. /**
  50714. * Parses a color grading texture serialized by Babylon.
  50715. * @param parsedTexture The texture information being parsedTexture
  50716. * @param scene The scene to load the texture in
  50717. * @param rootUrl The root url of the data assets to load
  50718. * @return A color gradind texture
  50719. */
  50720. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  50721. var texture = null;
  50722. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  50723. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  50724. texture.name = parsedTexture.name;
  50725. texture.level = parsedTexture.level;
  50726. }
  50727. return texture;
  50728. };
  50729. /**
  50730. * Serializes the LUT texture to json format.
  50731. */
  50732. ColorGradingTexture.prototype.serialize = function () {
  50733. if (!this.name) {
  50734. return null;
  50735. }
  50736. var serializationObject = {};
  50737. serializationObject.name = this.name;
  50738. serializationObject.level = this.level;
  50739. serializationObject.customType = "BABYLON.ColorGradingTexture";
  50740. return serializationObject;
  50741. };
  50742. /**
  50743. * Empty line regex stored for GC.
  50744. */
  50745. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  50746. return ColorGradingTexture;
  50747. }(BABYLON.BaseTexture));
  50748. BABYLON.ColorGradingTexture = ColorGradingTexture;
  50749. })(BABYLON || (BABYLON = {}));
  50750. var BABYLON;
  50751. (function (BABYLON) {
  50752. /**
  50753. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  50754. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  50755. * 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;
  50756. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  50757. */
  50758. var ColorCurves = (function () {
  50759. function ColorCurves() {
  50760. this._dirty = true;
  50761. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  50762. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  50763. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  50764. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  50765. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  50766. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  50767. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  50768. this._globalHue = 30;
  50769. this._globalDensity = 0;
  50770. this._globalSaturation = 0;
  50771. this._globalExposure = 0;
  50772. this._highlightsHue = 30;
  50773. this._highlightsDensity = 0;
  50774. this._highlightsSaturation = 0;
  50775. this._highlightsExposure = 0;
  50776. this._midtonesHue = 30;
  50777. this._midtonesDensity = 0;
  50778. this._midtonesSaturation = 0;
  50779. this._midtonesExposure = 0;
  50780. this._shadowsHue = 30;
  50781. this._shadowsDensity = 0;
  50782. this._shadowsSaturation = 0;
  50783. this._shadowsExposure = 0;
  50784. }
  50785. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  50786. /**
  50787. * Gets the global Hue value.
  50788. * 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).
  50789. */
  50790. get: function () {
  50791. return this._globalHue;
  50792. },
  50793. /**
  50794. * Sets the global Hue value.
  50795. * 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).
  50796. */
  50797. set: function (value) {
  50798. this._globalHue = value;
  50799. this._dirty = true;
  50800. },
  50801. enumerable: true,
  50802. configurable: true
  50803. });
  50804. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  50805. /**
  50806. * Gets the global Density value.
  50807. * 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.
  50808. * Values less than zero provide a filter of opposite hue.
  50809. */
  50810. get: function () {
  50811. return this._globalDensity;
  50812. },
  50813. /**
  50814. * Sets the global Density value.
  50815. * 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.
  50816. * Values less than zero provide a filter of opposite hue.
  50817. */
  50818. set: function (value) {
  50819. this._globalDensity = value;
  50820. this._dirty = true;
  50821. },
  50822. enumerable: true,
  50823. configurable: true
  50824. });
  50825. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  50826. /**
  50827. * Gets the global Saturation value.
  50828. * 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.
  50829. */
  50830. get: function () {
  50831. return this._globalSaturation;
  50832. },
  50833. /**
  50834. * Sets the global Saturation value.
  50835. * 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.
  50836. */
  50837. set: function (value) {
  50838. this._globalSaturation = value;
  50839. this._dirty = true;
  50840. },
  50841. enumerable: true,
  50842. configurable: true
  50843. });
  50844. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  50845. /**
  50846. * Gets the highlights Hue value.
  50847. * 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).
  50848. */
  50849. get: function () {
  50850. return this._highlightsHue;
  50851. },
  50852. /**
  50853. * Sets the highlights Hue value.
  50854. * 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).
  50855. */
  50856. set: function (value) {
  50857. this._highlightsHue = value;
  50858. this._dirty = true;
  50859. },
  50860. enumerable: true,
  50861. configurable: true
  50862. });
  50863. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  50864. /**
  50865. * Gets the highlights Density value.
  50866. * 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.
  50867. * Values less than zero provide a filter of opposite hue.
  50868. */
  50869. get: function () {
  50870. return this._highlightsDensity;
  50871. },
  50872. /**
  50873. * Sets the highlights Density value.
  50874. * 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.
  50875. * Values less than zero provide a filter of opposite hue.
  50876. */
  50877. set: function (value) {
  50878. this._highlightsDensity = value;
  50879. this._dirty = true;
  50880. },
  50881. enumerable: true,
  50882. configurable: true
  50883. });
  50884. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  50885. /**
  50886. * Gets the highlights Saturation value.
  50887. * 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.
  50888. */
  50889. get: function () {
  50890. return this._highlightsSaturation;
  50891. },
  50892. /**
  50893. * Sets the highlights Saturation value.
  50894. * 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.
  50895. */
  50896. set: function (value) {
  50897. this._highlightsSaturation = value;
  50898. this._dirty = true;
  50899. },
  50900. enumerable: true,
  50901. configurable: true
  50902. });
  50903. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  50904. /**
  50905. * Gets the highlights Exposure value.
  50906. * 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.
  50907. */
  50908. get: function () {
  50909. return this._highlightsExposure;
  50910. },
  50911. /**
  50912. * Sets the highlights Exposure value.
  50913. * 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.
  50914. */
  50915. set: function (value) {
  50916. this._highlightsExposure = value;
  50917. this._dirty = true;
  50918. },
  50919. enumerable: true,
  50920. configurable: true
  50921. });
  50922. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  50923. /**
  50924. * Gets the midtones Hue value.
  50925. * 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).
  50926. */
  50927. get: function () {
  50928. return this._midtonesHue;
  50929. },
  50930. /**
  50931. * Sets the midtones Hue value.
  50932. * 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).
  50933. */
  50934. set: function (value) {
  50935. this._midtonesHue = value;
  50936. this._dirty = true;
  50937. },
  50938. enumerable: true,
  50939. configurable: true
  50940. });
  50941. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  50942. /**
  50943. * Gets the midtones Density value.
  50944. * 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.
  50945. * Values less than zero provide a filter of opposite hue.
  50946. */
  50947. get: function () {
  50948. return this._midtonesDensity;
  50949. },
  50950. /**
  50951. * Sets the midtones Density value.
  50952. * 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.
  50953. * Values less than zero provide a filter of opposite hue.
  50954. */
  50955. set: function (value) {
  50956. this._midtonesDensity = value;
  50957. this._dirty = true;
  50958. },
  50959. enumerable: true,
  50960. configurable: true
  50961. });
  50962. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  50963. /**
  50964. * Gets the midtones Saturation value.
  50965. * 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.
  50966. */
  50967. get: function () {
  50968. return this._midtonesSaturation;
  50969. },
  50970. /**
  50971. * Sets the midtones Saturation value.
  50972. * 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.
  50973. */
  50974. set: function (value) {
  50975. this._midtonesSaturation = value;
  50976. this._dirty = true;
  50977. },
  50978. enumerable: true,
  50979. configurable: true
  50980. });
  50981. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  50982. /**
  50983. * Gets the midtones Exposure value.
  50984. * 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.
  50985. */
  50986. get: function () {
  50987. return this._midtonesExposure;
  50988. },
  50989. /**
  50990. * Sets the midtones Exposure value.
  50991. * 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.
  50992. */
  50993. set: function (value) {
  50994. this._midtonesExposure = value;
  50995. this._dirty = true;
  50996. },
  50997. enumerable: true,
  50998. configurable: true
  50999. });
  51000. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  51001. /**
  51002. * Gets the shadows Hue value.
  51003. * 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).
  51004. */
  51005. get: function () {
  51006. return this._shadowsHue;
  51007. },
  51008. /**
  51009. * Sets the shadows Hue value.
  51010. * 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).
  51011. */
  51012. set: function (value) {
  51013. this._shadowsHue = value;
  51014. this._dirty = true;
  51015. },
  51016. enumerable: true,
  51017. configurable: true
  51018. });
  51019. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  51020. /**
  51021. * Gets the shadows Density value.
  51022. * 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.
  51023. * Values less than zero provide a filter of opposite hue.
  51024. */
  51025. get: function () {
  51026. return this._shadowsDensity;
  51027. },
  51028. /**
  51029. * Sets the shadows Density value.
  51030. * 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.
  51031. * Values less than zero provide a filter of opposite hue.
  51032. */
  51033. set: function (value) {
  51034. this._shadowsDensity = value;
  51035. this._dirty = true;
  51036. },
  51037. enumerable: true,
  51038. configurable: true
  51039. });
  51040. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  51041. /**
  51042. * Gets the shadows Saturation value.
  51043. * 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.
  51044. */
  51045. get: function () {
  51046. return this._shadowsSaturation;
  51047. },
  51048. /**
  51049. * Sets the shadows Saturation value.
  51050. * 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.
  51051. */
  51052. set: function (value) {
  51053. this._shadowsSaturation = value;
  51054. this._dirty = true;
  51055. },
  51056. enumerable: true,
  51057. configurable: true
  51058. });
  51059. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  51060. /**
  51061. * Gets the shadows Exposure value.
  51062. * 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.
  51063. */
  51064. get: function () {
  51065. return this._shadowsExposure;
  51066. },
  51067. /**
  51068. * Sets the shadows Exposure value.
  51069. * 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.
  51070. */
  51071. set: function (value) {
  51072. this._shadowsExposure = value;
  51073. this._dirty = true;
  51074. },
  51075. enumerable: true,
  51076. configurable: true
  51077. });
  51078. /**
  51079. * Binds the color curves to the shader.
  51080. * @param colorCurves The color curve to bind
  51081. * @param effect The effect to bind to
  51082. */
  51083. ColorCurves.Bind = function (colorCurves, effect) {
  51084. if (colorCurves._dirty) {
  51085. colorCurves._dirty = false;
  51086. // Fill in global info.
  51087. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  51088. // Compute highlights info.
  51089. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  51090. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  51091. // Compute midtones info.
  51092. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  51093. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  51094. // Compute shadows info.
  51095. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  51096. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  51097. // Compute deltas (neutral is midtones).
  51098. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  51099. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  51100. }
  51101. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  51102. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  51103. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  51104. };
  51105. /**
  51106. * Prepare the list of uniforms associated with the ColorCurves effects.
  51107. * @param uniformsList The list of uniforms used in the effect
  51108. */
  51109. ColorCurves.PrepareUniforms = function (uniformsList) {
  51110. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  51111. };
  51112. /**
  51113. * Returns color grading data based on a hue, density, saturation and exposure value.
  51114. * @param filterHue The hue of the color filter.
  51115. * @param filterDensity The density of the color filter.
  51116. * @param saturation The saturation.
  51117. * @param exposure The exposure.
  51118. * @param result The result data container.
  51119. */
  51120. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  51121. if (hue == null) {
  51122. return;
  51123. }
  51124. hue = ColorCurves.clamp(hue, 0, 360);
  51125. density = ColorCurves.clamp(density, -100, 100);
  51126. saturation = ColorCurves.clamp(saturation, -100, 100);
  51127. exposure = ColorCurves.clamp(exposure, -100, 100);
  51128. // Remap the slider/config filter density with non-linear mapping and also scale by half
  51129. // so that the maximum filter density is only 50% control. This provides fine control
  51130. // for small values and reasonable range.
  51131. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  51132. density *= 0.5;
  51133. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  51134. if (density < 0) {
  51135. density *= -1;
  51136. hue = (hue + 180) % 360;
  51137. }
  51138. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  51139. result.scaleToRef(2, result);
  51140. result.a = 1 + 0.01 * saturation;
  51141. };
  51142. /**
  51143. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  51144. * @param value The input slider value in range [-100,100].
  51145. * @returns Adjusted value.
  51146. */
  51147. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  51148. value /= 100;
  51149. var x = Math.abs(value);
  51150. x = Math.pow(x, 2);
  51151. if (value < 0) {
  51152. x *= -1;
  51153. }
  51154. x *= 100;
  51155. return x;
  51156. };
  51157. /**
  51158. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  51159. * @param hue The hue (H) input.
  51160. * @param saturation The saturation (S) input.
  51161. * @param brightness The brightness (B) input.
  51162. * @result An RGBA color represented as Vector4.
  51163. */
  51164. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  51165. var h = ColorCurves.clamp(hue, 0, 360);
  51166. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  51167. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  51168. if (s === 0) {
  51169. result.r = v;
  51170. result.g = v;
  51171. result.b = v;
  51172. }
  51173. else {
  51174. // sector 0 to 5
  51175. h /= 60;
  51176. var i = Math.floor(h);
  51177. // fractional part of h
  51178. var f = h - i;
  51179. var p = v * (1 - s);
  51180. var q = v * (1 - s * f);
  51181. var t = v * (1 - s * (1 - f));
  51182. switch (i) {
  51183. case 0:
  51184. result.r = v;
  51185. result.g = t;
  51186. result.b = p;
  51187. break;
  51188. case 1:
  51189. result.r = q;
  51190. result.g = v;
  51191. result.b = p;
  51192. break;
  51193. case 2:
  51194. result.r = p;
  51195. result.g = v;
  51196. result.b = t;
  51197. break;
  51198. case 3:
  51199. result.r = p;
  51200. result.g = q;
  51201. result.b = v;
  51202. break;
  51203. case 4:
  51204. result.r = t;
  51205. result.g = p;
  51206. result.b = v;
  51207. break;
  51208. default:
  51209. result.r = v;
  51210. result.g = p;
  51211. result.b = q;
  51212. break;
  51213. }
  51214. }
  51215. result.a = 1;
  51216. };
  51217. /**
  51218. * Returns a value clamped between min and max
  51219. * @param value The value to clamp
  51220. * @param min The minimum of value
  51221. * @param max The maximum of value
  51222. * @returns The clamped value.
  51223. */
  51224. ColorCurves.clamp = function (value, min, max) {
  51225. return Math.min(Math.max(value, min), max);
  51226. };
  51227. /**
  51228. * Clones the current color curve instance.
  51229. * @return The cloned curves
  51230. */
  51231. ColorCurves.prototype.clone = function () {
  51232. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  51233. };
  51234. /**
  51235. * Serializes the current color curve instance to a json representation.
  51236. * @return a JSON representation
  51237. */
  51238. ColorCurves.prototype.serialize = function () {
  51239. return BABYLON.SerializationHelper.Serialize(this);
  51240. };
  51241. /**
  51242. * Parses the color curve from a json representation.
  51243. * @param source the JSON source to parse
  51244. * @return The parsed curves
  51245. */
  51246. ColorCurves.Parse = function (source) {
  51247. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  51248. };
  51249. __decorate([
  51250. BABYLON.serialize()
  51251. ], ColorCurves.prototype, "_globalHue", void 0);
  51252. __decorate([
  51253. BABYLON.serialize()
  51254. ], ColorCurves.prototype, "_globalDensity", void 0);
  51255. __decorate([
  51256. BABYLON.serialize()
  51257. ], ColorCurves.prototype, "_globalSaturation", void 0);
  51258. __decorate([
  51259. BABYLON.serialize()
  51260. ], ColorCurves.prototype, "_globalExposure", void 0);
  51261. __decorate([
  51262. BABYLON.serialize()
  51263. ], ColorCurves.prototype, "_highlightsHue", void 0);
  51264. __decorate([
  51265. BABYLON.serialize()
  51266. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  51267. __decorate([
  51268. BABYLON.serialize()
  51269. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  51270. __decorate([
  51271. BABYLON.serialize()
  51272. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  51273. __decorate([
  51274. BABYLON.serialize()
  51275. ], ColorCurves.prototype, "_midtonesHue", void 0);
  51276. __decorate([
  51277. BABYLON.serialize()
  51278. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  51279. __decorate([
  51280. BABYLON.serialize()
  51281. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  51282. __decorate([
  51283. BABYLON.serialize()
  51284. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  51285. return ColorCurves;
  51286. }());
  51287. BABYLON.ColorCurves = ColorCurves;
  51288. })(BABYLON || (BABYLON = {}));
  51289. var BABYLON;
  51290. (function (BABYLON) {
  51291. var PBRMaterialDefines = (function (_super) {
  51292. __extends(PBRMaterialDefines, _super);
  51293. function PBRMaterialDefines() {
  51294. _super.call(this);
  51295. this.ALBEDO = false;
  51296. this.AMBIENT = false;
  51297. this.OPACITY = false;
  51298. this.OPACITYRGB = false;
  51299. this.REFLECTION = false;
  51300. this.EMISSIVE = false;
  51301. this.REFLECTIVITY = false;
  51302. this.BUMP = false;
  51303. this.PARALLAX = false;
  51304. this.PARALLAXOCCLUSION = false;
  51305. this.SPECULAROVERALPHA = false;
  51306. this.CLIPPLANE = false;
  51307. this.ALPHATEST = false;
  51308. this.ALPHAFROMALBEDO = false;
  51309. this.POINTSIZE = false;
  51310. this.FOG = false;
  51311. this.SPECULARTERM = false;
  51312. this.OPACITYFRESNEL = false;
  51313. this.EMISSIVEFRESNEL = false;
  51314. this.FRESNEL = false;
  51315. this.NORMAL = false;
  51316. this.UV1 = false;
  51317. this.UV2 = false;
  51318. this.VERTEXCOLOR = false;
  51319. this.VERTEXALPHA = false;
  51320. this.NUM_BONE_INFLUENCERS = 0;
  51321. this.BonesPerMesh = 0;
  51322. this.INSTANCES = false;
  51323. this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  51324. this.MICROSURFACEAUTOMATIC = false;
  51325. this.EMISSIVEASILLUMINATION = false;
  51326. this.LINKEMISSIVEWITHALBEDO = false;
  51327. this.LIGHTMAP = false;
  51328. this.USELIGHTMAPASSHADOWMAP = false;
  51329. this.REFLECTIONMAP_3D = false;
  51330. this.REFLECTIONMAP_SPHERICAL = false;
  51331. this.REFLECTIONMAP_PLANAR = false;
  51332. this.REFLECTIONMAP_CUBIC = false;
  51333. this.REFLECTIONMAP_PROJECTION = false;
  51334. this.REFLECTIONMAP_SKYBOX = false;
  51335. this.REFLECTIONMAP_EXPLICIT = false;
  51336. this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  51337. this.INVERTCUBICMAP = false;
  51338. this.LOGARITHMICDEPTH = false;
  51339. this.CAMERATONEMAP = false;
  51340. this.CAMERACONTRAST = false;
  51341. this.CAMERACOLORGRADING = false;
  51342. this.CAMERACOLORCURVES = false;
  51343. this.OVERLOADEDVALUES = false;
  51344. this.OVERLOADEDSHADOWVALUES = false;
  51345. this.USESPHERICALFROMREFLECTIONMAP = false;
  51346. this.REFRACTION = false;
  51347. this.REFRACTIONMAP_3D = false;
  51348. this.LINKREFRACTIONTOTRANSPARENCY = false;
  51349. this.REFRACTIONMAPINLINEARSPACE = false;
  51350. this.LODBASEDMICROSFURACE = false;
  51351. this.USEPHYSICALLIGHTFALLOFF = false;
  51352. this.RADIANCEOVERALPHA = false;
  51353. this.USEPMREMREFLECTION = false;
  51354. this.USEPMREMREFRACTION = false;
  51355. this.OPENGLNORMALMAP = false;
  51356. this.INVERTNORMALMAPX = false;
  51357. this.INVERTNORMALMAPY = false;
  51358. this.SHADOWFULLFLOAT = false;
  51359. this.rebuild();
  51360. }
  51361. return PBRMaterialDefines;
  51362. }(BABYLON.MaterialDefines));
  51363. /**
  51364. * The Physically based material of BJS.
  51365. *
  51366. * This offers the main features of a standard PBR material.
  51367. * For more information, please refer to the documentation :
  51368. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  51369. */
  51370. var PBRMaterial = (function (_super) {
  51371. __extends(PBRMaterial, _super);
  51372. /**
  51373. * Instantiates a new PBRMaterial instance.
  51374. *
  51375. * @param name The material name
  51376. * @param scene The scene the material will be use in.
  51377. */
  51378. function PBRMaterial(name, scene) {
  51379. var _this = this;
  51380. _super.call(this, name, scene);
  51381. /**
  51382. * Intensity of the direct lights e.g. the four lights available in your scene.
  51383. * This impacts both the direct diffuse and specular highlights.
  51384. */
  51385. this.directIntensity = 1.0;
  51386. /**
  51387. * Intensity of the emissive part of the material.
  51388. * This helps controlling the emissive effect without modifying the emissive color.
  51389. */
  51390. this.emissiveIntensity = 1.0;
  51391. /**
  51392. * Intensity of the environment e.g. how much the environment will light the object
  51393. * either through harmonics for rough material or through the refelction for shiny ones.
  51394. */
  51395. this.environmentIntensity = 1.0;
  51396. /**
  51397. * This is a special control allowing the reduction of the specular highlights coming from the
  51398. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  51399. */
  51400. this.specularIntensity = 1.0;
  51401. this._lightingInfos = new BABYLON.Vector4(this.directIntensity, this.emissiveIntensity, this.environmentIntensity, this.specularIntensity);
  51402. /**
  51403. * Debug Control allowing disabling the bump map on this material.
  51404. */
  51405. this.disableBumpMap = false;
  51406. /**
  51407. * Debug Control helping enforcing or dropping the darkness of shadows.
  51408. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  51409. */
  51410. this.overloadedShadowIntensity = 1.0;
  51411. /**
  51412. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  51413. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  51414. */
  51415. this.overloadedShadeIntensity = 1.0;
  51416. this._overloadedShadowInfos = new BABYLON.Vector4(this.overloadedShadowIntensity, this.overloadedShadeIntensity, 0.0, 0.0);
  51417. /**
  51418. * The camera exposure used on this material.
  51419. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  51420. * This corresponds to a photographic exposure.
  51421. */
  51422. this.cameraExposure = 1.0;
  51423. /**
  51424. * The camera contrast used on this material.
  51425. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  51426. */
  51427. this.cameraContrast = 1.0;
  51428. /**
  51429. * Color Grading 2D Lookup Texture.
  51430. * This allows special effects like sepia, black and white to sixties rendering style.
  51431. */
  51432. this.cameraColorGradingTexture = null;
  51433. /**
  51434. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  51435. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  51436. * 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;
  51437. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  51438. */
  51439. this.cameraColorCurves = null;
  51440. this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  51441. this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  51442. /**
  51443. * Debug Control allowing to overload the ambient color.
  51444. * This as to be use with the overloadedAmbientIntensity parameter.
  51445. */
  51446. this.overloadedAmbient = BABYLON.Color3.White();
  51447. /**
  51448. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  51449. */
  51450. this.overloadedAmbientIntensity = 0.0;
  51451. /**
  51452. * Debug Control allowing to overload the albedo color.
  51453. * This as to be use with the overloadedAlbedoIntensity parameter.
  51454. */
  51455. this.overloadedAlbedo = BABYLON.Color3.White();
  51456. /**
  51457. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  51458. */
  51459. this.overloadedAlbedoIntensity = 0.0;
  51460. /**
  51461. * Debug Control allowing to overload the reflectivity color.
  51462. * This as to be use with the overloadedReflectivityIntensity parameter.
  51463. */
  51464. this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  51465. /**
  51466. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  51467. */
  51468. this.overloadedReflectivityIntensity = 0.0;
  51469. /**
  51470. * Debug Control allowing to overload the emissive color.
  51471. * This as to be use with the overloadedEmissiveIntensity parameter.
  51472. */
  51473. this.overloadedEmissive = BABYLON.Color3.White();
  51474. /**
  51475. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  51476. */
  51477. this.overloadedEmissiveIntensity = 0.0;
  51478. this._overloadedIntensity = new BABYLON.Vector4(this.overloadedAmbientIntensity, this.overloadedAlbedoIntensity, this.overloadedReflectivityIntensity, this.overloadedEmissiveIntensity);
  51479. /**
  51480. * Debug Control allowing to overload the reflection color.
  51481. * This as to be use with the overloadedReflectionIntensity parameter.
  51482. */
  51483. this.overloadedReflection = BABYLON.Color3.White();
  51484. /**
  51485. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  51486. */
  51487. this.overloadedReflectionIntensity = 0.0;
  51488. /**
  51489. * Debug Control allowing to overload the microsurface.
  51490. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  51491. */
  51492. this.overloadedMicroSurface = 0.0;
  51493. /**
  51494. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  51495. */
  51496. this.overloadedMicroSurfaceIntensity = 0.0;
  51497. this._overloadedMicroSurface = new BABYLON.Vector3(this.overloadedMicroSurface, this.overloadedMicroSurfaceIntensity, this.overloadedReflectionIntensity);
  51498. /**
  51499. * AKA Occlusion Texture Intensity in other nomenclature.
  51500. */
  51501. this.ambientTextureStrength = 1.0;
  51502. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  51503. /**
  51504. * AKA Diffuse Color in other nomenclature.
  51505. */
  51506. this.albedoColor = new BABYLON.Color3(1, 1, 1);
  51507. /**
  51508. * AKA Specular Color in other nomenclature.
  51509. */
  51510. this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  51511. this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  51512. this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  51513. /**
  51514. * AKA Glossiness in other nomenclature.
  51515. */
  51516. this.microSurface = 0.9;
  51517. /**
  51518. * source material index of refraction (IOR)' / 'destination material IOR.
  51519. */
  51520. this.indexOfRefraction = 0.66;
  51521. /**
  51522. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  51523. */
  51524. this.invertRefractionY = false;
  51525. /**
  51526. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  51527. * Materials half opaque for instance using refraction could benefit from this control.
  51528. */
  51529. this.linkRefractionWithTransparency = false;
  51530. /**
  51531. * The emissive and albedo are linked to never be more than one (Energy conservation).
  51532. */
  51533. this.linkEmissiveWithAlbedo = false;
  51534. this.useLightmapAsShadowmap = false;
  51535. /**
  51536. * In this mode, the emissive informtaion will always be added to the lighting once.
  51537. * A light for instance can be thought as emissive.
  51538. */
  51539. this.useEmissiveAsIllumination = false;
  51540. /**
  51541. * Secifies that the alpha is coming form the albedo channel alpha channel.
  51542. */
  51543. this.useAlphaFromAlbedoTexture = false;
  51544. /**
  51545. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  51546. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  51547. */
  51548. this.useSpecularOverAlpha = true;
  51549. /**
  51550. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  51551. */
  51552. this.useMicroSurfaceFromReflectivityMapAlpha = false;
  51553. /**
  51554. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  51555. * The material will try to infer what glossiness each pixel should be.
  51556. */
  51557. this.useAutoMicroSurfaceFromReflectivityMap = false;
  51558. /**
  51559. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  51560. * the creation of the material.
  51561. */
  51562. this.useScalarInLinearSpace = false;
  51563. /**
  51564. * BJS is using an harcoded light falloff based on a manually sets up range.
  51565. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  51566. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  51567. */
  51568. this.usePhysicalLightFalloff = true;
  51569. /**
  51570. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  51571. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  51572. */
  51573. this.useRadianceOverAlpha = true;
  51574. /**
  51575. * Allows using the bump map in parallax mode.
  51576. */
  51577. this.useParallax = false;
  51578. /**
  51579. * Allows using the bump map in parallax occlusion mode.
  51580. */
  51581. this.useParallaxOcclusion = false;
  51582. /**
  51583. * Controls the scale bias of the parallax mode.
  51584. */
  51585. this.parallaxScaleBias = 0.05;
  51586. /**
  51587. * If sets to true, disables all the lights affecting the material.
  51588. */
  51589. this.disableLighting = false;
  51590. /**
  51591. * Number of Simultaneous lights allowed on the material.
  51592. */
  51593. this.maxSimultaneousLights = 4;
  51594. /**
  51595. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  51596. */
  51597. this.invertNormalMapX = false;
  51598. /**
  51599. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  51600. */
  51601. this.invertNormalMapY = false;
  51602. this._renderTargets = new BABYLON.SmartArray(16);
  51603. this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  51604. this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  51605. this._tempColor = new BABYLON.Color3();
  51606. this._defines = new PBRMaterialDefines();
  51607. this._cachedDefines = new PBRMaterialDefines();
  51608. this._myScene = null;
  51609. this._myShadowGenerator = null;
  51610. this._cachedDefines.BonesPerMesh = -1;
  51611. this.getRenderTargetTextures = function () {
  51612. _this._renderTargets.reset();
  51613. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  51614. _this._renderTargets.push(_this.reflectionTexture);
  51615. }
  51616. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  51617. _this._renderTargets.push(_this.refractionTexture);
  51618. }
  51619. return _this._renderTargets;
  51620. };
  51621. }
  51622. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  51623. get: function () {
  51624. return this._useLogarithmicDepth;
  51625. },
  51626. set: function (value) {
  51627. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  51628. },
  51629. enumerable: true,
  51630. configurable: true
  51631. });
  51632. PBRMaterial.prototype.needAlphaBlending = function () {
  51633. if (this.linkRefractionWithTransparency) {
  51634. return false;
  51635. }
  51636. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  51637. };
  51638. PBRMaterial.prototype.needAlphaTesting = function () {
  51639. if (this.linkRefractionWithTransparency) {
  51640. return false;
  51641. }
  51642. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  51643. };
  51644. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  51645. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  51646. };
  51647. PBRMaterial.prototype.getAlphaTestTexture = function () {
  51648. return this.albedoTexture;
  51649. };
  51650. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  51651. if (!mesh) {
  51652. return true;
  51653. }
  51654. if (this._defines.INSTANCES !== useInstances) {
  51655. return false;
  51656. }
  51657. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  51658. return true;
  51659. }
  51660. return false;
  51661. };
  51662. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  51663. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  51664. };
  51665. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  51666. if (!useScalarInLinear) {
  51667. color.toLinearSpaceToRef(ref);
  51668. }
  51669. else {
  51670. ref.r = color.r;
  51671. ref.g = color.g;
  51672. ref.b = color.b;
  51673. }
  51674. };
  51675. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  51676. var lightIndex = 0;
  51677. var depthValuesAlreadySet = false;
  51678. for (var index = 0; index < scene.lights.length; index++) {
  51679. var light = scene.lights[index];
  51680. if (!light.isEnabled()) {
  51681. continue;
  51682. }
  51683. if (!light.canAffectMesh(mesh)) {
  51684. continue;
  51685. }
  51686. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  51687. // GAMMA CORRECTION.
  51688. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  51689. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  51690. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  51691. if (defines["SPECULARTERM"]) {
  51692. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  51693. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  51694. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  51695. }
  51696. // Shadows
  51697. if (scene.shadowsEnabled) {
  51698. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  51699. }
  51700. lightIndex++;
  51701. if (lightIndex === maxSimultaneousLights)
  51702. break;
  51703. }
  51704. };
  51705. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  51706. if (this.checkReadyOnlyOnce) {
  51707. if (this._wasPreviouslyReady) {
  51708. return true;
  51709. }
  51710. }
  51711. var scene = this.getScene();
  51712. if (!this.checkReadyOnEveryCall) {
  51713. if (this._renderId === scene.getRenderId()) {
  51714. if (this._checkCache(scene, mesh, useInstances)) {
  51715. return true;
  51716. }
  51717. }
  51718. }
  51719. var engine = scene.getEngine();
  51720. var needNormals = false;
  51721. var needUVs = false;
  51722. this._defines.reset();
  51723. if (scene.texturesEnabled) {
  51724. if (scene.getEngine().getCaps().textureLOD) {
  51725. this._defines.LODBASEDMICROSFURACE = true;
  51726. }
  51727. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  51728. if (!this.albedoTexture.isReady()) {
  51729. return false;
  51730. }
  51731. else {
  51732. needUVs = true;
  51733. this._defines.ALBEDO = true;
  51734. }
  51735. }
  51736. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  51737. if (!this.ambientTexture.isReady()) {
  51738. return false;
  51739. }
  51740. else {
  51741. needUVs = true;
  51742. this._defines.AMBIENT = true;
  51743. }
  51744. }
  51745. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  51746. if (!this.opacityTexture.isReady()) {
  51747. return false;
  51748. }
  51749. else {
  51750. needUVs = true;
  51751. this._defines.OPACITY = true;
  51752. if (this.opacityTexture.getAlphaFromRGB) {
  51753. this._defines.OPACITYRGB = true;
  51754. }
  51755. }
  51756. }
  51757. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  51758. if (!this.reflectionTexture.isReady()) {
  51759. return false;
  51760. }
  51761. else {
  51762. needNormals = true;
  51763. this._defines.REFLECTION = true;
  51764. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  51765. this._defines.INVERTCUBICMAP = true;
  51766. }
  51767. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  51768. switch (this.reflectionTexture.coordinatesMode) {
  51769. case BABYLON.Texture.CUBIC_MODE:
  51770. case BABYLON.Texture.INVCUBIC_MODE:
  51771. this._defines.REFLECTIONMAP_CUBIC = true;
  51772. break;
  51773. case BABYLON.Texture.EXPLICIT_MODE:
  51774. this._defines.REFLECTIONMAP_EXPLICIT = true;
  51775. break;
  51776. case BABYLON.Texture.PLANAR_MODE:
  51777. this._defines.REFLECTIONMAP_PLANAR = true;
  51778. break;
  51779. case BABYLON.Texture.PROJECTION_MODE:
  51780. this._defines.REFLECTIONMAP_PROJECTION = true;
  51781. break;
  51782. case BABYLON.Texture.SKYBOX_MODE:
  51783. this._defines.REFLECTIONMAP_SKYBOX = true;
  51784. break;
  51785. case BABYLON.Texture.SPHERICAL_MODE:
  51786. this._defines.REFLECTIONMAP_SPHERICAL = true;
  51787. break;
  51788. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  51789. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  51790. break;
  51791. }
  51792. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  51793. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  51794. needNormals = true;
  51795. if (this.reflectionTexture.isPMREM) {
  51796. this._defines.USEPMREMREFLECTION = true;
  51797. }
  51798. }
  51799. }
  51800. }
  51801. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  51802. if (!this.lightmapTexture.isReady()) {
  51803. return false;
  51804. }
  51805. else {
  51806. needUVs = true;
  51807. this._defines.LIGHTMAP = true;
  51808. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  51809. }
  51810. }
  51811. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  51812. if (!this.emissiveTexture.isReady()) {
  51813. return false;
  51814. }
  51815. else {
  51816. needUVs = true;
  51817. this._defines.EMISSIVE = true;
  51818. }
  51819. }
  51820. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  51821. if (!this.reflectivityTexture.isReady()) {
  51822. return false;
  51823. }
  51824. else {
  51825. needUVs = true;
  51826. this._defines.REFLECTIVITY = true;
  51827. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  51828. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  51829. }
  51830. }
  51831. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  51832. if (!this.bumpTexture.isReady()) {
  51833. return false;
  51834. }
  51835. else {
  51836. needUVs = true;
  51837. this._defines.BUMP = true;
  51838. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  51839. this._defines.PARALLAX = true;
  51840. if (this.useParallaxOcclusion) {
  51841. this._defines.PARALLAXOCCLUSION = true;
  51842. }
  51843. }
  51844. if (this.invertNormalMapX) {
  51845. this._defines.INVERTNORMALMAPX = true;
  51846. }
  51847. if (this.invertNormalMapY) {
  51848. this._defines.INVERTNORMALMAPY = true;
  51849. }
  51850. }
  51851. }
  51852. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  51853. if (!this.refractionTexture.isReady()) {
  51854. return false;
  51855. }
  51856. else {
  51857. needUVs = true;
  51858. this._defines.REFRACTION = true;
  51859. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  51860. if (this.linkRefractionWithTransparency) {
  51861. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  51862. }
  51863. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  51864. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  51865. if (this.refractionTexture.isPMREM) {
  51866. this._defines.USEPMREMREFRACTION = true;
  51867. }
  51868. }
  51869. }
  51870. }
  51871. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  51872. if (!this.cameraColorGradingTexture.isReady()) {
  51873. return false;
  51874. }
  51875. else {
  51876. this._defines.CAMERACOLORGRADING = true;
  51877. }
  51878. }
  51879. }
  51880. // Effect
  51881. if (scene.clipPlane) {
  51882. this._defines.CLIPPLANE = true;
  51883. }
  51884. if (engine.getAlphaTesting()) {
  51885. this._defines.ALPHATEST = true;
  51886. }
  51887. if (this._shouldUseAlphaFromAlbedoTexture()) {
  51888. this._defines.ALPHAFROMALBEDO = true;
  51889. }
  51890. if (this.useEmissiveAsIllumination) {
  51891. this._defines.EMISSIVEASILLUMINATION = true;
  51892. }
  51893. if (this.linkEmissiveWithAlbedo) {
  51894. this._defines.LINKEMISSIVEWITHALBEDO = true;
  51895. }
  51896. if (this.useLogarithmicDepth) {
  51897. this._defines.LOGARITHMICDEPTH = true;
  51898. }
  51899. if (this.cameraContrast != 1) {
  51900. this._defines.CAMERACONTRAST = true;
  51901. }
  51902. if (this.cameraExposure != 1) {
  51903. this._defines.CAMERATONEMAP = true;
  51904. }
  51905. if (this.cameraColorCurves) {
  51906. this._defines.CAMERACOLORCURVES = true;
  51907. }
  51908. if (this.overloadedShadeIntensity != 1 ||
  51909. this.overloadedShadowIntensity != 1) {
  51910. this._defines.OVERLOADEDSHADOWVALUES = true;
  51911. }
  51912. if (this.overloadedMicroSurfaceIntensity > 0 ||
  51913. this.overloadedEmissiveIntensity > 0 ||
  51914. this.overloadedReflectivityIntensity > 0 ||
  51915. this.overloadedAlbedoIntensity > 0 ||
  51916. this.overloadedAmbientIntensity > 0 ||
  51917. this.overloadedReflectionIntensity > 0) {
  51918. this._defines.OVERLOADEDVALUES = true;
  51919. }
  51920. // Point size
  51921. if (this.pointsCloud || scene.forcePointsCloud) {
  51922. this._defines.POINTSIZE = true;
  51923. }
  51924. // Fog
  51925. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  51926. this._defines.FOG = true;
  51927. }
  51928. if (scene.lightsEnabled && !this.disableLighting) {
  51929. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  51930. }
  51931. if (BABYLON.StandardMaterial.FresnelEnabled) {
  51932. // Fresnel
  51933. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  51934. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  51935. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  51936. this._defines.OPACITYFRESNEL = true;
  51937. }
  51938. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  51939. this._defines.EMISSIVEFRESNEL = true;
  51940. }
  51941. needNormals = true;
  51942. this._defines.FRESNEL = true;
  51943. }
  51944. }
  51945. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  51946. this._defines.SPECULAROVERALPHA = true;
  51947. }
  51948. if (this.usePhysicalLightFalloff) {
  51949. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  51950. }
  51951. if (this.useRadianceOverAlpha) {
  51952. this._defines.RADIANCEOVERALPHA = true;
  51953. }
  51954. // Attribs
  51955. if (mesh) {
  51956. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  51957. this._defines.NORMAL = true;
  51958. }
  51959. if (needUVs) {
  51960. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  51961. this._defines.UV1 = true;
  51962. }
  51963. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  51964. this._defines.UV2 = true;
  51965. }
  51966. }
  51967. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  51968. this._defines.VERTEXCOLOR = true;
  51969. if (mesh.hasVertexAlpha) {
  51970. this._defines.VERTEXALPHA = true;
  51971. }
  51972. }
  51973. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  51974. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  51975. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  51976. }
  51977. // Instances
  51978. if (useInstances) {
  51979. this._defines.INSTANCES = true;
  51980. }
  51981. }
  51982. // Get correct effect
  51983. if (!this._defines.isEqual(this._cachedDefines)) {
  51984. this._defines.cloneTo(this._cachedDefines);
  51985. scene.resetCachedMaterial();
  51986. // Fallbacks
  51987. var fallbacks = new BABYLON.EffectFallbacks();
  51988. if (this._defines.REFLECTION) {
  51989. fallbacks.addFallback(0, "REFLECTION");
  51990. }
  51991. if (this._defines.REFRACTION) {
  51992. fallbacks.addFallback(0, "REFRACTION");
  51993. }
  51994. if (this._defines.REFLECTIVITY) {
  51995. fallbacks.addFallback(0, "REFLECTIVITY");
  51996. }
  51997. if (this._defines.BUMP) {
  51998. fallbacks.addFallback(0, "BUMP");
  51999. }
  52000. if (this._defines.PARALLAX) {
  52001. fallbacks.addFallback(1, "PARALLAX");
  52002. }
  52003. if (this._defines.PARALLAXOCCLUSION) {
  52004. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  52005. }
  52006. if (this._defines.SPECULAROVERALPHA) {
  52007. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  52008. }
  52009. if (this._defines.FOG) {
  52010. fallbacks.addFallback(1, "FOG");
  52011. }
  52012. if (this._defines.POINTSIZE) {
  52013. fallbacks.addFallback(0, "POINTSIZE");
  52014. }
  52015. if (this._defines.LOGARITHMICDEPTH) {
  52016. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  52017. }
  52018. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  52019. if (this._defines.SPECULARTERM) {
  52020. fallbacks.addFallback(0, "SPECULARTERM");
  52021. }
  52022. if (this._defines.OPACITYFRESNEL) {
  52023. fallbacks.addFallback(1, "OPACITYFRESNEL");
  52024. }
  52025. if (this._defines.EMISSIVEFRESNEL) {
  52026. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  52027. }
  52028. if (this._defines.FRESNEL) {
  52029. fallbacks.addFallback(3, "FRESNEL");
  52030. }
  52031. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  52032. fallbacks.addCPUSkinningFallback(0, mesh);
  52033. }
  52034. //Attributes
  52035. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52036. if (this._defines.NORMAL) {
  52037. attribs.push(BABYLON.VertexBuffer.NormalKind);
  52038. }
  52039. if (this._defines.UV1) {
  52040. attribs.push(BABYLON.VertexBuffer.UVKind);
  52041. }
  52042. if (this._defines.UV2) {
  52043. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52044. }
  52045. if (this._defines.VERTEXCOLOR) {
  52046. attribs.push(BABYLON.VertexBuffer.ColorKind);
  52047. }
  52048. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  52049. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  52050. // Legacy browser patch
  52051. var join = this._defines.toString();
  52052. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  52053. "vFogInfos", "vFogColor", "pointSize",
  52054. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  52055. "mBones",
  52056. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  52057. "depthValues",
  52058. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  52059. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  52060. "logarithmicDepthConstant",
  52061. "vSphericalX", "vSphericalY", "vSphericalZ",
  52062. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  52063. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  52064. "vMicrosurfaceTextureLods",
  52065. "vCameraInfos"
  52066. ];
  52067. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  52068. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  52069. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  52070. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  52071. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  52072. }
  52073. if (!this._effect.isReady()) {
  52074. return false;
  52075. }
  52076. this._renderId = scene.getRenderId();
  52077. this._wasPreviouslyReady = true;
  52078. if (mesh) {
  52079. if (!mesh._materialDefines) {
  52080. mesh._materialDefines = new PBRMaterialDefines();
  52081. }
  52082. this._defines.cloneTo(mesh._materialDefines);
  52083. }
  52084. return true;
  52085. };
  52086. PBRMaterial.prototype.unbind = function () {
  52087. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  52088. this._effect.setTexture("reflection2DSampler", null);
  52089. }
  52090. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  52091. this._effect.setTexture("refraction2DSampler", null);
  52092. }
  52093. _super.prototype.unbind.call(this);
  52094. };
  52095. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  52096. this._effect.setMatrix("world", world);
  52097. };
  52098. PBRMaterial.prototype.bind = function (world, mesh) {
  52099. this._myScene = this.getScene();
  52100. // Matrices
  52101. this.bindOnlyWorldMatrix(world);
  52102. // Bones
  52103. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  52104. if (this._myScene.getCachedMaterial() !== this) {
  52105. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  52106. if (BABYLON.StandardMaterial.FresnelEnabled) {
  52107. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  52108. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  52109. }
  52110. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  52111. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  52112. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  52113. }
  52114. }
  52115. // Textures
  52116. if (this._myScene.texturesEnabled) {
  52117. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  52118. this._effect.setTexture("albedoSampler", this.albedoTexture);
  52119. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  52120. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  52121. }
  52122. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  52123. this._effect.setTexture("ambientSampler", this.ambientTexture);
  52124. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  52125. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  52126. }
  52127. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  52128. this._effect.setTexture("opacitySampler", this.opacityTexture);
  52129. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  52130. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  52131. }
  52132. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  52133. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  52134. if (this.reflectionTexture.isCube) {
  52135. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  52136. }
  52137. else {
  52138. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  52139. }
  52140. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  52141. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  52142. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  52143. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  52144. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  52145. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  52146. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  52147. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  52148. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  52149. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  52150. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  52151. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  52152. }
  52153. }
  52154. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  52155. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  52156. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  52157. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  52158. }
  52159. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  52160. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  52161. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  52162. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  52163. }
  52164. if (this.reflectivityTexture && BABYLON.StandardMaterial.SpecularTextureEnabled) {
  52165. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  52166. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  52167. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  52168. }
  52169. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  52170. this._effect.setTexture("bumpSampler", this.bumpTexture);
  52171. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  52172. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  52173. }
  52174. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  52175. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  52176. var depth = 1.0;
  52177. if (this.refractionTexture.isCube) {
  52178. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  52179. }
  52180. else {
  52181. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  52182. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  52183. if (this.refractionTexture.depth) {
  52184. depth = this.refractionTexture.depth;
  52185. }
  52186. }
  52187. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  52188. }
  52189. if ((this.reflectionTexture || this.refractionTexture)) {
  52190. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  52191. }
  52192. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  52193. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  52194. }
  52195. }
  52196. // Clip plane
  52197. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  52198. // Point size
  52199. if (this.pointsCloud) {
  52200. this._effect.setFloat("pointSize", this.pointSize);
  52201. }
  52202. // Colors
  52203. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  52204. // GAMMA CORRECTION.
  52205. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  52206. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  52207. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  52208. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  52209. // GAMMA CORRECTION.
  52210. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  52211. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  52212. // GAMMA CORRECTION.
  52213. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  52214. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  52215. }
  52216. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  52217. // GAMMA CORRECTION.
  52218. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  52219. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  52220. // Lights
  52221. if (this._myScene.lightsEnabled && !this.disableLighting) {
  52222. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  52223. }
  52224. // View
  52225. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  52226. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  52227. }
  52228. // Fog
  52229. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  52230. this._lightingInfos.x = this.directIntensity;
  52231. this._lightingInfos.y = this.emissiveIntensity;
  52232. this._lightingInfos.z = this.environmentIntensity;
  52233. this._lightingInfos.w = this.specularIntensity;
  52234. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  52235. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  52236. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  52237. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  52238. this._cameraInfos.x = this.cameraExposure;
  52239. this._cameraInfos.y = this.cameraContrast;
  52240. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  52241. if (this.cameraColorCurves) {
  52242. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  52243. }
  52244. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  52245. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  52246. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  52247. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  52248. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  52249. this.convertColorToLinearSpaceToRef(this.overloadedAmbient, this._tempColor);
  52250. this._effect.setColor3("vOverloadedAmbient", this._tempColor);
  52251. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  52252. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  52253. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  52254. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  52255. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  52256. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  52257. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  52258. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  52259. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  52260. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  52261. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  52262. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  52263. // Log. depth
  52264. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  52265. }
  52266. _super.prototype.bind.call(this, world, mesh);
  52267. this._myScene = null;
  52268. };
  52269. PBRMaterial.prototype.getAnimatables = function () {
  52270. var results = [];
  52271. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  52272. results.push(this.albedoTexture);
  52273. }
  52274. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  52275. results.push(this.ambientTexture);
  52276. }
  52277. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  52278. results.push(this.opacityTexture);
  52279. }
  52280. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  52281. results.push(this.reflectionTexture);
  52282. }
  52283. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  52284. results.push(this.emissiveTexture);
  52285. }
  52286. if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  52287. results.push(this.reflectivityTexture);
  52288. }
  52289. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  52290. results.push(this.bumpTexture);
  52291. }
  52292. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  52293. results.push(this.lightmapTexture);
  52294. }
  52295. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  52296. results.push(this.refractionTexture);
  52297. }
  52298. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  52299. results.push(this.cameraColorGradingTexture);
  52300. }
  52301. return results;
  52302. };
  52303. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  52304. if (forceDisposeTextures) {
  52305. if (this.albedoTexture) {
  52306. this.albedoTexture.dispose();
  52307. }
  52308. if (this.ambientTexture) {
  52309. this.ambientTexture.dispose();
  52310. }
  52311. if (this.opacityTexture) {
  52312. this.opacityTexture.dispose();
  52313. }
  52314. if (this.reflectionTexture) {
  52315. this.reflectionTexture.dispose();
  52316. }
  52317. if (this.emissiveTexture) {
  52318. this.emissiveTexture.dispose();
  52319. }
  52320. if (this.reflectivityTexture) {
  52321. this.reflectivityTexture.dispose();
  52322. }
  52323. if (this.bumpTexture) {
  52324. this.bumpTexture.dispose();
  52325. }
  52326. if (this.lightmapTexture) {
  52327. this.lightmapTexture.dispose();
  52328. }
  52329. if (this.refractionTexture) {
  52330. this.refractionTexture.dispose();
  52331. }
  52332. if (this.cameraColorGradingTexture) {
  52333. this.cameraColorGradingTexture.dispose();
  52334. }
  52335. }
  52336. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  52337. };
  52338. PBRMaterial.prototype.clone = function (name) {
  52339. var _this = this;
  52340. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  52341. };
  52342. PBRMaterial.prototype.serialize = function () {
  52343. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  52344. serializationObject.customType = "BABYLON.PBRMaterial";
  52345. return serializationObject;
  52346. };
  52347. // Statics
  52348. PBRMaterial.Parse = function (source, scene, rootUrl) {
  52349. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  52350. };
  52351. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  52352. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  52353. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  52354. PBRMaterial._scaledReflection = new BABYLON.Color3();
  52355. __decorate([
  52356. BABYLON.serialize()
  52357. ], PBRMaterial.prototype, "directIntensity", void 0);
  52358. __decorate([
  52359. BABYLON.serialize()
  52360. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  52361. __decorate([
  52362. BABYLON.serialize()
  52363. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  52364. __decorate([
  52365. BABYLON.serialize()
  52366. ], PBRMaterial.prototype, "specularIntensity", void 0);
  52367. __decorate([
  52368. BABYLON.serialize()
  52369. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  52370. __decorate([
  52371. BABYLON.serialize()
  52372. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  52373. __decorate([
  52374. BABYLON.serialize()
  52375. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  52376. __decorate([
  52377. BABYLON.serialize()
  52378. ], PBRMaterial.prototype, "cameraExposure", void 0);
  52379. __decorate([
  52380. BABYLON.serialize()
  52381. ], PBRMaterial.prototype, "cameraContrast", void 0);
  52382. __decorate([
  52383. BABYLON.serializeAsTexture()
  52384. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  52385. __decorate([
  52386. BABYLON.serializeAsColorCurves()
  52387. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  52388. __decorate([
  52389. BABYLON.serializeAsColor3()
  52390. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  52391. __decorate([
  52392. BABYLON.serialize()
  52393. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  52394. __decorate([
  52395. BABYLON.serializeAsColor3()
  52396. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  52397. __decorate([
  52398. BABYLON.serialize()
  52399. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  52400. __decorate([
  52401. BABYLON.serializeAsColor3()
  52402. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  52403. __decorate([
  52404. BABYLON.serialize()
  52405. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  52406. __decorate([
  52407. BABYLON.serializeAsColor3()
  52408. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  52409. __decorate([
  52410. BABYLON.serialize()
  52411. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  52412. __decorate([
  52413. BABYLON.serializeAsColor3()
  52414. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  52415. __decorate([
  52416. BABYLON.serialize()
  52417. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  52418. __decorate([
  52419. BABYLON.serialize()
  52420. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  52421. __decorate([
  52422. BABYLON.serialize()
  52423. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  52424. __decorate([
  52425. BABYLON.serializeAsTexture()
  52426. ], PBRMaterial.prototype, "albedoTexture", void 0);
  52427. __decorate([
  52428. BABYLON.serializeAsTexture()
  52429. ], PBRMaterial.prototype, "ambientTexture", void 0);
  52430. __decorate([
  52431. BABYLON.serialize()
  52432. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  52433. __decorate([
  52434. BABYLON.serializeAsTexture()
  52435. ], PBRMaterial.prototype, "opacityTexture", void 0);
  52436. __decorate([
  52437. BABYLON.serializeAsTexture()
  52438. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  52439. __decorate([
  52440. BABYLON.serializeAsTexture()
  52441. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  52442. __decorate([
  52443. BABYLON.serializeAsTexture()
  52444. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  52445. __decorate([
  52446. BABYLON.serializeAsTexture()
  52447. ], PBRMaterial.prototype, "bumpTexture", void 0);
  52448. __decorate([
  52449. BABYLON.serializeAsTexture()
  52450. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  52451. __decorate([
  52452. BABYLON.serializeAsTexture()
  52453. ], PBRMaterial.prototype, "refractionTexture", void 0);
  52454. __decorate([
  52455. BABYLON.serializeAsColor3("ambient")
  52456. ], PBRMaterial.prototype, "ambientColor", void 0);
  52457. __decorate([
  52458. BABYLON.serializeAsColor3("albedo")
  52459. ], PBRMaterial.prototype, "albedoColor", void 0);
  52460. __decorate([
  52461. BABYLON.serializeAsColor3("reflectivity")
  52462. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  52463. __decorate([
  52464. BABYLON.serializeAsColor3("reflection")
  52465. ], PBRMaterial.prototype, "reflectionColor", void 0);
  52466. __decorate([
  52467. BABYLON.serializeAsColor3("emissive")
  52468. ], PBRMaterial.prototype, "emissiveColor", void 0);
  52469. __decorate([
  52470. BABYLON.serialize()
  52471. ], PBRMaterial.prototype, "microSurface", void 0);
  52472. __decorate([
  52473. BABYLON.serialize()
  52474. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  52475. __decorate([
  52476. BABYLON.serialize()
  52477. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  52478. __decorate([
  52479. BABYLON.serializeAsFresnelParameters()
  52480. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  52481. __decorate([
  52482. BABYLON.serializeAsFresnelParameters()
  52483. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  52484. __decorate([
  52485. BABYLON.serialize()
  52486. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  52487. __decorate([
  52488. BABYLON.serialize()
  52489. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  52490. __decorate([
  52491. BABYLON.serialize()
  52492. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  52493. __decorate([
  52494. BABYLON.serialize()
  52495. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  52496. __decorate([
  52497. BABYLON.serialize()
  52498. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  52499. __decorate([
  52500. BABYLON.serialize()
  52501. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  52502. __decorate([
  52503. BABYLON.serialize()
  52504. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  52505. __decorate([
  52506. BABYLON.serialize()
  52507. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  52508. __decorate([
  52509. BABYLON.serialize()
  52510. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  52511. __decorate([
  52512. BABYLON.serialize()
  52513. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  52514. __decorate([
  52515. BABYLON.serialize()
  52516. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  52517. __decorate([
  52518. BABYLON.serialize()
  52519. ], PBRMaterial.prototype, "useParallax", void 0);
  52520. __decorate([
  52521. BABYLON.serialize()
  52522. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  52523. __decorate([
  52524. BABYLON.serialize()
  52525. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  52526. __decorate([
  52527. BABYLON.serialize()
  52528. ], PBRMaterial.prototype, "disableLighting", void 0);
  52529. __decorate([
  52530. BABYLON.serialize()
  52531. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  52532. __decorate([
  52533. BABYLON.serialize()
  52534. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  52535. __decorate([
  52536. BABYLON.serialize()
  52537. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  52538. __decorate([
  52539. BABYLON.serialize()
  52540. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  52541. return PBRMaterial;
  52542. }(BABYLON.Material));
  52543. BABYLON.PBRMaterial = PBRMaterial;
  52544. })(BABYLON || (BABYLON = {}));
  52545. var BABYLON;
  52546. (function (BABYLON) {
  52547. var DebugLayer = (function () {
  52548. function DebugLayer(scene) {
  52549. var _this = this;
  52550. this._transformationMatrix = BABYLON.Matrix.Identity();
  52551. this._enabled = false;
  52552. this._labelsEnabled = false;
  52553. this._displayStatistics = true;
  52554. this._displayTree = false;
  52555. this._displayLogs = false;
  52556. this._skeletonViewers = new Array();
  52557. this._identityMatrix = BABYLON.Matrix.Identity();
  52558. this.axisRatio = 0.02;
  52559. this.accentColor = "orange";
  52560. this._scene = scene;
  52561. this._syncPositions = function () {
  52562. var engine = _this._scene.getEngine();
  52563. var canvasRect = engine.getRenderingCanvasClientRect();
  52564. if (_this._showUI) {
  52565. _this._statsDiv.style.left = (canvasRect.width - 410) + "px";
  52566. _this._statsDiv.style.top = (canvasRect.height - 290) + "px";
  52567. _this._statsDiv.style.width = "400px";
  52568. _this._statsDiv.style.height = "auto";
  52569. _this._statsSubsetDiv.style.maxHeight = "240px";
  52570. _this._optionsDiv.style.left = "0px";
  52571. _this._optionsDiv.style.top = "10px";
  52572. _this._optionsDiv.style.width = "200px";
  52573. _this._optionsDiv.style.height = "auto";
  52574. _this._optionsSubsetDiv.style.maxHeight = (canvasRect.height - 225) + "px";
  52575. _this._logDiv.style.left = "0px";
  52576. _this._logDiv.style.top = (canvasRect.height - 170) + "px";
  52577. _this._logDiv.style.width = "600px";
  52578. _this._logDiv.style.height = "160px";
  52579. _this._treeDiv.style.left = (canvasRect.width - 310) + "px";
  52580. _this._treeDiv.style.top = "10px";
  52581. _this._treeDiv.style.width = "300px";
  52582. _this._treeDiv.style.height = "auto";
  52583. _this._treeSubsetDiv.style.maxHeight = (canvasRect.height - 340) + "px";
  52584. }
  52585. _this._globalDiv.style.left = canvasRect.left + "px";
  52586. _this._globalDiv.style.top = canvasRect.top + "px";
  52587. _this._drawingCanvas.style.left = "0px";
  52588. _this._drawingCanvas.style.top = "0px";
  52589. _this._drawingCanvas.style.width = engine.getRenderWidth() + "px";
  52590. _this._drawingCanvas.style.height = engine.getRenderHeight() + "px";
  52591. var devicePixelRatio = window.devicePixelRatio || 1;
  52592. var context = _this._drawingContext;
  52593. var backingStoreRatio = context.webkitBackingStorePixelRatio ||
  52594. context.mozBackingStorePixelRatio ||
  52595. context.msBackingStorePixelRatio ||
  52596. context.oBackingStorePixelRatio ||
  52597. context.backingStorePixelRatio || 1;
  52598. _this._ratio = devicePixelRatio / backingStoreRatio;
  52599. _this._drawingCanvas.width = engine.getRenderWidth() * _this._ratio;
  52600. _this._drawingCanvas.height = engine.getRenderHeight() * _this._ratio;
  52601. };
  52602. this._onCanvasClick = function (evt) {
  52603. _this._clickPosition = {
  52604. x: evt.clientX * _this._ratio,
  52605. y: evt.clientY * _this._ratio
  52606. };
  52607. };
  52608. this._syncUI = function () {
  52609. if (_this._showUI) {
  52610. if (_this._displayStatistics) {
  52611. _this._displayStats();
  52612. _this._statsDiv.style.display = "";
  52613. }
  52614. else {
  52615. _this._statsDiv.style.display = "none";
  52616. }
  52617. if (_this._displayLogs) {
  52618. _this._logDiv.style.display = "";
  52619. }
  52620. else {
  52621. _this._logDiv.style.display = "none";
  52622. }
  52623. if (_this._displayTree) {
  52624. _this._treeDiv.style.display = "";
  52625. if (_this._needToRefreshMeshesTree) {
  52626. _this._needToRefreshMeshesTree = false;
  52627. _this._refreshMeshesTreeContent();
  52628. }
  52629. }
  52630. else {
  52631. _this._treeDiv.style.display = "none";
  52632. }
  52633. }
  52634. };
  52635. this._syncData = function () {
  52636. if (_this._labelsEnabled || !_this._showUI) {
  52637. _this._camera.getViewMatrix().multiplyToRef(_this._camera.getProjectionMatrix(), _this._transformationMatrix);
  52638. _this._drawingContext.clearRect(0, 0, _this._drawingCanvas.width, _this._drawingCanvas.height);
  52639. var engine = _this._scene.getEngine();
  52640. var viewport = _this._camera.viewport;
  52641. var globalViewport = viewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  52642. // Meshes
  52643. var meshes = _this._camera.getActiveMeshes();
  52644. var index;
  52645. var projectedPosition;
  52646. for (index = 0; index < meshes.length; index++) {
  52647. var mesh = meshes.data[index];
  52648. var position = mesh.getBoundingInfo().boundingSphere.center;
  52649. projectedPosition = BABYLON.Vector3.Project(position, mesh.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  52650. if (mesh.renderOverlay || _this.shouldDisplayAxis && _this.shouldDisplayAxis(mesh)) {
  52651. _this._renderAxis(projectedPosition, mesh, globalViewport);
  52652. }
  52653. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(mesh)) {
  52654. _this._renderLabel(mesh.name, projectedPosition, 12, function () { mesh.renderOverlay = !mesh.renderOverlay; }, function () { return mesh.renderOverlay ? 'red' : 'black'; });
  52655. }
  52656. }
  52657. // Cameras
  52658. var cameras = _this._scene.cameras;
  52659. for (index = 0; index < cameras.length; index++) {
  52660. var camera = cameras[index];
  52661. if (camera === _this._camera) {
  52662. continue;
  52663. }
  52664. projectedPosition = BABYLON.Vector3.Project(BABYLON.Vector3.Zero(), camera.getWorldMatrix(), _this._transformationMatrix, globalViewport);
  52665. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(camera)) {
  52666. _this._renderLabel(camera.name, projectedPosition, 12, function () {
  52667. _this._camera.detachControl(engine.getRenderingCanvas());
  52668. _this._camera = camera;
  52669. _this._camera.attachControl(engine.getRenderingCanvas());
  52670. }, function () { return "purple"; });
  52671. }
  52672. }
  52673. // Lights
  52674. var lights = _this._scene.lights;
  52675. for (index = 0; index < lights.length; index++) {
  52676. var light = lights[index];
  52677. if (light.position) {
  52678. projectedPosition = BABYLON.Vector3.Project(light.getAbsolutePosition(), _this._identityMatrix, _this._transformationMatrix, globalViewport);
  52679. if (!_this.shouldDisplayLabel || _this.shouldDisplayLabel(light)) {
  52680. _this._renderLabel(light.name, projectedPosition, -20, function () {
  52681. light.setEnabled(!light.isEnabled());
  52682. }, function () { return light.isEnabled() ? "orange" : "gray"; });
  52683. }
  52684. }
  52685. }
  52686. }
  52687. _this._clickPosition = undefined;
  52688. };
  52689. }
  52690. DebugLayer.prototype._refreshMeshesTreeContent = function () {
  52691. while (this._treeSubsetDiv.hasChildNodes()) {
  52692. this._treeSubsetDiv.removeChild(this._treeSubsetDiv.lastChild);
  52693. }
  52694. // Add meshes
  52695. var sortedArray = this._scene.meshes.slice(0, this._scene.meshes.length);
  52696. sortedArray.sort(function (a, b) {
  52697. if (a.name === b.name) {
  52698. return 0;
  52699. }
  52700. return (a.name > b.name) ? 1 : -1;
  52701. });
  52702. for (var index = 0; index < sortedArray.length; index++) {
  52703. var mesh = sortedArray[index];
  52704. if (!mesh.isEnabled()) {
  52705. continue;
  52706. }
  52707. this._generateAdvancedCheckBox(this._treeSubsetDiv, mesh.name, mesh.getTotalVertices() + " verts", mesh.isVisible, function (element, m) {
  52708. m.isVisible = element.checked;
  52709. }, mesh);
  52710. }
  52711. };
  52712. DebugLayer.prototype._renderSingleAxis = function (zero, unit, unitText, label, color) {
  52713. this._drawingContext.beginPath();
  52714. this._drawingContext.moveTo(zero.x, zero.y);
  52715. this._drawingContext.lineTo(unit.x, unit.y);
  52716. this._drawingContext.strokeStyle = color;
  52717. this._drawingContext.lineWidth = 4;
  52718. this._drawingContext.stroke();
  52719. this._drawingContext.font = "normal 14px Segoe UI";
  52720. this._drawingContext.fillStyle = color;
  52721. this._drawingContext.fillText(label, unitText.x, unitText.y);
  52722. };
  52723. DebugLayer.prototype._renderAxis = function (projectedPosition, mesh, globalViewport) {
  52724. var position = mesh.getBoundingInfo().boundingSphere.center;
  52725. var worldMatrix = mesh.getWorldMatrix();
  52726. var unprojectedVector = BABYLON.Vector3.UnprojectFromTransform(projectedPosition.add(new BABYLON.Vector3(this._drawingCanvas.width * this.axisRatio, 0, 0)), globalViewport.width, globalViewport.height, worldMatrix, this._transformationMatrix);
  52727. var unit = (unprojectedVector.subtract(position)).length();
  52728. var xAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52729. var xAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(unit * 1.5, 0, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52730. this._renderSingleAxis(projectedPosition, xAxis, xAxisText, "x", "#FF0000");
  52731. var yAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52732. var yAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, unit * 1.5, 0)), worldMatrix, this._transformationMatrix, globalViewport);
  52733. this._renderSingleAxis(projectedPosition, yAxis, yAxisText, "y", "#00FF00");
  52734. var zAxis = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit)), worldMatrix, this._transformationMatrix, globalViewport);
  52735. var zAxisText = BABYLON.Vector3.Project(position.add(new BABYLON.Vector3(0, 0, unit * 1.5)), worldMatrix, this._transformationMatrix, globalViewport);
  52736. this._renderSingleAxis(projectedPosition, zAxis, zAxisText, "z", "#0000FF");
  52737. };
  52738. DebugLayer.prototype._renderLabel = function (text, projectedPosition, labelOffset, onClick, getFillStyle) {
  52739. if (projectedPosition.z > 0 && projectedPosition.z < 1.0) {
  52740. this._drawingContext.font = "normal 12px Segoe UI";
  52741. var textMetrics = this._drawingContext.measureText(text);
  52742. var centerX = projectedPosition.x - textMetrics.width / 2;
  52743. var centerY = projectedPosition.y;
  52744. var clientRect = this._drawingCanvas.getBoundingClientRect();
  52745. if (this._showUI && this._isClickInsideRect(clientRect.left * this._ratio + centerX - 5, clientRect.top * this._ratio + centerY - labelOffset - 12, textMetrics.width + 10, 17)) {
  52746. onClick();
  52747. }
  52748. this._drawingContext.beginPath();
  52749. this._drawingContext.rect(centerX - 5, centerY - labelOffset - 12, textMetrics.width + 10, 17);
  52750. this._drawingContext.fillStyle = getFillStyle();
  52751. this._drawingContext.globalAlpha = 0.5;
  52752. this._drawingContext.fill();
  52753. this._drawingContext.globalAlpha = 1.0;
  52754. this._drawingContext.strokeStyle = '#FFFFFF';
  52755. this._drawingContext.lineWidth = 1;
  52756. this._drawingContext.stroke();
  52757. this._drawingContext.fillStyle = "#FFFFFF";
  52758. this._drawingContext.fillText(text, centerX, centerY - labelOffset);
  52759. this._drawingContext.beginPath();
  52760. this._drawingContext.arc(projectedPosition.x, centerY, 5, 0, 2 * Math.PI, false);
  52761. this._drawingContext.fill();
  52762. }
  52763. };
  52764. DebugLayer.prototype._isClickInsideRect = function (x, y, width, height) {
  52765. if (!this._clickPosition) {
  52766. return false;
  52767. }
  52768. if (this._clickPosition.x < x || this._clickPosition.x > x + width) {
  52769. return false;
  52770. }
  52771. if (this._clickPosition.y < y || this._clickPosition.y > y + height) {
  52772. return false;
  52773. }
  52774. return true;
  52775. };
  52776. DebugLayer.prototype.isVisible = function () {
  52777. return this._enabled;
  52778. };
  52779. DebugLayer.prototype.hide = function () {
  52780. if (!this._enabled) {
  52781. return;
  52782. }
  52783. this._enabled = false;
  52784. var engine = this._scene.getEngine();
  52785. this._scene.unregisterBeforeRender(this._syncData);
  52786. this._scene.unregisterAfterRender(this._syncUI);
  52787. this._rootElement.removeChild(this._globalDiv);
  52788. this._scene.forceShowBoundingBoxes = false;
  52789. this._scene.forceWireframe = false;
  52790. BABYLON.StandardMaterial.DiffuseTextureEnabled = true;
  52791. BABYLON.StandardMaterial.AmbientTextureEnabled = true;
  52792. BABYLON.StandardMaterial.SpecularTextureEnabled = true;
  52793. BABYLON.StandardMaterial.EmissiveTextureEnabled = true;
  52794. BABYLON.StandardMaterial.BumpTextureEnabled = true;
  52795. BABYLON.StandardMaterial.OpacityTextureEnabled = true;
  52796. BABYLON.StandardMaterial.ReflectionTextureEnabled = true;
  52797. BABYLON.StandardMaterial.LightmapTextureEnabled = true;
  52798. BABYLON.StandardMaterial.RefractionTextureEnabled = true;
  52799. BABYLON.StandardMaterial.ColorGradingTextureEnabled = true;
  52800. this._scene.shadowsEnabled = true;
  52801. this._scene.particlesEnabled = true;
  52802. this._scene.postProcessesEnabled = true;
  52803. this._scene.collisionsEnabled = true;
  52804. this._scene.lightsEnabled = true;
  52805. this._scene.texturesEnabled = true;
  52806. this._scene.lensFlaresEnabled = true;
  52807. this._scene.proceduralTexturesEnabled = true;
  52808. this._scene.renderTargetsEnabled = true;
  52809. this._scene.probesEnabled = true;
  52810. engine.getRenderingCanvas().removeEventListener("click", this._onCanvasClick);
  52811. this._clearSkeletonViewers();
  52812. };
  52813. DebugLayer.prototype._clearSkeletonViewers = function () {
  52814. for (var index = 0; index < this._skeletonViewers.length; index++) {
  52815. this._skeletonViewers[index].dispose();
  52816. }
  52817. this._skeletonViewers = [];
  52818. };
  52819. DebugLayer.prototype.show = function (showUI, camera, rootElement) {
  52820. if (showUI === void 0) { showUI = true; }
  52821. if (camera === void 0) { camera = null; }
  52822. if (rootElement === void 0) { rootElement = null; }
  52823. if (this._enabled) {
  52824. return;
  52825. }
  52826. this._enabled = true;
  52827. if (camera) {
  52828. this._camera = camera;
  52829. }
  52830. else {
  52831. this._camera = this._scene.activeCamera;
  52832. }
  52833. this._showUI = showUI;
  52834. var engine = this._scene.getEngine();
  52835. this._globalDiv = document.createElement("div");
  52836. this._rootElement = rootElement || document.body;
  52837. this._rootElement.appendChild(this._globalDiv);
  52838. this._generateDOMelements();
  52839. engine.getRenderingCanvas().addEventListener("click", this._onCanvasClick);
  52840. this._syncPositions();
  52841. this._scene.registerBeforeRender(this._syncData);
  52842. this._scene.registerAfterRender(this._syncUI);
  52843. };
  52844. DebugLayer.prototype._clearLabels = function () {
  52845. this._drawingContext.clearRect(0, 0, this._drawingCanvas.width, this._drawingCanvas.height);
  52846. for (var index = 0; index < this._scene.meshes.length; index++) {
  52847. var mesh = this._scene.meshes[index];
  52848. mesh.renderOverlay = false;
  52849. }
  52850. };
  52851. DebugLayer.prototype._generateheader = function (root, text) {
  52852. var header = document.createElement("div");
  52853. header.innerHTML = text + "&nbsp;";
  52854. header.style.textAlign = "right";
  52855. header.style.width = "100%";
  52856. header.style.color = "white";
  52857. header.style.backgroundColor = "Black";
  52858. header.style.padding = "5px 5px 4px 0px";
  52859. header.style.marginLeft = "-5px";
  52860. header.style.fontWeight = "bold";
  52861. root.appendChild(header);
  52862. };
  52863. DebugLayer.prototype._generateTexBox = function (root, title, color) {
  52864. var label = document.createElement("label");
  52865. label.style.display = "inline";
  52866. label.innerHTML = title;
  52867. label.style.color = color;
  52868. root.appendChild(label);
  52869. root.appendChild(document.createElement("br"));
  52870. };
  52871. DebugLayer.prototype._generateAdvancedCheckBox = function (root, leftTitle, rightTitle, initialState, task, tag) {
  52872. if (tag === void 0) { tag = null; }
  52873. var label = document.createElement("label");
  52874. label.style.display = "inline";
  52875. var boundingBoxesCheckbox = document.createElement("input");
  52876. boundingBoxesCheckbox.type = "checkbox";
  52877. boundingBoxesCheckbox.checked = initialState;
  52878. boundingBoxesCheckbox.style.display = "inline";
  52879. boundingBoxesCheckbox.style.margin = "0px 5px 0px 0px";
  52880. boundingBoxesCheckbox.style.verticalAlign = "sub";
  52881. boundingBoxesCheckbox.addEventListener("change", function (evt) {
  52882. task(evt.target, tag);
  52883. });
  52884. label.appendChild(boundingBoxesCheckbox);
  52885. var container = document.createElement("span");
  52886. var leftPart = document.createElement("span");
  52887. var rightPart = document.createElement("span");
  52888. rightPart.style.cssFloat = "right";
  52889. leftPart.innerHTML = leftTitle;
  52890. rightPart.innerHTML = rightTitle;
  52891. rightPart.style.fontSize = "12px";
  52892. rightPart.style.maxWidth = "200px";
  52893. container.appendChild(leftPart);
  52894. container.appendChild(rightPart);
  52895. label.appendChild(container);
  52896. root.appendChild(label);
  52897. root.appendChild(document.createElement("br"));
  52898. };
  52899. DebugLayer.prototype._generateCheckBox = function (root, title, initialState, task, tag) {
  52900. if (tag === void 0) { tag = null; }
  52901. var label = document.createElement("label");
  52902. label.style.display = "inline";
  52903. var checkBox = document.createElement("input");
  52904. checkBox.type = "checkbox";
  52905. checkBox.checked = initialState;
  52906. checkBox.style.display = "inline";
  52907. checkBox.style.margin = "0px 5px 0px 0px";
  52908. checkBox.style.verticalAlign = "sub";
  52909. checkBox.addEventListener("change", function (evt) {
  52910. task(evt.target, tag);
  52911. });
  52912. label.appendChild(checkBox);
  52913. label.appendChild(document.createTextNode(title));
  52914. root.appendChild(label);
  52915. root.appendChild(document.createElement("br"));
  52916. };
  52917. DebugLayer.prototype._generateButton = function (root, title, task, tag) {
  52918. if (tag === void 0) { tag = null; }
  52919. var button = document.createElement("button");
  52920. button.innerHTML = title;
  52921. button.style.height = "24px";
  52922. button.style.width = "150px";
  52923. button.style.marginBottom = "5px";
  52924. button.style.color = "#444444";
  52925. button.style.border = "1px solid white";
  52926. button.className = "debugLayerButton";
  52927. button.addEventListener("click", function (evt) {
  52928. task(evt.target, tag);
  52929. });
  52930. root.appendChild(button);
  52931. root.appendChild(document.createElement("br"));
  52932. };
  52933. DebugLayer.prototype._generateRadio = function (root, title, name, initialState, task, tag) {
  52934. if (tag === void 0) { tag = null; }
  52935. var label = document.createElement("label");
  52936. label.style.display = "inline";
  52937. var boundingBoxesRadio = document.createElement("input");
  52938. boundingBoxesRadio.type = "radio";
  52939. boundingBoxesRadio.name = name;
  52940. boundingBoxesRadio.checked = initialState;
  52941. boundingBoxesRadio.style.display = "inline";
  52942. boundingBoxesRadio.style.margin = "0px 5px 0px 0px";
  52943. boundingBoxesRadio.style.verticalAlign = "sub";
  52944. boundingBoxesRadio.addEventListener("change", function (evt) {
  52945. task(evt.target, tag);
  52946. });
  52947. label.appendChild(boundingBoxesRadio);
  52948. label.appendChild(document.createTextNode(title));
  52949. root.appendChild(label);
  52950. root.appendChild(document.createElement("br"));
  52951. };
  52952. DebugLayer.prototype._generateDOMelements = function () {
  52953. var _this = this;
  52954. this._globalDiv.id = "DebugLayer";
  52955. this._globalDiv.style.position = "absolute";
  52956. this._globalDiv.style.fontFamily = "Segoe UI, Arial";
  52957. this._globalDiv.style.fontSize = "14px";
  52958. this._globalDiv.style.color = "white";
  52959. // Drawing canvas
  52960. this._drawingCanvas = document.createElement("canvas");
  52961. this._drawingCanvas.id = "DebugLayerDrawingCanvas";
  52962. this._drawingCanvas.style.position = "absolute";
  52963. this._drawingCanvas.style.pointerEvents = "none";
  52964. this._drawingCanvas.style.backgroundColor = "transparent";
  52965. this._drawingContext = this._drawingCanvas.getContext("2d");
  52966. this._globalDiv.appendChild(this._drawingCanvas);
  52967. if (this._showUI) {
  52968. var background = "rgba(128, 128, 128, 0.4)";
  52969. var border = "rgb(180, 180, 180) solid 1px";
  52970. // Stats
  52971. this._statsDiv = document.createElement("div");
  52972. this._statsDiv.id = "DebugLayerStats";
  52973. this._statsDiv.style.border = border;
  52974. this._statsDiv.style.position = "absolute";
  52975. this._statsDiv.style.background = background;
  52976. this._statsDiv.style.padding = "0px 0px 0px 5px";
  52977. this._generateheader(this._statsDiv, "STATISTICS");
  52978. this._statsSubsetDiv = document.createElement("div");
  52979. this._statsSubsetDiv.style.paddingTop = "5px";
  52980. this._statsSubsetDiv.style.paddingBottom = "5px";
  52981. this._statsSubsetDiv.style.overflowY = "auto";
  52982. this._statsDiv.appendChild(this._statsSubsetDiv);
  52983. // Tree
  52984. this._treeDiv = document.createElement("div");
  52985. this._treeDiv.id = "DebugLayerTree";
  52986. this._treeDiv.style.border = border;
  52987. this._treeDiv.style.position = "absolute";
  52988. this._treeDiv.style.background = background;
  52989. this._treeDiv.style.padding = "0px 0px 0px 5px";
  52990. this._treeDiv.style.display = "none";
  52991. this._generateheader(this._treeDiv, "MESHES TREE");
  52992. this._treeSubsetDiv = document.createElement("div");
  52993. this._treeSubsetDiv.style.paddingTop = "5px";
  52994. this._treeSubsetDiv.style.paddingRight = "5px";
  52995. this._treeSubsetDiv.style.overflowY = "auto";
  52996. this._treeSubsetDiv.style.maxHeight = "300px";
  52997. this._treeDiv.appendChild(this._treeSubsetDiv);
  52998. this._needToRefreshMeshesTree = true;
  52999. // Logs
  53000. this._logDiv = document.createElement("div");
  53001. this._logDiv.style.border = border;
  53002. this._logDiv.id = "DebugLayerLogs";
  53003. this._logDiv.style.position = "absolute";
  53004. this._logDiv.style.background = background;
  53005. this._logDiv.style.padding = "0px 0px 0px 5px";
  53006. this._logDiv.style.display = "none";
  53007. this._generateheader(this._logDiv, "LOGS");
  53008. this._logSubsetDiv = document.createElement("div");
  53009. this._logSubsetDiv.style.height = "127px";
  53010. this._logSubsetDiv.style.paddingTop = "5px";
  53011. this._logSubsetDiv.style.overflowY = "auto";
  53012. this._logSubsetDiv.style.fontSize = "12px";
  53013. this._logSubsetDiv.style.fontFamily = "consolas";
  53014. this._logSubsetDiv.innerHTML = BABYLON.Tools.LogCache;
  53015. this._logDiv.appendChild(this._logSubsetDiv);
  53016. BABYLON.Tools.OnNewCacheEntry = function (entry) {
  53017. _this._logSubsetDiv.innerHTML = entry + _this._logSubsetDiv.innerHTML;
  53018. };
  53019. // Options
  53020. this._optionsDiv = document.createElement("div");
  53021. this._optionsDiv.id = "DebugLayerOptions";
  53022. this._optionsDiv.style.border = border;
  53023. this._optionsDiv.style.position = "absolute";
  53024. this._optionsDiv.style.background = background;
  53025. this._optionsDiv.style.padding = "0px 0px 0px 5px";
  53026. this._optionsDiv.style.overflowY = "auto";
  53027. this._generateheader(this._optionsDiv, "OPTIONS");
  53028. this._optionsSubsetDiv = document.createElement("div");
  53029. this._optionsSubsetDiv.style.paddingTop = "5px";
  53030. this._optionsSubsetDiv.style.paddingBottom = "5px";
  53031. this._optionsSubsetDiv.style.overflowY = "auto";
  53032. this._optionsSubsetDiv.style.maxHeight = "200px";
  53033. this._optionsDiv.appendChild(this._optionsSubsetDiv);
  53034. this._generateTexBox(this._optionsSubsetDiv, "<b>Windows:</b>", this.accentColor);
  53035. this._generateCheckBox(this._optionsSubsetDiv, "Statistics", this._displayStatistics, function (element) { _this._displayStatistics = element.checked; });
  53036. this._generateCheckBox(this._optionsSubsetDiv, "Logs", this._displayLogs, function (element) { _this._displayLogs = element.checked; });
  53037. this._generateCheckBox(this._optionsSubsetDiv, "Meshes tree", this._displayTree, function (element) {
  53038. _this._displayTree = element.checked;
  53039. _this._needToRefreshMeshesTree = true;
  53040. });
  53041. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53042. this._generateTexBox(this._optionsSubsetDiv, "<b>General:</b>", this.accentColor);
  53043. this._generateCheckBox(this._optionsSubsetDiv, "Bounding boxes", this._scene.forceShowBoundingBoxes, function (element) { _this._scene.forceShowBoundingBoxes = element.checked; });
  53044. this._generateCheckBox(this._optionsSubsetDiv, "Clickable labels", this._labelsEnabled, function (element) {
  53045. _this._labelsEnabled = element.checked;
  53046. if (!_this._labelsEnabled) {
  53047. _this._clearLabels();
  53048. }
  53049. });
  53050. this._generateCheckBox(this._optionsSubsetDiv, "Generate user marks (F12)", BABYLON.Tools.PerformanceLogLevel === BABYLON.Tools.PerformanceUserMarkLogLevel, function (element) {
  53051. if (element.checked) {
  53052. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceUserMarkLogLevel;
  53053. }
  53054. else {
  53055. BABYLON.Tools.PerformanceLogLevel = BABYLON.Tools.PerformanceNoneLogLevel;
  53056. }
  53057. });
  53058. ;
  53059. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53060. this._generateTexBox(this._optionsSubsetDiv, "<b>Rendering mode:</b>", this.accentColor);
  53061. this._generateRadio(this._optionsSubsetDiv, "Solid", "renderMode", !this._scene.forceWireframe && !this._scene.forcePointsCloud, function (element) {
  53062. if (element.checked) {
  53063. _this._scene.forceWireframe = false;
  53064. _this._scene.forcePointsCloud = false;
  53065. }
  53066. });
  53067. this._generateRadio(this._optionsSubsetDiv, "Wireframe", "renderMode", this._scene.forceWireframe, function (element) {
  53068. if (element.checked) {
  53069. _this._scene.forceWireframe = true;
  53070. _this._scene.forcePointsCloud = false;
  53071. }
  53072. });
  53073. this._generateRadio(this._optionsSubsetDiv, "Point", "renderMode", this._scene.forcePointsCloud, function (element) {
  53074. if (element.checked) {
  53075. _this._scene.forceWireframe = false;
  53076. _this._scene.forcePointsCloud = true;
  53077. }
  53078. });
  53079. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53080. this._generateTexBox(this._optionsSubsetDiv, "<b>Texture channels:</b>", this.accentColor);
  53081. this._generateCheckBox(this._optionsSubsetDiv, "Diffuse", BABYLON.StandardMaterial.DiffuseTextureEnabled, function (element) { BABYLON.StandardMaterial.DiffuseTextureEnabled = element.checked; });
  53082. this._generateCheckBox(this._optionsSubsetDiv, "Ambient", BABYLON.StandardMaterial.AmbientTextureEnabled, function (element) { BABYLON.StandardMaterial.AmbientTextureEnabled = element.checked; });
  53083. this._generateCheckBox(this._optionsSubsetDiv, "Specular", BABYLON.StandardMaterial.SpecularTextureEnabled, function (element) { BABYLON.StandardMaterial.SpecularTextureEnabled = element.checked; });
  53084. this._generateCheckBox(this._optionsSubsetDiv, "Emissive", BABYLON.StandardMaterial.EmissiveTextureEnabled, function (element) { BABYLON.StandardMaterial.EmissiveTextureEnabled = element.checked; });
  53085. this._generateCheckBox(this._optionsSubsetDiv, "Bump", BABYLON.StandardMaterial.BumpTextureEnabled, function (element) { BABYLON.StandardMaterial.BumpTextureEnabled = element.checked; });
  53086. this._generateCheckBox(this._optionsSubsetDiv, "Opacity", BABYLON.StandardMaterial.OpacityTextureEnabled, function (element) { BABYLON.StandardMaterial.OpacityTextureEnabled = element.checked; });
  53087. this._generateCheckBox(this._optionsSubsetDiv, "Reflection", BABYLON.StandardMaterial.ReflectionTextureEnabled, function (element) { BABYLON.StandardMaterial.ReflectionTextureEnabled = element.checked; });
  53088. this._generateCheckBox(this._optionsSubsetDiv, "Refraction", BABYLON.StandardMaterial.RefractionTextureEnabled, function (element) { BABYLON.StandardMaterial.RefractionTextureEnabled = element.checked; });
  53089. this._generateCheckBox(this._optionsSubsetDiv, "ColorGrading", BABYLON.StandardMaterial.ColorGradingTextureEnabled, function (element) { BABYLON.StandardMaterial.ColorGradingTextureEnabled = element.checked; });
  53090. this._generateCheckBox(this._optionsSubsetDiv, "Lightmap", BABYLON.StandardMaterial.LightmapTextureEnabled, function (element) { BABYLON.StandardMaterial.LightmapTextureEnabled = element.checked; });
  53091. this._generateCheckBox(this._optionsSubsetDiv, "Fresnel", BABYLON.StandardMaterial.FresnelEnabled, function (element) { BABYLON.StandardMaterial.FresnelEnabled = element.checked; });
  53092. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53093. this._generateTexBox(this._optionsSubsetDiv, "<b>Options:</b>", this.accentColor);
  53094. this._generateCheckBox(this._optionsSubsetDiv, "Animations", this._scene.animationsEnabled, function (element) { _this._scene.animationsEnabled = element.checked; });
  53095. this._generateCheckBox(this._optionsSubsetDiv, "Collisions", this._scene.collisionsEnabled, function (element) { _this._scene.collisionsEnabled = element.checked; });
  53096. this._generateCheckBox(this._optionsSubsetDiv, "Fog", this._scene.fogEnabled, function (element) { _this._scene.fogEnabled = element.checked; });
  53097. this._generateCheckBox(this._optionsSubsetDiv, "Lens flares", this._scene.lensFlaresEnabled, function (element) { _this._scene.lensFlaresEnabled = element.checked; });
  53098. this._generateCheckBox(this._optionsSubsetDiv, "Lights", this._scene.lightsEnabled, function (element) { _this._scene.lightsEnabled = element.checked; });
  53099. this._generateCheckBox(this._optionsSubsetDiv, "Particles", this._scene.particlesEnabled, function (element) { _this._scene.particlesEnabled = element.checked; });
  53100. this._generateCheckBox(this._optionsSubsetDiv, "Post-processes", this._scene.postProcessesEnabled, function (element) { _this._scene.postProcessesEnabled = element.checked; });
  53101. this._generateCheckBox(this._optionsSubsetDiv, "Probes", this._scene.probesEnabled, function (element) { _this._scene.probesEnabled = element.checked; });
  53102. this._generateCheckBox(this._optionsSubsetDiv, "Procedural textures", this._scene.proceduralTexturesEnabled, function (element) { _this._scene.proceduralTexturesEnabled = element.checked; });
  53103. this._generateCheckBox(this._optionsSubsetDiv, "Render targets", this._scene.renderTargetsEnabled, function (element) { _this._scene.renderTargetsEnabled = element.checked; });
  53104. this._generateCheckBox(this._optionsSubsetDiv, "Shadows", this._scene.shadowsEnabled, function (element) { _this._scene.shadowsEnabled = element.checked; });
  53105. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", this._scene.skeletonsEnabled, function (element) { _this._scene.skeletonsEnabled = element.checked; });
  53106. this._generateCheckBox(this._optionsSubsetDiv, "Sprites", this._scene.spritesEnabled, function (element) { _this._scene.spritesEnabled = element.checked; });
  53107. this._generateCheckBox(this._optionsSubsetDiv, "Textures", this._scene.texturesEnabled, function (element) { _this._scene.texturesEnabled = element.checked; });
  53108. if (BABYLON.AudioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  53109. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53110. this._generateTexBox(this._optionsSubsetDiv, "<b>Audio:</b>", this.accentColor);
  53111. this._generateRadio(this._optionsSubsetDiv, "Headphones", "panningModel", this._scene.headphone, function (element) {
  53112. if (element.checked) {
  53113. _this._scene.headphone = true;
  53114. }
  53115. });
  53116. this._generateRadio(this._optionsSubsetDiv, "Normal Speakers", "panningModel", !this._scene.headphone, function (element) {
  53117. if (element.checked) {
  53118. _this._scene.headphone = false;
  53119. }
  53120. });
  53121. this._generateCheckBox(this._optionsSubsetDiv, "Disable audio", !this._scene.audioEnabled, function (element) {
  53122. _this._scene.audioEnabled = !element.checked;
  53123. });
  53124. }
  53125. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53126. this._generateTexBox(this._optionsSubsetDiv, "<b>Viewers:</b>", this.accentColor);
  53127. this._generateCheckBox(this._optionsSubsetDiv, "Skeletons", false, function (element) {
  53128. if (!element.checked) {
  53129. _this._clearSkeletonViewers();
  53130. return;
  53131. }
  53132. for (var index = 0; index < _this._scene.meshes.length; index++) {
  53133. var mesh = _this._scene.meshes[index];
  53134. if (mesh.skeleton) {
  53135. var found = false;
  53136. for (var sIndex = 0; sIndex < _this._skeletonViewers.length; sIndex++) {
  53137. if (_this._skeletonViewers[sIndex].skeleton === mesh.skeleton) {
  53138. found = true;
  53139. break;
  53140. }
  53141. }
  53142. if (found) {
  53143. continue;
  53144. }
  53145. var viewer = new BABYLON.Debug.SkeletonViewer(mesh.skeleton, mesh, _this._scene);
  53146. viewer.isEnabled = true;
  53147. _this._skeletonViewers.push(viewer);
  53148. }
  53149. }
  53150. });
  53151. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53152. this._generateTexBox(this._optionsSubsetDiv, "<b>Tools:</b>", this.accentColor);
  53153. this._generateButton(this._optionsSubsetDiv, "Dump rendertargets", function (element) { _this._scene.dumpNextRenderTargets = true; });
  53154. this._generateButton(this._optionsSubsetDiv, "Run SceneOptimizer", function (element) { BABYLON.SceneOptimizer.OptimizeAsync(_this._scene); });
  53155. this._generateButton(this._optionsSubsetDiv, "Log camera object", function (element) {
  53156. if (_this._camera) {
  53157. console.log(_this._camera);
  53158. }
  53159. else {
  53160. console.warn("No camera defined, or debug layer created before camera creation!");
  53161. }
  53162. });
  53163. this._optionsSubsetDiv.appendChild(document.createElement("br"));
  53164. this._globalDiv.appendChild(this._statsDiv);
  53165. this._globalDiv.appendChild(this._logDiv);
  53166. this._globalDiv.appendChild(this._optionsDiv);
  53167. this._globalDiv.appendChild(this._treeDiv);
  53168. }
  53169. };
  53170. DebugLayer.prototype._displayStats = function () {
  53171. var scene = this._scene;
  53172. var engine = scene.getEngine();
  53173. var glInfo = engine.getGlInfo();
  53174. this._statsSubsetDiv.innerHTML = "Babylon.js v" + BABYLON.Engine.Version + " - <b>" + BABYLON.Tools.Format(engine.getFps(), 0) + " fps</b><br><br>"
  53175. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  53176. + "<b>Count</b><br>"
  53177. + "Total meshes: " + scene.meshes.length + "<br>"
  53178. + "Total lights: " + scene.lights.length + "<br>"
  53179. + "Total vertices: " + scene.getTotalVertices() + "<br>"
  53180. + "Total materials: " + scene.materials.length + "<br>"
  53181. + "Total textures: " + scene.textures.length + "<br>"
  53182. + "Active meshes: " + scene.getActiveMeshes().length + "<br>"
  53183. + "Active indices: " + scene.getActiveIndices() + "<br>"
  53184. + "Active bones: " + scene.getActiveBones() + "<br>"
  53185. + "Active particles: " + scene.getActiveParticles() + "<br>"
  53186. + "<b>Draw calls: " + engine.drawCalls + "</b><br><br>"
  53187. + "<b>Duration</b><br>"
  53188. + "Meshes selection:</i> " + BABYLON.Tools.Format(scene.getEvaluateActiveMeshesDuration()) + " ms<br>"
  53189. + "Render Targets: " + BABYLON.Tools.Format(scene.getRenderTargetsDuration()) + " ms<br>"
  53190. + "Particles: " + BABYLON.Tools.Format(scene.getParticlesDuration()) + " ms<br>"
  53191. + "Sprites: " + BABYLON.Tools.Format(scene.getSpritesDuration()) + " ms<br><br>"
  53192. + "Render: <b>" + BABYLON.Tools.Format(scene.getRenderDuration()) + " ms</b><br>"
  53193. + "Frame: " + BABYLON.Tools.Format(scene.getLastFrameDuration()) + " ms<br>"
  53194. + "Potential FPS: " + BABYLON.Tools.Format(1000.0 / scene.getLastFrameDuration(), 0) + "<br>"
  53195. + "Resolution: " + engine.getRenderWidth() + "x" + engine.getRenderHeight() + "<br><br>"
  53196. + "</div>"
  53197. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  53198. + "<b>Extensions</b><br>"
  53199. + "Std derivatives: " + (engine.getCaps().standardDerivatives ? "Yes" : "No") + "<br>"
  53200. + "Compressed textures: " + (engine.getCaps().s3tc ? "Yes" : "No") + "<br>"
  53201. + "Hardware instances: " + (engine.getCaps().instancedArrays ? "Yes" : "No") + "<br>"
  53202. + "Texture float: " + (engine.getCaps().textureFloat ? "Yes" : "No") + "<br><br>"
  53203. + "32bits indices: " + (engine.getCaps().uintIndices ? "Yes" : "No") + "<br>"
  53204. + "Fragment depth: " + (engine.getCaps().fragmentDepthSupported ? "Yes" : "No") + "<br>"
  53205. + "High precision shaders: " + (engine.getCaps().highPrecisionShaderSupported ? "Yes" : "No") + "<br>"
  53206. + "Draw buffers: " + (engine.getCaps().drawBuffersExtension ? "Yes" : "No") + "<br>"
  53207. + "</div><br>"
  53208. + "<div style='column-count: 2;-moz-column-count:2;-webkit-column-count:2'>"
  53209. + "<b>Caps.</b><br>"
  53210. + "Stencil: " + (engine.isStencilEnable ? "Enabled" : "Disabled") + "<br>"
  53211. + "Max textures units: " + engine.getCaps().maxTexturesImageUnits + "<br>"
  53212. + "Max textures size: " + engine.getCaps().maxTextureSize + "<br>"
  53213. + "Max anisotropy: " + engine.getCaps().maxAnisotropy + "<br>"
  53214. + "<b>Info</b><br>"
  53215. + "WebGL feature level: " + engine.webGLVersion + "<br>"
  53216. + glInfo.version + "<br>"
  53217. + "</div><br>"
  53218. + glInfo.renderer + "<br>";
  53219. if (this.customStatsFunction) {
  53220. this._statsSubsetDiv.innerHTML += this.customStatsFunction();
  53221. }
  53222. };
  53223. return DebugLayer;
  53224. }());
  53225. BABYLON.DebugLayer = DebugLayer;
  53226. })(BABYLON || (BABYLON = {}));
  53227. var BABYLON;
  53228. (function (BABYLON) {
  53229. var StandardRenderingPipeline = (function (_super) {
  53230. __extends(StandardRenderingPipeline, _super);
  53231. /**
  53232. * @constructor
  53233. * @param {string} name - The rendering pipeline name
  53234. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53235. * @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)
  53236. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  53237. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53238. */
  53239. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  53240. var _this = this;
  53241. if (originalPostProcess === void 0) { originalPostProcess = null; }
  53242. _super.call(this, scene.getEngine(), name);
  53243. this.downSampleX4PostProcess = null;
  53244. this.brightPassPostProcess = null;
  53245. this.gaussianBlurHPostProcesses = [];
  53246. this.gaussianBlurVPostProcesses = [];
  53247. this.textureAdderPostProcess = null;
  53248. this.textureAdderFinalPostProcess = null;
  53249. this.lensFlarePostProcess = null;
  53250. this.lensFlareShiftPostProcess = null;
  53251. this.lensFlareComposePostProcess = null;
  53252. this.depthOfFieldPostProcess = null;
  53253. this.motionBlurPostProcess = null;
  53254. // Values
  53255. this.brightThreshold = 1.0;
  53256. this.gaussianCoefficient = 0.25;
  53257. this.gaussianMean = 1.0;
  53258. this.gaussianStandardDeviation = 1.0;
  53259. this.exposure = 1.0;
  53260. this.lensTexture = null;
  53261. this.lensColorTexture = null;
  53262. this.lensFlareStrength = 1.0;
  53263. this.lensFlareGhostDispersal = 1.0;
  53264. this.lensFlareHaloWidth = 0.4;
  53265. this.lensFlareDistortionStrength = 4.0;
  53266. this.lensStarTexture = null;
  53267. this.lensFlareDirtTexture = null;
  53268. this.depthOfFieldDistance = 10.0;
  53269. this._depthRenderer = null;
  53270. // Getters and setters
  53271. this._depthOfFieldEnabled = true;
  53272. this._lensFlareEnabled = true;
  53273. // Initialize
  53274. this._scene = scene;
  53275. // Create pass post-processe
  53276. if (!originalPostProcess) {
  53277. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  53278. }
  53279. else {
  53280. this.originalPostProcess = originalPostProcess;
  53281. }
  53282. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  53283. // Create down sample X4 post-process
  53284. this._createDownSampleX4PostProcess(scene, ratio / 2);
  53285. // Create bright pass post-process
  53286. this._createBrightPassPostProcess(scene, ratio / 2);
  53287. // Create gaussian blur post-processes (down sampling blurs)
  53288. this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  53289. this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  53290. this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  53291. this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  53292. // Create texture adder post-process
  53293. this._createTextureAdderPostProcess(scene, ratio);
  53294. // Create depth-of-field source post-process
  53295. this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRTextureAdderPostProcess", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53296. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  53297. // Create lens flare post-process
  53298. this._createLensFlarePostProcess(scene, ratio);
  53299. // Create gaussian blur used by depth-of-field
  53300. this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  53301. // Create depth-of-field post-process
  53302. this._createDepthOfFieldPostProcess(scene, ratio);
  53303. // Finish
  53304. scene.postProcessRenderPipelineManager.addPipeline(this);
  53305. if (cameras !== null) {
  53306. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  53307. }
  53308. // Deactivate
  53309. this.LensFlareEnabled = false;
  53310. this.DepthOfFieldEnabled = false;
  53311. }
  53312. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  53313. get: function () {
  53314. return this._depthOfFieldEnabled;
  53315. },
  53316. set: function (enabled) {
  53317. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  53318. if (enabled && !this._depthOfFieldEnabled) {
  53319. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53320. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53321. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  53322. this._depthRenderer = this._scene.enableDepthRenderer();
  53323. }
  53324. else if (!enabled && this._depthOfFieldEnabled) {
  53325. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53326. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53327. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  53328. }
  53329. this._depthOfFieldEnabled = enabled;
  53330. },
  53331. enumerable: true,
  53332. configurable: true
  53333. });
  53334. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  53335. get: function () {
  53336. return this._lensFlareEnabled;
  53337. },
  53338. set: function (enabled) {
  53339. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  53340. if (enabled && !this._lensFlareEnabled) {
  53341. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  53342. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  53343. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53344. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53345. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  53346. this._depthRenderer = this._scene.enableDepthRenderer();
  53347. }
  53348. else if (!enabled && this._lensFlareEnabled) {
  53349. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  53350. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  53351. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  53352. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  53353. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  53354. }
  53355. this._lensFlareEnabled = enabled;
  53356. },
  53357. enumerable: true,
  53358. configurable: true
  53359. });
  53360. // Down Sample X4 Post-Processs
  53361. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53362. var _this = this;
  53363. var downSampleX4Offsets = new Array(32);
  53364. 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);
  53365. this.downSampleX4PostProcess.onApply = function (effect) {
  53366. var id = 0;
  53367. for (var i = -2; i < 2; i++) {
  53368. for (var j = -2; j < 2; j++) {
  53369. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  53370. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  53371. id += 2;
  53372. }
  53373. }
  53374. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53375. };
  53376. // Add to pipeline
  53377. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  53378. };
  53379. // Brightpass Post-Process
  53380. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53381. var _this = this;
  53382. var brightOffsets = new Array(8);
  53383. 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);
  53384. this.brightPassPostProcess.onApply = function (effect) {
  53385. var sU = (1.0 / _this.brightPassPostProcess.width);
  53386. var sV = (1.0 / _this.brightPassPostProcess.height);
  53387. brightOffsets[0] = -0.5 * sU;
  53388. brightOffsets[1] = 0.5 * sV;
  53389. brightOffsets[2] = 0.5 * sU;
  53390. brightOffsets[3] = 0.5 * sV;
  53391. brightOffsets[4] = -0.5 * sU;
  53392. brightOffsets[5] = -0.5 * sV;
  53393. brightOffsets[6] = 0.5 * sU;
  53394. brightOffsets[7] = -0.5 * sV;
  53395. effect.setArray2("dsOffsets", brightOffsets);
  53396. effect.setFloat("brightThreshold", _this.brightThreshold);
  53397. };
  53398. // Add to pipeline
  53399. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  53400. };
  53401. // Create gaussian blur H&V post-processes
  53402. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  53403. var _this = this;
  53404. var blurOffsets = new Array(9);
  53405. var blurWeights = new Array(9);
  53406. var uniforms = ["blurOffsets", "blurWeights"];
  53407. var callback = function (height) {
  53408. return function (effect) {
  53409. // Weights
  53410. var x = 0.0;
  53411. for (var i = 0; i < 9; i++) {
  53412. x = (i - 4.0) / 4.0;
  53413. blurWeights[i] =
  53414. _this.gaussianCoefficient
  53415. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  53416. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  53417. }
  53418. var lastOutputDimensions = {
  53419. width: scene.getEngine().getRenderWidth(),
  53420. height: scene.getEngine().getRenderHeight()
  53421. };
  53422. for (var i = 0; i < 9; i++) {
  53423. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  53424. blurOffsets[i] = value;
  53425. }
  53426. effect.setArray("blurOffsets", blurOffsets);
  53427. effect.setArray("blurWeights", blurWeights);
  53428. };
  53429. };
  53430. // Create horizontal gaussian blur post-processes
  53431. 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);
  53432. gaussianBlurHPostProcess.onApply = callback(false);
  53433. // Create vertical gaussian blur post-process
  53434. 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);
  53435. gaussianBlurVPostProcess.onApply = callback(true);
  53436. // Add to pipeline
  53437. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  53438. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  53439. // Finish
  53440. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  53441. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  53442. };
  53443. // Create texture adder post-process
  53444. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53445. var _this = this;
  53446. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  53447. 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);
  53448. this.textureAdderPostProcess.onApply = function (effect) {
  53449. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  53450. effect.setTexture("lensSampler", _this.lensTexture);
  53451. effect.setFloat("exposure", _this.exposure);
  53452. };
  53453. // Add to pipeline
  53454. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  53455. };
  53456. // Create lens flare post-process
  53457. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  53458. var _this = this;
  53459. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth"], ["lensColorSampler"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53460. this.lensFlareShiftPostProcess = new BABYLON.PostProcess("HDRLensFlareShift", "standard", ["resolution", "distortionStrength"], [], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_SHIFT", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53461. this._createGaussianBlurPostProcesses(scene, ratio / 8, 4);
  53462. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["viewMatrix", "scaleBias1", "scaleBias2"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53463. var resolution = new BABYLON.Vector2(0, 0);
  53464. // Lens flare
  53465. this.lensFlarePostProcess.onApply = function (effect) {
  53466. effect.setTextureFromPostProcess("textureSampler", _this.textureAdderPostProcess);
  53467. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  53468. effect.setFloat("strength", _this.lensFlareStrength);
  53469. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  53470. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  53471. };
  53472. // Shift
  53473. this.lensFlareShiftPostProcess.onApply = function (effect) {
  53474. resolution.x = _this.lensFlareShiftPostProcess.width;
  53475. resolution.y = _this.lensFlareShiftPostProcess.height;
  53476. effect.setVector2("resolution", resolution);
  53477. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  53478. };
  53479. // Compose
  53480. var scaleBias1 = BABYLON.Matrix.GetAsMatrix3x3(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, 0.0));
  53481. var scaleBias2 = BABYLON.Matrix.GetAsMatrix3x3(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, 0.0));
  53482. this.lensFlareComposePostProcess.onApply = function (effect) {
  53483. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  53484. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  53485. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  53486. effect.setMatrix("viewMatrix", _this._scene.activeCamera.getViewMatrix());
  53487. effect.setMatrix3x3("scaleBias1", scaleBias1);
  53488. effect.setMatrix3x3("scaleBias2", scaleBias2);
  53489. };
  53490. // Add to pipeline
  53491. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  53492. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareShift", function () { return _this.lensFlareShiftPostProcess; }, false));
  53493. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  53494. };
  53495. // Create depth-of-field post-process
  53496. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  53497. var _this = this;
  53498. 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);
  53499. this.depthOfFieldPostProcess.onApply = function (effect) {
  53500. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  53501. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  53502. effect.setFloat("distance", _this.depthOfFieldDistance);
  53503. };
  53504. // Add to pipeline
  53505. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  53506. };
  53507. return StandardRenderingPipeline;
  53508. }(BABYLON.PostProcessRenderPipeline));
  53509. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  53510. })(BABYLON || (BABYLON = {}));
  53511. 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}"};
  53512. 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"};
  53513. 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._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={}));";
  53514. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  53515. module.exports = BABYLON;
  53516. };