babylon.max.js 2.8 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  211. return Color3;
  212. }());
  213. BABYLON.Color3 = Color3;
  214. var Color4 = (function () {
  215. function Color4(r, g, b, a) {
  216. this.r = r;
  217. this.g = g;
  218. this.b = b;
  219. this.a = a;
  220. }
  221. // Operators
  222. Color4.prototype.addInPlace = function (right) {
  223. this.r += right.r;
  224. this.g += right.g;
  225. this.b += right.b;
  226. this.a += right.a;
  227. return this;
  228. };
  229. Color4.prototype.asArray = function () {
  230. var result = [];
  231. this.toArray(result, 0);
  232. return result;
  233. };
  234. Color4.prototype.toArray = function (array, index) {
  235. if (index === undefined) {
  236. index = 0;
  237. }
  238. array[index] = this.r;
  239. array[index + 1] = this.g;
  240. array[index + 2] = this.b;
  241. array[index + 3] = this.a;
  242. return this;
  243. };
  244. Color4.prototype.add = function (right) {
  245. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  246. };
  247. Color4.prototype.subtract = function (right) {
  248. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  249. };
  250. Color4.prototype.subtractToRef = function (right, result) {
  251. result.r = this.r - right.r;
  252. result.g = this.g - right.g;
  253. result.b = this.b - right.b;
  254. result.a = this.a - right.a;
  255. return this;
  256. };
  257. Color4.prototype.scale = function (scale) {
  258. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  259. };
  260. Color4.prototype.scaleToRef = function (scale, result) {
  261. result.r = this.r * scale;
  262. result.g = this.g * scale;
  263. result.b = this.b * scale;
  264. result.a = this.a * scale;
  265. return this;
  266. };
  267. /**
  268. * Multipy an RGBA Color4 value by another and return a new Color4 object
  269. * @param color The Color4 (RGBA) value to multiply by
  270. * @returns A new Color4.
  271. */
  272. Color4.prototype.multiply = function (color) {
  273. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  274. };
  275. /**
  276. * Multipy an RGBA Color4 value by another and push the result in a reference value
  277. * @param color The Color4 (RGBA) value to multiply by
  278. * @param result The Color4 (RGBA) to fill the result in
  279. * @returns the result Color4.
  280. */
  281. Color4.prototype.multiplyToRef = function (color, result) {
  282. result.r = this.r * color.r;
  283. result.g = this.g * color.g;
  284. result.b = this.b * color.b;
  285. result.a = this.a * color.a;
  286. return result;
  287. };
  288. Color4.prototype.toString = function () {
  289. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  290. };
  291. Color4.prototype.getClassName = function () {
  292. return "Color4";
  293. };
  294. Color4.prototype.getHashCode = function () {
  295. var hash = this.r || 0;
  296. hash = (hash * 397) ^ (this.g || 0);
  297. hash = (hash * 397) ^ (this.b || 0);
  298. hash = (hash * 397) ^ (this.a || 0);
  299. return hash;
  300. };
  301. Color4.prototype.clone = function () {
  302. return new Color4(this.r, this.g, this.b, this.a);
  303. };
  304. Color4.prototype.copyFrom = function (source) {
  305. this.r = source.r;
  306. this.g = source.g;
  307. this.b = source.b;
  308. this.a = source.a;
  309. return this;
  310. };
  311. Color4.prototype.toHexString = function () {
  312. var intR = (this.r * 255) | 0;
  313. var intG = (this.g * 255) | 0;
  314. var intB = (this.b * 255) | 0;
  315. var intA = (this.a * 255) | 0;
  316. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  317. };
  318. // Statics
  319. Color4.FromHexString = function (hex) {
  320. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  321. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  322. return new Color4(0, 0, 0, 0);
  323. }
  324. var r = parseInt(hex.substring(1, 3), 16);
  325. var g = parseInt(hex.substring(3, 5), 16);
  326. var b = parseInt(hex.substring(5, 7), 16);
  327. var a = parseInt(hex.substring(7, 9), 16);
  328. return Color4.FromInts(r, g, b, a);
  329. };
  330. Color4.Lerp = function (left, right, amount) {
  331. var result = new Color4(0, 0, 0, 0);
  332. Color4.LerpToRef(left, right, amount, result);
  333. return result;
  334. };
  335. Color4.LerpToRef = function (left, right, amount, result) {
  336. result.r = left.r + (right.r - left.r) * amount;
  337. result.g = left.g + (right.g - left.g) * amount;
  338. result.b = left.b + (right.b - left.b) * amount;
  339. result.a = left.a + (right.a - left.a) * amount;
  340. };
  341. Color4.FromArray = function (array, offset) {
  342. if (offset === void 0) { offset = 0; }
  343. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  344. };
  345. Color4.FromInts = function (r, g, b, a) {
  346. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  347. };
  348. Color4.CheckColors4 = function (colors, count) {
  349. // Check if color3 was used
  350. if (colors.length === count * 3) {
  351. var colors4 = [];
  352. for (var index = 0; index < colors.length; index += 3) {
  353. var newIndex = (index / 3) * 4;
  354. colors4[newIndex] = colors[index];
  355. colors4[newIndex + 1] = colors[index + 1];
  356. colors4[newIndex + 2] = colors[index + 2];
  357. colors4[newIndex + 3] = 1.0;
  358. }
  359. return colors4;
  360. }
  361. return colors;
  362. };
  363. return Color4;
  364. }());
  365. BABYLON.Color4 = Color4;
  366. var Vector2 = (function () {
  367. function Vector2(x, y) {
  368. this.x = x;
  369. this.y = y;
  370. }
  371. Vector2.prototype.toString = function () {
  372. return "{X: " + this.x + " Y:" + this.y + "}";
  373. };
  374. Vector2.prototype.getClassName = function () {
  375. return "Vector2";
  376. };
  377. Vector2.prototype.getHashCode = function () {
  378. var hash = this.x || 0;
  379. hash = (hash * 397) ^ (this.y || 0);
  380. return hash;
  381. };
  382. // Operators
  383. Vector2.prototype.toArray = function (array, index) {
  384. if (index === void 0) { index = 0; }
  385. array[index] = this.x;
  386. array[index + 1] = this.y;
  387. return this;
  388. };
  389. Vector2.prototype.asArray = function () {
  390. var result = [];
  391. this.toArray(result, 0);
  392. return result;
  393. };
  394. Vector2.prototype.copyFrom = function (source) {
  395. this.x = source.x;
  396. this.y = source.y;
  397. return this;
  398. };
  399. Vector2.prototype.copyFromFloats = function (x, y) {
  400. this.x = x;
  401. this.y = y;
  402. return this;
  403. };
  404. Vector2.prototype.add = function (otherVector) {
  405. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  406. };
  407. Vector2.prototype.addToRef = function (otherVector, result) {
  408. result.x = this.x + otherVector.x;
  409. result.y = this.y + otherVector.y;
  410. return this;
  411. };
  412. Vector2.prototype.addInPlace = function (otherVector) {
  413. this.x += otherVector.x;
  414. this.y += otherVector.y;
  415. return this;
  416. };
  417. Vector2.prototype.addVector3 = function (otherVector) {
  418. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  419. };
  420. Vector2.prototype.subtract = function (otherVector) {
  421. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  422. };
  423. Vector2.prototype.subtractToRef = function (otherVector, result) {
  424. result.x = this.x - otherVector.x;
  425. result.y = this.y - otherVector.y;
  426. return this;
  427. };
  428. Vector2.prototype.subtractInPlace = function (otherVector) {
  429. this.x -= otherVector.x;
  430. this.y -= otherVector.y;
  431. return this;
  432. };
  433. Vector2.prototype.multiplyInPlace = function (otherVector) {
  434. this.x *= otherVector.x;
  435. this.y *= otherVector.y;
  436. return this;
  437. };
  438. Vector2.prototype.multiply = function (otherVector) {
  439. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  440. };
  441. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  442. result.x = this.x * otherVector.x;
  443. result.y = this.y * otherVector.y;
  444. return this;
  445. };
  446. Vector2.prototype.multiplyByFloats = function (x, y) {
  447. return new Vector2(this.x * x, this.y * y);
  448. };
  449. Vector2.prototype.divide = function (otherVector) {
  450. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  451. };
  452. Vector2.prototype.divideToRef = function (otherVector, result) {
  453. result.x = this.x / otherVector.x;
  454. result.y = this.y / otherVector.y;
  455. return this;
  456. };
  457. Vector2.prototype.negate = function () {
  458. return new Vector2(-this.x, -this.y);
  459. };
  460. Vector2.prototype.scaleInPlace = function (scale) {
  461. this.x *= scale;
  462. this.y *= scale;
  463. return this;
  464. };
  465. Vector2.prototype.scale = function (scale) {
  466. return new Vector2(this.x * scale, this.y * scale);
  467. };
  468. Vector2.prototype.equals = function (otherVector) {
  469. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  470. };
  471. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  472. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  473. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  474. };
  475. // Properties
  476. Vector2.prototype.length = function () {
  477. return Math.sqrt(this.x * this.x + this.y * this.y);
  478. };
  479. Vector2.prototype.lengthSquared = function () {
  480. return (this.x * this.x + this.y * this.y);
  481. };
  482. // Methods
  483. Vector2.prototype.normalize = function () {
  484. var len = this.length();
  485. if (len === 0)
  486. return this;
  487. var num = 1.0 / len;
  488. this.x *= num;
  489. this.y *= num;
  490. return this;
  491. };
  492. Vector2.prototype.clone = function () {
  493. return new Vector2(this.x, this.y);
  494. };
  495. // Statics
  496. Vector2.Zero = function () {
  497. return new Vector2(0, 0);
  498. };
  499. Vector2.FromArray = function (array, offset) {
  500. if (offset === void 0) { offset = 0; }
  501. return new Vector2(array[offset], array[offset + 1]);
  502. };
  503. Vector2.FromArrayToRef = function (array, offset, result) {
  504. result.x = array[offset];
  505. result.y = array[offset + 1];
  506. };
  507. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  508. var squared = amount * amount;
  509. var cubed = amount * squared;
  510. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  511. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  512. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  513. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  514. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  515. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  516. return new Vector2(x, y);
  517. };
  518. Vector2.Clamp = function (value, min, max) {
  519. var x = value.x;
  520. x = (x > max.x) ? max.x : x;
  521. x = (x < min.x) ? min.x : x;
  522. var y = value.y;
  523. y = (y > max.y) ? max.y : y;
  524. y = (y < min.y) ? min.y : y;
  525. return new Vector2(x, y);
  526. };
  527. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  528. var squared = amount * amount;
  529. var cubed = amount * squared;
  530. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  531. var part2 = (-2.0 * cubed) + (3.0 * squared);
  532. var part3 = (cubed - (2.0 * squared)) + amount;
  533. var part4 = cubed - squared;
  534. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  535. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  536. return new Vector2(x, y);
  537. };
  538. Vector2.Lerp = function (start, end, amount) {
  539. var x = start.x + ((end.x - start.x) * amount);
  540. var y = start.y + ((end.y - start.y) * amount);
  541. return new Vector2(x, y);
  542. };
  543. Vector2.Dot = function (left, right) {
  544. return left.x * right.x + left.y * right.y;
  545. };
  546. Vector2.Normalize = function (vector) {
  547. var newVector = vector.clone();
  548. newVector.normalize();
  549. return newVector;
  550. };
  551. Vector2.Minimize = function (left, right) {
  552. var x = (left.x < right.x) ? left.x : right.x;
  553. var y = (left.y < right.y) ? left.y : right.y;
  554. return new Vector2(x, y);
  555. };
  556. Vector2.Maximize = function (left, right) {
  557. var x = (left.x > right.x) ? left.x : right.x;
  558. var y = (left.y > right.y) ? left.y : right.y;
  559. return new Vector2(x, y);
  560. };
  561. Vector2.Transform = function (vector, transformation) {
  562. var r = Vector2.Zero();
  563. Vector2.TransformToRef(vector, transformation, r);
  564. return r;
  565. };
  566. Vector2.TransformToRef = function (vector, transformation, result) {
  567. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  568. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  569. result.x = x;
  570. result.y = y;
  571. };
  572. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  573. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  574. var sign = a < 0 ? -1 : 1;
  575. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  576. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  577. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  578. };
  579. Vector2.Distance = function (value1, value2) {
  580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  581. };
  582. Vector2.DistanceSquared = function (value1, value2) {
  583. var x = value1.x - value2.x;
  584. var y = value1.y - value2.y;
  585. return (x * x) + (y * y);
  586. };
  587. Vector2.Center = function (value1, value2) {
  588. var center = value1.add(value2);
  589. center.scaleInPlace(0.5);
  590. return center;
  591. };
  592. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  593. var l2 = Vector2.DistanceSquared(segA, segB);
  594. if (l2 === 0.0) {
  595. return Vector2.Distance(p, segA);
  596. }
  597. var v = segB.subtract(segA);
  598. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  599. var proj = segA.add(v.multiplyByFloats(t, t));
  600. return Vector2.Distance(p, proj);
  601. };
  602. return Vector2;
  603. }());
  604. BABYLON.Vector2 = Vector2;
  605. var Vector3 = (function () {
  606. function Vector3(x, y, z) {
  607. this.x = x;
  608. this.y = y;
  609. this.z = z;
  610. }
  611. Vector3.prototype.toString = function () {
  612. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  613. };
  614. Vector3.prototype.getClassName = function () {
  615. return "Vector3";
  616. };
  617. Vector3.prototype.getHashCode = function () {
  618. var hash = this.x || 0;
  619. hash = (hash * 397) ^ (this.y || 0);
  620. hash = (hash * 397) ^ (this.z || 0);
  621. return hash;
  622. };
  623. // Operators
  624. Vector3.prototype.asArray = function () {
  625. var result = [];
  626. this.toArray(result, 0);
  627. return result;
  628. };
  629. Vector3.prototype.toArray = function (array, index) {
  630. if (index === void 0) { index = 0; }
  631. array[index] = this.x;
  632. array[index + 1] = this.y;
  633. array[index + 2] = this.z;
  634. return this;
  635. };
  636. Vector3.prototype.toQuaternion = function () {
  637. var result = new Quaternion(0, 0, 0, 1);
  638. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  639. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  640. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  641. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  642. var cosy = Math.cos(this.y * 0.5);
  643. var siny = Math.sin(this.y * 0.5);
  644. result.x = coszMinusx * siny;
  645. result.y = -sinzMinusx * siny;
  646. result.z = sinxPlusz * cosy;
  647. result.w = cosxPlusz * cosy;
  648. return result;
  649. };
  650. Vector3.prototype.addInPlace = function (otherVector) {
  651. this.x += otherVector.x;
  652. this.y += otherVector.y;
  653. this.z += otherVector.z;
  654. return this;
  655. };
  656. Vector3.prototype.add = function (otherVector) {
  657. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  658. };
  659. Vector3.prototype.addToRef = function (otherVector, result) {
  660. result.x = this.x + otherVector.x;
  661. result.y = this.y + otherVector.y;
  662. result.z = this.z + otherVector.z;
  663. return this;
  664. };
  665. Vector3.prototype.subtractInPlace = function (otherVector) {
  666. this.x -= otherVector.x;
  667. this.y -= otherVector.y;
  668. this.z -= otherVector.z;
  669. return this;
  670. };
  671. Vector3.prototype.subtract = function (otherVector) {
  672. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  673. };
  674. Vector3.prototype.subtractToRef = function (otherVector, result) {
  675. result.x = this.x - otherVector.x;
  676. result.y = this.y - otherVector.y;
  677. result.z = this.z - otherVector.z;
  678. return this;
  679. };
  680. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  681. return new Vector3(this.x - x, this.y - y, this.z - z);
  682. };
  683. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  684. result.x = this.x - x;
  685. result.y = this.y - y;
  686. result.z = this.z - z;
  687. return this;
  688. };
  689. Vector3.prototype.negate = function () {
  690. return new Vector3(-this.x, -this.y, -this.z);
  691. };
  692. Vector3.prototype.scaleInPlace = function (scale) {
  693. this.x *= scale;
  694. this.y *= scale;
  695. this.z *= scale;
  696. return this;
  697. };
  698. Vector3.prototype.scale = function (scale) {
  699. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  700. };
  701. Vector3.prototype.scaleToRef = function (scale, result) {
  702. result.x = this.x * scale;
  703. result.y = this.y * scale;
  704. result.z = this.z * scale;
  705. };
  706. Vector3.prototype.equals = function (otherVector) {
  707. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  708. };
  709. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  710. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  711. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  712. };
  713. Vector3.prototype.equalsToFloats = function (x, y, z) {
  714. return this.x === x && this.y === y && this.z === z;
  715. };
  716. Vector3.prototype.multiplyInPlace = function (otherVector) {
  717. this.x *= otherVector.x;
  718. this.y *= otherVector.y;
  719. this.z *= otherVector.z;
  720. return this;
  721. };
  722. Vector3.prototype.multiply = function (otherVector) {
  723. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  724. };
  725. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  726. result.x = this.x * otherVector.x;
  727. result.y = this.y * otherVector.y;
  728. result.z = this.z * otherVector.z;
  729. return this;
  730. };
  731. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  732. return new Vector3(this.x * x, this.y * y, this.z * z);
  733. };
  734. Vector3.prototype.divide = function (otherVector) {
  735. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  736. };
  737. Vector3.prototype.divideToRef = function (otherVector, result) {
  738. result.x = this.x / otherVector.x;
  739. result.y = this.y / otherVector.y;
  740. result.z = this.z / otherVector.z;
  741. return this;
  742. };
  743. Vector3.prototype.MinimizeInPlace = function (other) {
  744. if (other.x < this.x)
  745. this.x = other.x;
  746. if (other.y < this.y)
  747. this.y = other.y;
  748. if (other.z < this.z)
  749. this.z = other.z;
  750. return this;
  751. };
  752. Vector3.prototype.MaximizeInPlace = function (other) {
  753. if (other.x > this.x)
  754. this.x = other.x;
  755. if (other.y > this.y)
  756. this.y = other.y;
  757. if (other.z > this.z)
  758. this.z = other.z;
  759. return this;
  760. };
  761. // Properties
  762. Vector3.prototype.length = function () {
  763. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  764. };
  765. Vector3.prototype.lengthSquared = function () {
  766. return (this.x * this.x + this.y * this.y + this.z * this.z);
  767. };
  768. // Methods
  769. Vector3.prototype.normalize = function () {
  770. var len = this.length();
  771. if (len === 0 || len === 1.0)
  772. return this;
  773. var num = 1.0 / len;
  774. this.x *= num;
  775. this.y *= num;
  776. this.z *= num;
  777. return this;
  778. };
  779. Vector3.prototype.clone = function () {
  780. return new Vector3(this.x, this.y, this.z);
  781. };
  782. Vector3.prototype.copyFrom = function (source) {
  783. this.x = source.x;
  784. this.y = source.y;
  785. this.z = source.z;
  786. return this;
  787. };
  788. Vector3.prototype.copyFromFloats = function (x, y, z) {
  789. this.x = x;
  790. this.y = y;
  791. this.z = z;
  792. return this;
  793. };
  794. // Statics
  795. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  796. var d0 = Vector3.Dot(vector0, axis) - size;
  797. var d1 = Vector3.Dot(vector1, axis) - size;
  798. var s = d0 / (d0 - d1);
  799. return s;
  800. };
  801. Vector3.FromArray = function (array, offset) {
  802. if (!offset) {
  803. offset = 0;
  804. }
  805. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  806. };
  807. Vector3.FromFloatArray = function (array, offset) {
  808. if (!offset) {
  809. offset = 0;
  810. }
  811. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  812. };
  813. Vector3.FromArrayToRef = function (array, offset, result) {
  814. result.x = array[offset];
  815. result.y = array[offset + 1];
  816. result.z = array[offset + 2];
  817. };
  818. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  819. result.x = array[offset];
  820. result.y = array[offset + 1];
  821. result.z = array[offset + 2];
  822. };
  823. Vector3.FromFloatsToRef = function (x, y, z, result) {
  824. result.x = x;
  825. result.y = y;
  826. result.z = z;
  827. };
  828. Vector3.Zero = function () {
  829. return new Vector3(0, 0, 0);
  830. };
  831. Vector3.Up = function () {
  832. return new Vector3(0, 1.0, 0);
  833. };
  834. Vector3.Forward = function () {
  835. return new Vector3(0, 0, 1.0);
  836. };
  837. Vector3.Right = function () {
  838. return new Vector3(1.0, 0, 0);
  839. };
  840. Vector3.Left = function () {
  841. return new Vector3(-1.0, 0, 0);
  842. };
  843. Vector3.TransformCoordinates = function (vector, transformation) {
  844. var result = Vector3.Zero();
  845. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  846. return result;
  847. };
  848. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  849. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  850. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  851. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  852. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  853. result.x = x / w;
  854. result.y = y / w;
  855. result.z = z / w;
  856. };
  857. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  858. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  859. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  860. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  861. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  862. result.x = rx / rw;
  863. result.y = ry / rw;
  864. result.z = rz / rw;
  865. };
  866. Vector3.TransformNormal = function (vector, transformation) {
  867. var result = Vector3.Zero();
  868. Vector3.TransformNormalToRef(vector, transformation, result);
  869. return result;
  870. };
  871. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  872. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  873. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  874. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  875. result.x = x;
  876. result.y = y;
  877. result.z = z;
  878. };
  879. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  880. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  881. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  882. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  883. };
  884. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  885. var squared = amount * amount;
  886. var cubed = amount * squared;
  887. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  888. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  889. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  890. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  891. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  892. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  893. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  894. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  895. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  896. return new Vector3(x, y, z);
  897. };
  898. Vector3.Clamp = function (value, min, max) {
  899. var x = value.x;
  900. x = (x > max.x) ? max.x : x;
  901. x = (x < min.x) ? min.x : x;
  902. var y = value.y;
  903. y = (y > max.y) ? max.y : y;
  904. y = (y < min.y) ? min.y : y;
  905. var z = value.z;
  906. z = (z > max.z) ? max.z : z;
  907. z = (z < min.z) ? min.z : z;
  908. return new Vector3(x, y, z);
  909. };
  910. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  911. var squared = amount * amount;
  912. var cubed = amount * squared;
  913. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  914. var part2 = (-2.0 * cubed) + (3.0 * squared);
  915. var part3 = (cubed - (2.0 * squared)) + amount;
  916. var part4 = cubed - squared;
  917. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  918. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  919. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  920. return new Vector3(x, y, z);
  921. };
  922. Vector3.Lerp = function (start, end, amount) {
  923. var result = new Vector3(0, 0, 0);
  924. Vector3.LerpToRef(start, end, amount, result);
  925. return result;
  926. };
  927. Vector3.LerpToRef = function (start, end, amount, result) {
  928. result.x = start.x + ((end.x - start.x) * amount);
  929. result.y = start.y + ((end.y - start.y) * amount);
  930. result.z = start.z + ((end.z - start.z) * amount);
  931. };
  932. Vector3.Dot = function (left, right) {
  933. return (left.x * right.x + left.y * right.y + left.z * right.z);
  934. };
  935. Vector3.Cross = function (left, right) {
  936. var result = Vector3.Zero();
  937. Vector3.CrossToRef(left, right, result);
  938. return result;
  939. };
  940. Vector3.CrossToRef = function (left, right, result) {
  941. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  942. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  943. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  944. result.copyFrom(Tmp.Vector3[0]);
  945. };
  946. Vector3.Normalize = function (vector) {
  947. var result = Vector3.Zero();
  948. Vector3.NormalizeToRef(vector, result);
  949. return result;
  950. };
  951. Vector3.NormalizeToRef = function (vector, result) {
  952. result.copyFrom(vector);
  953. result.normalize();
  954. };
  955. Vector3.Project = function (vector, world, transform, viewport) {
  956. var cw = viewport.width;
  957. var ch = viewport.height;
  958. var cx = viewport.x;
  959. var cy = viewport.y;
  960. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  961. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  962. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  963. world.multiplyToRef(transform, matrix);
  964. matrix.multiplyToRef(viewportMatrix, matrix);
  965. return Vector3.TransformCoordinates(vector, matrix);
  966. };
  967. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  968. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  969. world.multiplyToRef(transform, matrix);
  970. matrix.invert();
  971. source.x = source.x / viewportWidth * 2 - 1;
  972. source.y = -(source.y / viewportHeight * 2 - 1);
  973. var vector = Vector3.TransformCoordinates(source, matrix);
  974. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  975. if (MathTools.WithinEpsilon(num, 1.0)) {
  976. vector = vector.scale(1.0 / num);
  977. }
  978. return vector;
  979. };
  980. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  981. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  982. world.multiplyToRef(view, matrix);
  983. matrix.multiplyToRef(projection, matrix);
  984. matrix.invert();
  985. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  986. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  987. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  988. if (MathTools.WithinEpsilon(num, 1.0)) {
  989. vector = vector.scale(1.0 / num);
  990. }
  991. return vector;
  992. };
  993. Vector3.Minimize = function (left, right) {
  994. var min = left.clone();
  995. min.MinimizeInPlace(right);
  996. return min;
  997. };
  998. Vector3.Maximize = function (left, right) {
  999. var max = left.clone();
  1000. max.MaximizeInPlace(right);
  1001. return max;
  1002. };
  1003. Vector3.Distance = function (value1, value2) {
  1004. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1005. };
  1006. Vector3.DistanceSquared = function (value1, value2) {
  1007. var x = value1.x - value2.x;
  1008. var y = value1.y - value2.y;
  1009. var z = value1.z - value2.z;
  1010. return (x * x) + (y * y) + (z * z);
  1011. };
  1012. Vector3.Center = function (value1, value2) {
  1013. var center = value1.add(value2);
  1014. center.scaleInPlace(0.5);
  1015. return center;
  1016. };
  1017. /**
  1018. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1019. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1020. * to something in order to rotate it from its local system to the given target system.
  1021. */
  1022. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1023. var rotation = Vector3.Zero();
  1024. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1025. return rotation;
  1026. };
  1027. /**
  1028. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1029. */
  1030. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1031. var u = axis1.normalize();
  1032. var w = axis3.normalize();
  1033. // world axis
  1034. var X = Axis.X;
  1035. var Y = Axis.Y;
  1036. // equation unknowns and vars
  1037. var yaw = 0.0;
  1038. var pitch = 0.0;
  1039. var roll = 0.0;
  1040. var x = 0.0;
  1041. var y = 0.0;
  1042. var z = 0.0;
  1043. var t = 0.0;
  1044. var sign = -1.0;
  1045. var nbRevert = 0;
  1046. var cross = Tmp.Vector3[0];
  1047. var dot = 0.0;
  1048. // step 1 : rotation around w
  1049. // Rv3(u) = u1, and u1 belongs to plane xOz
  1050. // Rv3(w) = w1 = w invariant
  1051. var u1 = Tmp.Vector3[1];
  1052. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1053. z = 1.0;
  1054. }
  1055. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1056. x = 1.0;
  1057. }
  1058. else {
  1059. t = w.z / w.x;
  1060. x = -t * Math.sqrt(1 / (1 + t * t));
  1061. z = Math.sqrt(1 / (1 + t * t));
  1062. }
  1063. u1.x = x;
  1064. u1.y = y;
  1065. u1.z = z;
  1066. u1.normalize();
  1067. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1068. cross.normalize();
  1069. if (Vector3.Dot(w, cross) < 0) {
  1070. sign = 1.0;
  1071. }
  1072. dot = Vector3.Dot(u, u1);
  1073. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1074. roll = Math.acos(dot) * sign;
  1075. if (Vector3.Dot(u1, X) < 0) {
  1076. roll = Math.PI + roll;
  1077. u1 = u1.scaleInPlace(-1);
  1078. nbRevert++;
  1079. }
  1080. // step 2 : rotate around u1
  1081. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1082. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1083. var w2 = Tmp.Vector3[2];
  1084. var v2 = Tmp.Vector3[3];
  1085. x = 0.0;
  1086. y = 0.0;
  1087. z = 0.0;
  1088. sign = -1.0;
  1089. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1090. x = 1.0;
  1091. }
  1092. else {
  1093. t = u1.z / u1.x;
  1094. x = -t * Math.sqrt(1 / (1 + t * t));
  1095. z = Math.sqrt(1 / (1 + t * t));
  1096. }
  1097. w2.x = x;
  1098. w2.y = y;
  1099. w2.z = z;
  1100. w2.normalize();
  1101. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1102. v2.normalize();
  1103. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1104. cross.normalize();
  1105. if (Vector3.Dot(u1, cross) < 0) {
  1106. sign = 1.0;
  1107. }
  1108. dot = Vector3.Dot(w, w2);
  1109. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1110. pitch = Math.acos(dot) * sign;
  1111. if (Vector3.Dot(v2, Y) < 0) {
  1112. pitch = Math.PI + pitch;
  1113. nbRevert++;
  1114. }
  1115. // step 3 : rotate around v2
  1116. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1117. sign = -1.0;
  1118. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1119. cross.normalize();
  1120. if (Vector3.Dot(cross, Y) < 0) {
  1121. sign = 1.0;
  1122. }
  1123. dot = Vector3.Dot(u1, X);
  1124. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1125. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1126. if (dot < 0 && nbRevert < 2) {
  1127. yaw = Math.PI + yaw;
  1128. }
  1129. ref.x = pitch;
  1130. ref.y = yaw;
  1131. ref.z = roll;
  1132. };
  1133. return Vector3;
  1134. }());
  1135. BABYLON.Vector3 = Vector3;
  1136. //Vector4 class created for EulerAngle class conversion to Quaternion
  1137. var Vector4 = (function () {
  1138. function Vector4(x, y, z, w) {
  1139. this.x = x;
  1140. this.y = y;
  1141. this.z = z;
  1142. this.w = w;
  1143. }
  1144. Vector4.prototype.toString = function () {
  1145. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1146. };
  1147. Vector4.prototype.getClassName = function () {
  1148. return "Vector4";
  1149. };
  1150. Vector4.prototype.getHashCode = function () {
  1151. var hash = this.x || 0;
  1152. hash = (hash * 397) ^ (this.y || 0);
  1153. hash = (hash * 397) ^ (this.z || 0);
  1154. hash = (hash * 397) ^ (this.w || 0);
  1155. return hash;
  1156. };
  1157. // Operators
  1158. Vector4.prototype.asArray = function () {
  1159. var result = [];
  1160. this.toArray(result, 0);
  1161. return result;
  1162. };
  1163. Vector4.prototype.toArray = function (array, index) {
  1164. if (index === undefined) {
  1165. index = 0;
  1166. }
  1167. array[index] = this.x;
  1168. array[index + 1] = this.y;
  1169. array[index + 2] = this.z;
  1170. array[index + 3] = this.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.addInPlace = function (otherVector) {
  1174. this.x += otherVector.x;
  1175. this.y += otherVector.y;
  1176. this.z += otherVector.z;
  1177. this.w += otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.add = function (otherVector) {
  1181. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1182. };
  1183. Vector4.prototype.addToRef = function (otherVector, result) {
  1184. result.x = this.x + otherVector.x;
  1185. result.y = this.y + otherVector.y;
  1186. result.z = this.z + otherVector.z;
  1187. result.w = this.w + otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractInPlace = function (otherVector) {
  1191. this.x -= otherVector.x;
  1192. this.y -= otherVector.y;
  1193. this.z -= otherVector.z;
  1194. this.w -= otherVector.w;
  1195. return this;
  1196. };
  1197. Vector4.prototype.subtract = function (otherVector) {
  1198. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1199. };
  1200. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1201. result.x = this.x - otherVector.x;
  1202. result.y = this.y - otherVector.y;
  1203. result.z = this.z - otherVector.z;
  1204. result.w = this.w - otherVector.w;
  1205. return this;
  1206. };
  1207. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1208. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1209. };
  1210. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1211. result.x = this.x - x;
  1212. result.y = this.y - y;
  1213. result.z = this.z - z;
  1214. result.w = this.w - w;
  1215. return this;
  1216. };
  1217. Vector4.prototype.negate = function () {
  1218. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1219. };
  1220. Vector4.prototype.scaleInPlace = function (scale) {
  1221. this.x *= scale;
  1222. this.y *= scale;
  1223. this.z *= scale;
  1224. this.w *= scale;
  1225. return this;
  1226. };
  1227. Vector4.prototype.scale = function (scale) {
  1228. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1229. };
  1230. Vector4.prototype.scaleToRef = function (scale, result) {
  1231. result.x = this.x * scale;
  1232. result.y = this.y * scale;
  1233. result.z = this.z * scale;
  1234. result.w = this.w * scale;
  1235. };
  1236. Vector4.prototype.equals = function (otherVector) {
  1237. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1238. };
  1239. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1240. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1241. return otherVector
  1242. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1243. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1244. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1245. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1246. };
  1247. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1248. return this.x === x && this.y === y && this.z === z && this.w === w;
  1249. };
  1250. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1251. this.x *= otherVector.x;
  1252. this.y *= otherVector.y;
  1253. this.z *= otherVector.z;
  1254. this.w *= otherVector.w;
  1255. return this;
  1256. };
  1257. Vector4.prototype.multiply = function (otherVector) {
  1258. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1259. };
  1260. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1261. result.x = this.x * otherVector.x;
  1262. result.y = this.y * otherVector.y;
  1263. result.z = this.z * otherVector.z;
  1264. result.w = this.w * otherVector.w;
  1265. return this;
  1266. };
  1267. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1268. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1269. };
  1270. Vector4.prototype.divide = function (otherVector) {
  1271. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1272. };
  1273. Vector4.prototype.divideToRef = function (otherVector, result) {
  1274. result.x = this.x / otherVector.x;
  1275. result.y = this.y / otherVector.y;
  1276. result.z = this.z / otherVector.z;
  1277. result.w = this.w / otherVector.w;
  1278. return this;
  1279. };
  1280. Vector4.prototype.MinimizeInPlace = function (other) {
  1281. if (other.x < this.x)
  1282. this.x = other.x;
  1283. if (other.y < this.y)
  1284. this.y = other.y;
  1285. if (other.z < this.z)
  1286. this.z = other.z;
  1287. if (other.w < this.w)
  1288. this.w = other.w;
  1289. return this;
  1290. };
  1291. Vector4.prototype.MaximizeInPlace = function (other) {
  1292. if (other.x > this.x)
  1293. this.x = other.x;
  1294. if (other.y > this.y)
  1295. this.y = other.y;
  1296. if (other.z > this.z)
  1297. this.z = other.z;
  1298. if (other.w > this.w)
  1299. this.w = other.w;
  1300. return this;
  1301. };
  1302. // Properties
  1303. Vector4.prototype.length = function () {
  1304. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1305. };
  1306. Vector4.prototype.lengthSquared = function () {
  1307. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1308. };
  1309. // Methods
  1310. Vector4.prototype.normalize = function () {
  1311. var len = this.length();
  1312. if (len === 0)
  1313. return this;
  1314. var num = 1.0 / len;
  1315. this.x *= num;
  1316. this.y *= num;
  1317. this.z *= num;
  1318. this.w *= num;
  1319. return this;
  1320. };
  1321. Vector4.prototype.toVector3 = function () {
  1322. return new Vector3(this.x, this.y, this.z);
  1323. };
  1324. Vector4.prototype.clone = function () {
  1325. return new Vector4(this.x, this.y, this.z, this.w);
  1326. };
  1327. Vector4.prototype.copyFrom = function (source) {
  1328. this.x = source.x;
  1329. this.y = source.y;
  1330. this.z = source.z;
  1331. this.w = source.w;
  1332. return this;
  1333. };
  1334. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1335. this.x = x;
  1336. this.y = y;
  1337. this.z = z;
  1338. this.w = w;
  1339. return this;
  1340. };
  1341. // Statics
  1342. Vector4.FromArray = function (array, offset) {
  1343. if (!offset) {
  1344. offset = 0;
  1345. }
  1346. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1347. };
  1348. Vector4.FromArrayToRef = function (array, offset, result) {
  1349. result.x = array[offset];
  1350. result.y = array[offset + 1];
  1351. result.z = array[offset + 2];
  1352. result.w = array[offset + 3];
  1353. };
  1354. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. result.w = array[offset + 3];
  1359. };
  1360. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1361. result.x = x;
  1362. result.y = y;
  1363. result.z = z;
  1364. result.w = w;
  1365. };
  1366. Vector4.Zero = function () {
  1367. return new Vector4(0, 0, 0, 0);
  1368. };
  1369. Vector4.Normalize = function (vector) {
  1370. var result = Vector4.Zero();
  1371. Vector4.NormalizeToRef(vector, result);
  1372. return result;
  1373. };
  1374. Vector4.NormalizeToRef = function (vector, result) {
  1375. result.copyFrom(vector);
  1376. result.normalize();
  1377. };
  1378. Vector4.Minimize = function (left, right) {
  1379. var min = left.clone();
  1380. min.MinimizeInPlace(right);
  1381. return min;
  1382. };
  1383. Vector4.Maximize = function (left, right) {
  1384. var max = left.clone();
  1385. max.MaximizeInPlace(right);
  1386. return max;
  1387. };
  1388. Vector4.Distance = function (value1, value2) {
  1389. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1390. };
  1391. Vector4.DistanceSquared = function (value1, value2) {
  1392. var x = value1.x - value2.x;
  1393. var y = value1.y - value2.y;
  1394. var z = value1.z - value2.z;
  1395. var w = value1.w - value2.w;
  1396. return (x * x) + (y * y) + (z * z) + (w * w);
  1397. };
  1398. Vector4.Center = function (value1, value2) {
  1399. var center = value1.add(value2);
  1400. center.scaleInPlace(0.5);
  1401. return center;
  1402. };
  1403. return Vector4;
  1404. }());
  1405. BABYLON.Vector4 = Vector4;
  1406. var Size = (function () {
  1407. function Size(width, height) {
  1408. this.width = width;
  1409. this.height = height;
  1410. }
  1411. Size.prototype.toString = function () {
  1412. return "{W: " + this.width + ", H: " + this.height + "}";
  1413. };
  1414. Size.prototype.getClassName = function () {
  1415. return "Size";
  1416. };
  1417. Size.prototype.getHashCode = function () {
  1418. var hash = this.width || 0;
  1419. hash = (hash * 397) ^ (this.height || 0);
  1420. return hash;
  1421. };
  1422. Size.prototype.copyFrom = function (src) {
  1423. this.width = src.width;
  1424. this.height = src.height;
  1425. };
  1426. Size.prototype.copyFromFloats = function (width, height) {
  1427. this.width = width;
  1428. this.height = height;
  1429. };
  1430. Size.prototype.multiplyByFloats = function (w, h) {
  1431. return new Size(this.width * w, this.height * h);
  1432. };
  1433. Size.prototype.clone = function () {
  1434. return new Size(this.width, this.height);
  1435. };
  1436. Size.prototype.equals = function (other) {
  1437. if (!other) {
  1438. return false;
  1439. }
  1440. return (this.width === other.width) && (this.height === other.height);
  1441. };
  1442. Object.defineProperty(Size.prototype, "surface", {
  1443. get: function () {
  1444. return this.width * this.height;
  1445. },
  1446. enumerable: true,
  1447. configurable: true
  1448. });
  1449. Size.Zero = function () {
  1450. return new Size(0, 0);
  1451. };
  1452. Size.prototype.add = function (otherSize) {
  1453. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1454. return r;
  1455. };
  1456. Size.prototype.subtract = function (otherSize) {
  1457. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1458. return r;
  1459. };
  1460. Size.Lerp = function (start, end, amount) {
  1461. var w = start.width + ((end.width - start.width) * amount);
  1462. var h = start.height + ((end.height - start.height) * amount);
  1463. return new Size(w, h);
  1464. };
  1465. return Size;
  1466. }());
  1467. BABYLON.Size = Size;
  1468. var Quaternion = (function () {
  1469. function Quaternion(x, y, z, w) {
  1470. if (x === void 0) { x = 0; }
  1471. if (y === void 0) { y = 0; }
  1472. if (z === void 0) { z = 0; }
  1473. if (w === void 0) { w = 1; }
  1474. this.x = x;
  1475. this.y = y;
  1476. this.z = z;
  1477. this.w = w;
  1478. }
  1479. Quaternion.prototype.toString = function () {
  1480. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1481. };
  1482. Quaternion.prototype.getClassName = function () {
  1483. return "Quaternion";
  1484. };
  1485. Quaternion.prototype.getHashCode = function () {
  1486. var hash = this.x || 0;
  1487. hash = (hash * 397) ^ (this.y || 0);
  1488. hash = (hash * 397) ^ (this.z || 0);
  1489. hash = (hash * 397) ^ (this.w || 0);
  1490. return hash;
  1491. };
  1492. Quaternion.prototype.asArray = function () {
  1493. return [this.x, this.y, this.z, this.w];
  1494. };
  1495. Quaternion.prototype.equals = function (otherQuaternion) {
  1496. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1497. };
  1498. Quaternion.prototype.clone = function () {
  1499. return new Quaternion(this.x, this.y, this.z, this.w);
  1500. };
  1501. Quaternion.prototype.copyFrom = function (other) {
  1502. this.x = other.x;
  1503. this.y = other.y;
  1504. this.z = other.z;
  1505. this.w = other.w;
  1506. return this;
  1507. };
  1508. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1509. this.x = x;
  1510. this.y = y;
  1511. this.z = z;
  1512. this.w = w;
  1513. return this;
  1514. };
  1515. Quaternion.prototype.add = function (other) {
  1516. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1517. };
  1518. Quaternion.prototype.subtract = function (other) {
  1519. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1520. };
  1521. Quaternion.prototype.scale = function (value) {
  1522. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1523. };
  1524. Quaternion.prototype.multiply = function (q1) {
  1525. var result = new Quaternion(0, 0, 0, 1.0);
  1526. this.multiplyToRef(q1, result);
  1527. return result;
  1528. };
  1529. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1530. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1531. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1532. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1533. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1534. result.copyFromFloats(x, y, z, w);
  1535. return this;
  1536. };
  1537. Quaternion.prototype.multiplyInPlace = function (q1) {
  1538. this.multiplyToRef(q1, this);
  1539. return this;
  1540. };
  1541. Quaternion.prototype.conjugateToRef = function (ref) {
  1542. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1543. return this;
  1544. };
  1545. Quaternion.prototype.conjugateInPlace = function () {
  1546. this.x *= -1;
  1547. this.y *= -1;
  1548. this.z *= -1;
  1549. return this;
  1550. };
  1551. Quaternion.prototype.conjugate = function () {
  1552. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.length = function () {
  1556. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1557. };
  1558. Quaternion.prototype.normalize = function () {
  1559. var length = 1.0 / this.length();
  1560. this.x *= length;
  1561. this.y *= length;
  1562. this.z *= length;
  1563. this.w *= length;
  1564. return this;
  1565. };
  1566. Quaternion.prototype.toEulerAngles = function (order) {
  1567. if (order === void 0) { order = "YZX"; }
  1568. var result = Vector3.Zero();
  1569. this.toEulerAnglesToRef(result, order);
  1570. return result;
  1571. };
  1572. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1573. if (order === void 0) { order = "YZX"; }
  1574. var qz = this.z;
  1575. var qx = this.x;
  1576. var qy = this.y;
  1577. var qw = this.w;
  1578. var sqw = qw * qw;
  1579. var sqz = qz * qz;
  1580. var sqx = qx * qx;
  1581. var sqy = qy * qy;
  1582. var zAxisY = qy * qz - qx * qw;
  1583. var limit = .4999999;
  1584. if (zAxisY < -limit) {
  1585. result.y = 2 * Math.atan2(qy, qw);
  1586. result.x = Math.PI / 2;
  1587. result.z = 0;
  1588. }
  1589. else if (zAxisY > limit) {
  1590. result.y = 2 * Math.atan2(qy, qw);
  1591. result.x = -Math.PI / 2;
  1592. result.z = 0;
  1593. }
  1594. else {
  1595. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  1596. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  1597. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  1598. }
  1599. return this;
  1600. };
  1601. Quaternion.prototype.toRotationMatrix = function (result) {
  1602. var xx = this.x * this.x;
  1603. var yy = this.y * this.y;
  1604. var zz = this.z * this.z;
  1605. var xy = this.x * this.y;
  1606. var zw = this.z * this.w;
  1607. var zx = this.z * this.x;
  1608. var yw = this.y * this.w;
  1609. var yz = this.y * this.z;
  1610. var xw = this.x * this.w;
  1611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1612. result.m[1] = 2.0 * (xy + zw);
  1613. result.m[2] = 2.0 * (zx - yw);
  1614. result.m[3] = 0;
  1615. result.m[4] = 2.0 * (xy - zw);
  1616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1617. result.m[6] = 2.0 * (yz + xw);
  1618. result.m[7] = 0;
  1619. result.m[8] = 2.0 * (zx + yw);
  1620. result.m[9] = 2.0 * (yz - xw);
  1621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1622. result.m[11] = 0;
  1623. result.m[12] = 0;
  1624. result.m[13] = 0;
  1625. result.m[14] = 0;
  1626. result.m[15] = 1.0;
  1627. return this;
  1628. };
  1629. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1630. Quaternion.FromRotationMatrixToRef(matrix, this);
  1631. return this;
  1632. };
  1633. // Statics
  1634. Quaternion.FromRotationMatrix = function (matrix) {
  1635. var result = new Quaternion();
  1636. Quaternion.FromRotationMatrixToRef(matrix, result);
  1637. return result;
  1638. };
  1639. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1640. var data = matrix.m;
  1641. var m11 = data[0], m12 = data[4], m13 = data[8];
  1642. var m21 = data[1], m22 = data[5], m23 = data[9];
  1643. var m31 = data[2], m32 = data[6], m33 = data[10];
  1644. var trace = m11 + m22 + m33;
  1645. var s;
  1646. if (trace > 0) {
  1647. s = 0.5 / Math.sqrt(trace + 1.0);
  1648. result.w = 0.25 / s;
  1649. result.x = (m32 - m23) * s;
  1650. result.y = (m13 - m31) * s;
  1651. result.z = (m21 - m12) * s;
  1652. }
  1653. else if (m11 > m22 && m11 > m33) {
  1654. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1655. result.w = (m32 - m23) / s;
  1656. result.x = 0.25 * s;
  1657. result.y = (m12 + m21) / s;
  1658. result.z = (m13 + m31) / s;
  1659. }
  1660. else if (m22 > m33) {
  1661. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1662. result.w = (m13 - m31) / s;
  1663. result.x = (m12 + m21) / s;
  1664. result.y = 0.25 * s;
  1665. result.z = (m23 + m32) / s;
  1666. }
  1667. else {
  1668. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1669. result.w = (m21 - m12) / s;
  1670. result.x = (m13 + m31) / s;
  1671. result.y = (m23 + m32) / s;
  1672. result.z = 0.25 * s;
  1673. }
  1674. };
  1675. Quaternion.Inverse = function (q) {
  1676. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1677. };
  1678. Quaternion.Identity = function () {
  1679. return new Quaternion(0, 0, 0, 1);
  1680. };
  1681. Quaternion.RotationAxis = function (axis, angle) {
  1682. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1683. };
  1684. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1685. var sin = Math.sin(angle / 2);
  1686. axis.normalize();
  1687. result.w = Math.cos(angle / 2);
  1688. result.x = axis.x * sin;
  1689. result.y = axis.y * sin;
  1690. result.z = axis.z * sin;
  1691. return result;
  1692. };
  1693. Quaternion.FromArray = function (array, offset) {
  1694. if (!offset) {
  1695. offset = 0;
  1696. }
  1697. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1698. };
  1699. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1700. var q = new Quaternion();
  1701. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1702. return q;
  1703. };
  1704. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1705. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1706. var halfRoll = roll * 0.5;
  1707. var halfPitch = pitch * 0.5;
  1708. var halfYaw = yaw * 0.5;
  1709. var sinRoll = Math.sin(halfRoll);
  1710. var cosRoll = Math.cos(halfRoll);
  1711. var sinPitch = Math.sin(halfPitch);
  1712. var cosPitch = Math.cos(halfPitch);
  1713. var sinYaw = Math.sin(halfYaw);
  1714. var cosYaw = Math.cos(halfYaw);
  1715. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1716. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1717. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1718. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1719. };
  1720. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1721. var result = new Quaternion();
  1722. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1723. return result;
  1724. };
  1725. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1726. // Produces a quaternion from Euler angles in the z-x-z orientation
  1727. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1728. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1729. var halfBeta = beta * 0.5;
  1730. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1731. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1732. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1733. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1734. };
  1735. Quaternion.Slerp = function (left, right, amount) {
  1736. var result = Quaternion.Identity();
  1737. Quaternion.SlerpToRef(left, right, amount, result);
  1738. return result;
  1739. };
  1740. Quaternion.SlerpToRef = function (left, right, amount, result) {
  1741. var num2;
  1742. var num3;
  1743. var num = amount;
  1744. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1745. var flag = false;
  1746. if (num4 < 0) {
  1747. flag = true;
  1748. num4 = -num4;
  1749. }
  1750. if (num4 > 0.999999) {
  1751. num3 = 1 - num;
  1752. num2 = flag ? -num : num;
  1753. }
  1754. else {
  1755. var num5 = Math.acos(num4);
  1756. var num6 = (1.0 / Math.sin(num5));
  1757. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1758. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1759. }
  1760. result.x = (num3 * left.x) + (num2 * right.x);
  1761. result.y = (num3 * left.y) + (num2 * right.y);
  1762. result.z = (num3 * left.z) + (num2 * right.z);
  1763. result.w = (num3 * left.w) + (num2 * right.w);
  1764. };
  1765. return Quaternion;
  1766. }());
  1767. BABYLON.Quaternion = Quaternion;
  1768. var Matrix = (function () {
  1769. function Matrix() {
  1770. this.m = new Float32Array(16);
  1771. }
  1772. // Properties
  1773. Matrix.prototype.isIdentity = function () {
  1774. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1775. return false;
  1776. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1777. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1778. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1779. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1780. return false;
  1781. return true;
  1782. };
  1783. Matrix.prototype.determinant = function () {
  1784. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1785. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1786. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1787. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1788. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1789. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1790. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1791. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1792. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1793. };
  1794. // Methods
  1795. Matrix.prototype.toArray = function () {
  1796. return this.m;
  1797. };
  1798. Matrix.prototype.asArray = function () {
  1799. return this.toArray();
  1800. };
  1801. Matrix.prototype.invert = function () {
  1802. this.invertToRef(this);
  1803. return this;
  1804. };
  1805. Matrix.prototype.reset = function () {
  1806. for (var index = 0; index < 16; index++) {
  1807. this.m[index] = 0;
  1808. }
  1809. return this;
  1810. };
  1811. Matrix.prototype.add = function (other) {
  1812. var result = new Matrix();
  1813. this.addToRef(other, result);
  1814. return result;
  1815. };
  1816. Matrix.prototype.addToRef = function (other, result) {
  1817. for (var index = 0; index < 16; index++) {
  1818. result.m[index] = this.m[index] + other.m[index];
  1819. }
  1820. return this;
  1821. };
  1822. Matrix.prototype.addToSelf = function (other) {
  1823. for (var index = 0; index < 16; index++) {
  1824. this.m[index] += other.m[index];
  1825. }
  1826. return this;
  1827. };
  1828. Matrix.prototype.invertToRef = function (other) {
  1829. var l1 = this.m[0];
  1830. var l2 = this.m[1];
  1831. var l3 = this.m[2];
  1832. var l4 = this.m[3];
  1833. var l5 = this.m[4];
  1834. var l6 = this.m[5];
  1835. var l7 = this.m[6];
  1836. var l8 = this.m[7];
  1837. var l9 = this.m[8];
  1838. var l10 = this.m[9];
  1839. var l11 = this.m[10];
  1840. var l12 = this.m[11];
  1841. var l13 = this.m[12];
  1842. var l14 = this.m[13];
  1843. var l15 = this.m[14];
  1844. var l16 = this.m[15];
  1845. var l17 = (l11 * l16) - (l12 * l15);
  1846. var l18 = (l10 * l16) - (l12 * l14);
  1847. var l19 = (l10 * l15) - (l11 * l14);
  1848. var l20 = (l9 * l16) - (l12 * l13);
  1849. var l21 = (l9 * l15) - (l11 * l13);
  1850. var l22 = (l9 * l14) - (l10 * l13);
  1851. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1852. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1853. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1854. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1855. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1856. var l28 = (l7 * l16) - (l8 * l15);
  1857. var l29 = (l6 * l16) - (l8 * l14);
  1858. var l30 = (l6 * l15) - (l7 * l14);
  1859. var l31 = (l5 * l16) - (l8 * l13);
  1860. var l32 = (l5 * l15) - (l7 * l13);
  1861. var l33 = (l5 * l14) - (l6 * l13);
  1862. var l34 = (l7 * l12) - (l8 * l11);
  1863. var l35 = (l6 * l12) - (l8 * l10);
  1864. var l36 = (l6 * l11) - (l7 * l10);
  1865. var l37 = (l5 * l12) - (l8 * l9);
  1866. var l38 = (l5 * l11) - (l7 * l9);
  1867. var l39 = (l5 * l10) - (l6 * l9);
  1868. other.m[0] = l23 * l27;
  1869. other.m[4] = l24 * l27;
  1870. other.m[8] = l25 * l27;
  1871. other.m[12] = l26 * l27;
  1872. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1873. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1874. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1875. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1876. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1877. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1878. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1879. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1880. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1881. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1882. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1883. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1884. return this;
  1885. };
  1886. Matrix.prototype.setTranslation = function (vector3) {
  1887. this.m[12] = vector3.x;
  1888. this.m[13] = vector3.y;
  1889. this.m[14] = vector3.z;
  1890. return this;
  1891. };
  1892. Matrix.prototype.getTranslation = function () {
  1893. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1894. };
  1895. Matrix.prototype.multiply = function (other) {
  1896. var result = new Matrix();
  1897. this.multiplyToRef(other, result);
  1898. return result;
  1899. };
  1900. Matrix.prototype.copyFrom = function (other) {
  1901. for (var index = 0; index < 16; index++) {
  1902. this.m[index] = other.m[index];
  1903. }
  1904. return this;
  1905. };
  1906. Matrix.prototype.copyToArray = function (array, offset) {
  1907. if (offset === void 0) { offset = 0; }
  1908. for (var index = 0; index < 16; index++) {
  1909. array[offset + index] = this.m[index];
  1910. }
  1911. return this;
  1912. };
  1913. Matrix.prototype.multiplyToRef = function (other, result) {
  1914. this.multiplyToArray(other, result.m, 0);
  1915. return this;
  1916. };
  1917. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1918. var tm0 = this.m[0];
  1919. var tm1 = this.m[1];
  1920. var tm2 = this.m[2];
  1921. var tm3 = this.m[3];
  1922. var tm4 = this.m[4];
  1923. var tm5 = this.m[5];
  1924. var tm6 = this.m[6];
  1925. var tm7 = this.m[7];
  1926. var tm8 = this.m[8];
  1927. var tm9 = this.m[9];
  1928. var tm10 = this.m[10];
  1929. var tm11 = this.m[11];
  1930. var tm12 = this.m[12];
  1931. var tm13 = this.m[13];
  1932. var tm14 = this.m[14];
  1933. var tm15 = this.m[15];
  1934. var om0 = other.m[0];
  1935. var om1 = other.m[1];
  1936. var om2 = other.m[2];
  1937. var om3 = other.m[3];
  1938. var om4 = other.m[4];
  1939. var om5 = other.m[5];
  1940. var om6 = other.m[6];
  1941. var om7 = other.m[7];
  1942. var om8 = other.m[8];
  1943. var om9 = other.m[9];
  1944. var om10 = other.m[10];
  1945. var om11 = other.m[11];
  1946. var om12 = other.m[12];
  1947. var om13 = other.m[13];
  1948. var om14 = other.m[14];
  1949. var om15 = other.m[15];
  1950. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1951. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1952. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1953. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1954. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1955. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1956. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1957. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1958. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1959. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1960. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1961. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1962. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1963. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1964. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1965. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1966. return this;
  1967. };
  1968. Matrix.prototype.equals = function (value) {
  1969. return value &&
  1970. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1971. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1972. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1973. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1974. };
  1975. Matrix.prototype.clone = function () {
  1976. return Matrix.FromValues(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5], this.m[6], this.m[7], this.m[8], this.m[9], this.m[10], this.m[11], this.m[12], this.m[13], this.m[14], this.m[15]);
  1977. };
  1978. Matrix.prototype.getClassName = function () {
  1979. return "Matrix";
  1980. };
  1981. Matrix.prototype.getHashCode = function () {
  1982. var hash = this.m[0] || 0;
  1983. for (var i = 1; i < 16; i++) {
  1984. hash = (hash * 397) ^ (this.m[i] || 0);
  1985. }
  1986. return hash;
  1987. };
  1988. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1989. translation.x = this.m[12];
  1990. translation.y = this.m[13];
  1991. translation.z = this.m[14];
  1992. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1993. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1994. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1995. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1996. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1997. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1998. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1999. rotation.x = 0;
  2000. rotation.y = 0;
  2001. rotation.z = 0;
  2002. rotation.w = 1;
  2003. return false;
  2004. }
  2005. Matrix.FromValuesToRef(this.m[0] / scale.x, this.m[1] / scale.x, this.m[2] / scale.x, 0, this.m[4] / scale.y, this.m[5] / scale.y, this.m[6] / scale.y, 0, this.m[8] / scale.z, this.m[9] / scale.z, this.m[10] / scale.z, 0, 0, 0, 0, 1, Tmp.Matrix[0]);
  2006. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  2007. return true;
  2008. };
  2009. Matrix.prototype.getRotationMatrix = function () {
  2010. var result = Matrix.Identity();
  2011. this.getRotationMatrixToRef(result);
  2012. return result;
  2013. };
  2014. Matrix.prototype.getRotationMatrixToRef = function (result) {
  2015. var m = this.m;
  2016. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  2017. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  2018. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  2019. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  2020. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  2021. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  2022. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  2023. };
  2024. // Statics
  2025. Matrix.FromArray = function (array, offset) {
  2026. var result = new Matrix();
  2027. if (!offset) {
  2028. offset = 0;
  2029. }
  2030. Matrix.FromArrayToRef(array, offset, result);
  2031. return result;
  2032. };
  2033. Matrix.FromArrayToRef = function (array, offset, result) {
  2034. for (var index = 0; index < 16; index++) {
  2035. result.m[index] = array[index + offset];
  2036. }
  2037. };
  2038. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2039. for (var index = 0; index < 16; index++) {
  2040. result.m[index] = array[index + offset] * scale;
  2041. }
  2042. };
  2043. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2044. result.m[0] = initialM11;
  2045. result.m[1] = initialM12;
  2046. result.m[2] = initialM13;
  2047. result.m[3] = initialM14;
  2048. result.m[4] = initialM21;
  2049. result.m[5] = initialM22;
  2050. result.m[6] = initialM23;
  2051. result.m[7] = initialM24;
  2052. result.m[8] = initialM31;
  2053. result.m[9] = initialM32;
  2054. result.m[10] = initialM33;
  2055. result.m[11] = initialM34;
  2056. result.m[12] = initialM41;
  2057. result.m[13] = initialM42;
  2058. result.m[14] = initialM43;
  2059. result.m[15] = initialM44;
  2060. };
  2061. Matrix.prototype.getRow = function (index) {
  2062. if (index < 0 || index > 3) {
  2063. return null;
  2064. }
  2065. var i = index * 4;
  2066. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2067. };
  2068. Matrix.prototype.setRow = function (index, row) {
  2069. if (index < 0 || index > 3) {
  2070. return this;
  2071. }
  2072. var i = index * 4;
  2073. this.m[i + 0] = row.x;
  2074. this.m[i + 1] = row.y;
  2075. this.m[i + 2] = row.z;
  2076. this.m[i + 3] = row.w;
  2077. return this;
  2078. };
  2079. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2080. var result = new Matrix();
  2081. result.m[0] = initialM11;
  2082. result.m[1] = initialM12;
  2083. result.m[2] = initialM13;
  2084. result.m[3] = initialM14;
  2085. result.m[4] = initialM21;
  2086. result.m[5] = initialM22;
  2087. result.m[6] = initialM23;
  2088. result.m[7] = initialM24;
  2089. result.m[8] = initialM31;
  2090. result.m[9] = initialM32;
  2091. result.m[10] = initialM33;
  2092. result.m[11] = initialM34;
  2093. result.m[12] = initialM41;
  2094. result.m[13] = initialM42;
  2095. result.m[14] = initialM43;
  2096. result.m[15] = initialM44;
  2097. return result;
  2098. };
  2099. Matrix.Compose = function (scale, rotation, translation) {
  2100. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2101. var rotationMatrix = Matrix.Identity();
  2102. rotation.toRotationMatrix(rotationMatrix);
  2103. result = result.multiply(rotationMatrix);
  2104. result.setTranslation(translation);
  2105. return result;
  2106. };
  2107. Matrix.Identity = function () {
  2108. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2109. };
  2110. Matrix.IdentityToRef = function (result) {
  2111. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2112. };
  2113. Matrix.Zero = function () {
  2114. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2115. };
  2116. Matrix.RotationX = function (angle) {
  2117. var result = new Matrix();
  2118. Matrix.RotationXToRef(angle, result);
  2119. return result;
  2120. };
  2121. Matrix.Invert = function (source) {
  2122. var result = new Matrix();
  2123. source.invertToRef(result);
  2124. return result;
  2125. };
  2126. Matrix.RotationXToRef = function (angle, result) {
  2127. var s = Math.sin(angle);
  2128. var c = Math.cos(angle);
  2129. result.m[0] = 1.0;
  2130. result.m[15] = 1.0;
  2131. result.m[5] = c;
  2132. result.m[10] = c;
  2133. result.m[9] = -s;
  2134. result.m[6] = s;
  2135. result.m[1] = 0;
  2136. result.m[2] = 0;
  2137. result.m[3] = 0;
  2138. result.m[4] = 0;
  2139. result.m[7] = 0;
  2140. result.m[8] = 0;
  2141. result.m[11] = 0;
  2142. result.m[12] = 0;
  2143. result.m[13] = 0;
  2144. result.m[14] = 0;
  2145. };
  2146. Matrix.RotationY = function (angle) {
  2147. var result = new Matrix();
  2148. Matrix.RotationYToRef(angle, result);
  2149. return result;
  2150. };
  2151. Matrix.RotationYToRef = function (angle, result) {
  2152. var s = Math.sin(angle);
  2153. var c = Math.cos(angle);
  2154. result.m[5] = 1.0;
  2155. result.m[15] = 1.0;
  2156. result.m[0] = c;
  2157. result.m[2] = -s;
  2158. result.m[8] = s;
  2159. result.m[10] = c;
  2160. result.m[1] = 0;
  2161. result.m[3] = 0;
  2162. result.m[4] = 0;
  2163. result.m[6] = 0;
  2164. result.m[7] = 0;
  2165. result.m[9] = 0;
  2166. result.m[11] = 0;
  2167. result.m[12] = 0;
  2168. result.m[13] = 0;
  2169. result.m[14] = 0;
  2170. };
  2171. Matrix.RotationZ = function (angle) {
  2172. var result = new Matrix();
  2173. Matrix.RotationZToRef(angle, result);
  2174. return result;
  2175. };
  2176. Matrix.RotationZToRef = function (angle, result) {
  2177. var s = Math.sin(angle);
  2178. var c = Math.cos(angle);
  2179. result.m[10] = 1.0;
  2180. result.m[15] = 1.0;
  2181. result.m[0] = c;
  2182. result.m[1] = s;
  2183. result.m[4] = -s;
  2184. result.m[5] = c;
  2185. result.m[2] = 0;
  2186. result.m[3] = 0;
  2187. result.m[6] = 0;
  2188. result.m[7] = 0;
  2189. result.m[8] = 0;
  2190. result.m[9] = 0;
  2191. result.m[11] = 0;
  2192. result.m[12] = 0;
  2193. result.m[13] = 0;
  2194. result.m[14] = 0;
  2195. };
  2196. Matrix.RotationAxis = function (axis, angle) {
  2197. var result = Matrix.Zero();
  2198. Matrix.RotationAxisToRef(axis, angle, result);
  2199. return result;
  2200. };
  2201. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2202. var s = Math.sin(-angle);
  2203. var c = Math.cos(-angle);
  2204. var c1 = 1 - c;
  2205. axis.normalize();
  2206. result.m[0] = (axis.x * axis.x) * c1 + c;
  2207. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2208. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2209. result.m[3] = 0.0;
  2210. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2211. result.m[5] = (axis.y * axis.y) * c1 + c;
  2212. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2213. result.m[7] = 0.0;
  2214. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2215. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2216. result.m[10] = (axis.z * axis.z) * c1 + c;
  2217. result.m[11] = 0.0;
  2218. result.m[15] = 1.0;
  2219. };
  2220. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2221. var result = new Matrix();
  2222. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2223. return result;
  2224. };
  2225. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2226. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2227. this._tempQuaternion.toRotationMatrix(result);
  2228. };
  2229. Matrix.Scaling = function (x, y, z) {
  2230. var result = Matrix.Zero();
  2231. Matrix.ScalingToRef(x, y, z, result);
  2232. return result;
  2233. };
  2234. Matrix.ScalingToRef = function (x, y, z, result) {
  2235. result.m[0] = x;
  2236. result.m[1] = 0;
  2237. result.m[2] = 0;
  2238. result.m[3] = 0;
  2239. result.m[4] = 0;
  2240. result.m[5] = y;
  2241. result.m[6] = 0;
  2242. result.m[7] = 0;
  2243. result.m[8] = 0;
  2244. result.m[9] = 0;
  2245. result.m[10] = z;
  2246. result.m[11] = 0;
  2247. result.m[12] = 0;
  2248. result.m[13] = 0;
  2249. result.m[14] = 0;
  2250. result.m[15] = 1.0;
  2251. };
  2252. Matrix.Translation = function (x, y, z) {
  2253. var result = Matrix.Identity();
  2254. Matrix.TranslationToRef(x, y, z, result);
  2255. return result;
  2256. };
  2257. Matrix.TranslationToRef = function (x, y, z, result) {
  2258. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2259. };
  2260. Matrix.Lerp = function (startValue, endValue, gradient) {
  2261. var result = Matrix.Zero();
  2262. for (var index = 0; index < 16; index++) {
  2263. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2264. }
  2265. return result;
  2266. };
  2267. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2268. var startScale = new Vector3(0, 0, 0);
  2269. var startRotation = new Quaternion();
  2270. var startTranslation = new Vector3(0, 0, 0);
  2271. startValue.decompose(startScale, startRotation, startTranslation);
  2272. var endScale = new Vector3(0, 0, 0);
  2273. var endRotation = new Quaternion();
  2274. var endTranslation = new Vector3(0, 0, 0);
  2275. endValue.decompose(endScale, endRotation, endTranslation);
  2276. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2277. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2278. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2279. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2280. };
  2281. Matrix.LookAtLH = function (eye, target, up) {
  2282. var result = Matrix.Zero();
  2283. Matrix.LookAtLHToRef(eye, target, up, result);
  2284. return result;
  2285. };
  2286. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2287. // Z axis
  2288. target.subtractToRef(eye, this._zAxis);
  2289. this._zAxis.normalize();
  2290. // X axis
  2291. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2292. if (this._xAxis.lengthSquared() === 0) {
  2293. this._xAxis.x = 1.0;
  2294. }
  2295. else {
  2296. this._xAxis.normalize();
  2297. }
  2298. // Y axis
  2299. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2300. this._yAxis.normalize();
  2301. // Eye angles
  2302. var ex = -Vector3.Dot(this._xAxis, eye);
  2303. var ey = -Vector3.Dot(this._yAxis, eye);
  2304. var ez = -Vector3.Dot(this._zAxis, eye);
  2305. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2306. };
  2307. Matrix.LookAtRH = function (eye, target, up) {
  2308. var result = Matrix.Zero();
  2309. Matrix.LookAtRHToRef(eye, target, up, result);
  2310. return result;
  2311. };
  2312. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2313. // Z axis
  2314. eye.subtractToRef(target, this._zAxis);
  2315. this._zAxis.normalize();
  2316. // X axis
  2317. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2318. if (this._xAxis.lengthSquared() === 0) {
  2319. this._xAxis.x = 1.0;
  2320. }
  2321. else {
  2322. this._xAxis.normalize();
  2323. }
  2324. // Y axis
  2325. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2326. this._yAxis.normalize();
  2327. // Eye angles
  2328. var ex = -Vector3.Dot(this._xAxis, eye);
  2329. var ey = -Vector3.Dot(this._yAxis, eye);
  2330. var ez = -Vector3.Dot(this._zAxis, eye);
  2331. return Matrix.FromValuesToRef(this._xAxis.x, this._yAxis.x, this._zAxis.x, 0, this._xAxis.y, this._yAxis.y, this._zAxis.y, 0, this._xAxis.z, this._yAxis.z, this._zAxis.z, 0, ex, ey, ez, 1, result);
  2332. };
  2333. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2334. var matrix = Matrix.Zero();
  2335. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2336. return matrix;
  2337. };
  2338. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2339. var n = znear;
  2340. var f = zfar;
  2341. var a = 2.0 / width;
  2342. var b = 2.0 / height;
  2343. var c = 2.0 / (f - n);
  2344. var d = -(f + n) / (f - n);
  2345. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, 0, 0, d, 1, result);
  2346. };
  2347. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2348. var matrix = Matrix.Zero();
  2349. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2350. return matrix;
  2351. };
  2352. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2353. var n = znear;
  2354. var f = zfar;
  2355. var a = 2.0 / (right - left);
  2356. var b = 2.0 / (top - bottom);
  2357. var c = 2.0 / (f - n);
  2358. var d = -(f + n) / (f - n);
  2359. var i0 = (left + right) / (left - right);
  2360. var i1 = (top + bottom) / (bottom - top);
  2361. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, i0, i1, d, 1, result);
  2362. };
  2363. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2364. var matrix = Matrix.Zero();
  2365. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2366. return matrix;
  2367. };
  2368. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2369. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2370. result.m[10] *= -1.0;
  2371. };
  2372. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2373. var matrix = Matrix.Zero();
  2374. var n = znear;
  2375. var f = zfar;
  2376. var a = 2.0 * n / width;
  2377. var b = 2.0 * n / height;
  2378. var c = (f + n) / (f - n);
  2379. var d = -2.0 * f * n / (f - n);
  2380. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 1, 0, 0, d, 0, matrix);
  2381. return matrix;
  2382. };
  2383. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2384. var matrix = Matrix.Zero();
  2385. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2386. return matrix;
  2387. };
  2388. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2389. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2390. var n = znear;
  2391. var f = zfar;
  2392. var t = 1.0 / (Math.tan(fov * 0.5));
  2393. var a = isVerticalFovFixed ? (t / aspect) : t;
  2394. var b = isVerticalFovFixed ? t : (t * aspect);
  2395. var c = (f + n) / (f - n);
  2396. var d = -2.0 * f * n / (f - n);
  2397. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 1, 0, 0, d, 0, result);
  2398. };
  2399. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2400. var matrix = Matrix.Zero();
  2401. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2402. return matrix;
  2403. };
  2404. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2405. //alternatively this could be expressed as:
  2406. // m = PerspectiveFovLHToRef
  2407. // m[10] *= -1.0;
  2408. // m[11] *= -1.0;
  2409. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2410. var n = znear;
  2411. var f = zfar;
  2412. var t = 1.0 / (Math.tan(fov * 0.5));
  2413. var a = isVerticalFovFixed ? (t / aspect) : t;
  2414. var b = isVerticalFovFixed ? t : (t * aspect);
  2415. var c = -(f + n) / (f - n);
  2416. var d = -2 * f * n / (f - n);
  2417. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, -1, 0, 0, d, 0, result);
  2418. };
  2419. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2420. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2421. //left handed
  2422. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2423. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2424. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2425. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2426. var xScale = 2.0 / (leftTan + rightTan);
  2427. var yScale = 2.0 / (upTan + downTan);
  2428. result.m[0] = xScale;
  2429. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2430. result.m[5] = yScale;
  2431. result.m[6] = result.m[7] = 0.0;
  2432. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2433. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2434. result.m[10] = -(znear + zfar) / (zfar - znear);
  2435. // result.m[10] = -zfar / (znear - zfar);
  2436. result.m[11] = 1.0;
  2437. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2438. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2439. // result.m[14] = (znear * zfar) / (znear - zfar);
  2440. };
  2441. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2442. var cw = viewport.width;
  2443. var ch = viewport.height;
  2444. var cx = viewport.x;
  2445. var cy = viewport.y;
  2446. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, zmax - zmin, 0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  2447. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2448. };
  2449. Matrix.GetAsMatrix2x2 = function (matrix) {
  2450. return new Float32Array([
  2451. matrix.m[0], matrix.m[1],
  2452. matrix.m[4], matrix.m[5]
  2453. ]);
  2454. };
  2455. Matrix.GetAsMatrix3x3 = function (matrix) {
  2456. return new Float32Array([
  2457. matrix.m[0], matrix.m[1], matrix.m[2],
  2458. matrix.m[4], matrix.m[5], matrix.m[6],
  2459. matrix.m[8], matrix.m[9], matrix.m[10]
  2460. ]);
  2461. };
  2462. Matrix.Transpose = function (matrix) {
  2463. var result = new Matrix();
  2464. result.m[0] = matrix.m[0];
  2465. result.m[1] = matrix.m[4];
  2466. result.m[2] = matrix.m[8];
  2467. result.m[3] = matrix.m[12];
  2468. result.m[4] = matrix.m[1];
  2469. result.m[5] = matrix.m[5];
  2470. result.m[6] = matrix.m[9];
  2471. result.m[7] = matrix.m[13];
  2472. result.m[8] = matrix.m[2];
  2473. result.m[9] = matrix.m[6];
  2474. result.m[10] = matrix.m[10];
  2475. result.m[11] = matrix.m[14];
  2476. result.m[12] = matrix.m[3];
  2477. result.m[13] = matrix.m[7];
  2478. result.m[14] = matrix.m[11];
  2479. result.m[15] = matrix.m[15];
  2480. return result;
  2481. };
  2482. Matrix.Reflection = function (plane) {
  2483. var matrix = new Matrix();
  2484. Matrix.ReflectionToRef(plane, matrix);
  2485. return matrix;
  2486. };
  2487. Matrix.ReflectionToRef = function (plane, result) {
  2488. plane.normalize();
  2489. var x = plane.normal.x;
  2490. var y = plane.normal.y;
  2491. var z = plane.normal.z;
  2492. var temp = -2 * x;
  2493. var temp2 = -2 * y;
  2494. var temp3 = -2 * z;
  2495. result.m[0] = (temp * x) + 1;
  2496. result.m[1] = temp2 * x;
  2497. result.m[2] = temp3 * x;
  2498. result.m[3] = 0.0;
  2499. result.m[4] = temp * y;
  2500. result.m[5] = (temp2 * y) + 1;
  2501. result.m[6] = temp3 * y;
  2502. result.m[7] = 0.0;
  2503. result.m[8] = temp * z;
  2504. result.m[9] = temp2 * z;
  2505. result.m[10] = (temp3 * z) + 1;
  2506. result.m[11] = 0.0;
  2507. result.m[12] = temp * plane.d;
  2508. result.m[13] = temp2 * plane.d;
  2509. result.m[14] = temp3 * plane.d;
  2510. result.m[15] = 1.0;
  2511. };
  2512. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  2513. mat.m[0] = xaxis.x;
  2514. mat.m[1] = xaxis.y;
  2515. mat.m[2] = xaxis.z;
  2516. mat.m[3] = 0;
  2517. mat.m[4] = yaxis.x;
  2518. mat.m[5] = yaxis.y;
  2519. mat.m[6] = yaxis.z;
  2520. mat.m[7] = 0;
  2521. mat.m[8] = zaxis.x;
  2522. mat.m[9] = zaxis.y;
  2523. mat.m[10] = zaxis.z;
  2524. mat.m[11] = 0;
  2525. mat.m[12] = 0;
  2526. mat.m[13] = 0;
  2527. mat.m[14] = 0;
  2528. mat.m[15] = 1;
  2529. };
  2530. Matrix.FromQuaternionToRef = function (quat, result) {
  2531. var xx = quat.x * quat.x;
  2532. var yy = quat.y * quat.y;
  2533. var zz = quat.z * quat.z;
  2534. var xy = quat.x * quat.y;
  2535. var zw = quat.z * quat.w;
  2536. var zx = quat.z * quat.x;
  2537. var yw = quat.y * quat.w;
  2538. var yz = quat.y * quat.z;
  2539. var xw = quat.x * quat.w;
  2540. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2541. result.m[1] = 2.0 * (xy + zw);
  2542. result.m[2] = 2.0 * (zx - yw);
  2543. result.m[3] = 0;
  2544. result.m[4] = 2.0 * (xy - zw);
  2545. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2546. result.m[6] = 2.0 * (yz + xw);
  2547. result.m[7] = 0;
  2548. result.m[8] = 2.0 * (zx + yw);
  2549. result.m[9] = 2.0 * (yz - xw);
  2550. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2551. result.m[11] = 0;
  2552. result.m[12] = 0;
  2553. result.m[13] = 0;
  2554. result.m[14] = 0;
  2555. result.m[15] = 1.0;
  2556. };
  2557. return Matrix;
  2558. }());
  2559. Matrix._tempQuaternion = new Quaternion();
  2560. Matrix._xAxis = Vector3.Zero();
  2561. Matrix._yAxis = Vector3.Zero();
  2562. Matrix._zAxis = Vector3.Zero();
  2563. BABYLON.Matrix = Matrix;
  2564. var Plane = (function () {
  2565. function Plane(a, b, c, d) {
  2566. this.normal = new Vector3(a, b, c);
  2567. this.d = d;
  2568. }
  2569. Plane.prototype.asArray = function () {
  2570. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2571. };
  2572. // Methods
  2573. Plane.prototype.clone = function () {
  2574. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2575. };
  2576. Plane.prototype.getClassName = function () {
  2577. return "Plane";
  2578. };
  2579. Plane.prototype.getHashCode = function () {
  2580. var hash = this.normal.getHashCode();
  2581. hash = (hash * 397) ^ (this.d || 0);
  2582. return hash;
  2583. };
  2584. Plane.prototype.normalize = function () {
  2585. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2586. var magnitude = 0;
  2587. if (norm !== 0) {
  2588. magnitude = 1.0 / norm;
  2589. }
  2590. this.normal.x *= magnitude;
  2591. this.normal.y *= magnitude;
  2592. this.normal.z *= magnitude;
  2593. this.d *= magnitude;
  2594. return this;
  2595. };
  2596. Plane.prototype.transform = function (transformation) {
  2597. var transposedMatrix = Matrix.Transpose(transformation);
  2598. var x = this.normal.x;
  2599. var y = this.normal.y;
  2600. var z = this.normal.z;
  2601. var d = this.d;
  2602. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2603. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2604. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2605. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2606. return new Plane(normalX, normalY, normalZ, finalD);
  2607. };
  2608. Plane.prototype.dotCoordinate = function (point) {
  2609. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2610. };
  2611. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2612. var x1 = point2.x - point1.x;
  2613. var y1 = point2.y - point1.y;
  2614. var z1 = point2.z - point1.z;
  2615. var x2 = point3.x - point1.x;
  2616. var y2 = point3.y - point1.y;
  2617. var z2 = point3.z - point1.z;
  2618. var yz = (y1 * z2) - (z1 * y2);
  2619. var xz = (z1 * x2) - (x1 * z2);
  2620. var xy = (x1 * y2) - (y1 * x2);
  2621. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2622. var invPyth;
  2623. if (pyth !== 0) {
  2624. invPyth = 1.0 / pyth;
  2625. }
  2626. else {
  2627. invPyth = 0;
  2628. }
  2629. this.normal.x = yz * invPyth;
  2630. this.normal.y = xz * invPyth;
  2631. this.normal.z = xy * invPyth;
  2632. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2633. return this;
  2634. };
  2635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2636. var dot = Vector3.Dot(this.normal, direction);
  2637. return (dot <= epsilon);
  2638. };
  2639. Plane.prototype.signedDistanceTo = function (point) {
  2640. return Vector3.Dot(point, this.normal) + this.d;
  2641. };
  2642. // Statics
  2643. Plane.FromArray = function (array) {
  2644. return new Plane(array[0], array[1], array[2], array[3]);
  2645. };
  2646. Plane.FromPoints = function (point1, point2, point3) {
  2647. var result = new Plane(0, 0, 0, 0);
  2648. result.copyFromPoints(point1, point2, point3);
  2649. return result;
  2650. };
  2651. Plane.FromPositionAndNormal = function (origin, normal) {
  2652. var result = new Plane(0, 0, 0, 0);
  2653. normal.normalize();
  2654. result.normal = normal;
  2655. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2656. return result;
  2657. };
  2658. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2659. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2660. return Vector3.Dot(point, normal) + d;
  2661. };
  2662. return Plane;
  2663. }());
  2664. BABYLON.Plane = Plane;
  2665. var Viewport = (function () {
  2666. function Viewport(x, y, width, height) {
  2667. this.x = x;
  2668. this.y = y;
  2669. this.width = width;
  2670. this.height = height;
  2671. }
  2672. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2673. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2674. };
  2675. return Viewport;
  2676. }());
  2677. BABYLON.Viewport = Viewport;
  2678. var Frustum = (function () {
  2679. function Frustum() {
  2680. }
  2681. Frustum.GetPlanes = function (transform) {
  2682. var frustumPlanes = [];
  2683. for (var index = 0; index < 6; index++) {
  2684. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2685. }
  2686. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2687. return frustumPlanes;
  2688. };
  2689. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2690. // Near
  2691. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2692. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2693. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2694. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2695. frustumPlanes[0].normalize();
  2696. // Far
  2697. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2698. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2699. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2700. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2701. frustumPlanes[1].normalize();
  2702. // Left
  2703. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2704. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2705. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2706. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2707. frustumPlanes[2].normalize();
  2708. // Right
  2709. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2710. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2711. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2712. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2713. frustumPlanes[3].normalize();
  2714. // Top
  2715. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2716. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2717. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2718. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2719. frustumPlanes[4].normalize();
  2720. // Bottom
  2721. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2722. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2723. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2724. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2725. frustumPlanes[5].normalize();
  2726. };
  2727. return Frustum;
  2728. }());
  2729. BABYLON.Frustum = Frustum;
  2730. var Space;
  2731. (function (Space) {
  2732. Space[Space["LOCAL"] = 0] = "LOCAL";
  2733. Space[Space["WORLD"] = 1] = "WORLD";
  2734. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  2735. var Axis = (function () {
  2736. function Axis() {
  2737. }
  2738. return Axis;
  2739. }());
  2740. Axis.X = new Vector3(1, 0, 0);
  2741. Axis.Y = new Vector3(0, 1, 0);
  2742. Axis.Z = new Vector3(0, 0, 1);
  2743. BABYLON.Axis = Axis;
  2744. ;
  2745. var BezierCurve = (function () {
  2746. function BezierCurve() {
  2747. }
  2748. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2749. // Extract X (which is equal to time here)
  2750. var f0 = 1 - 3 * x2 + 3 * x1;
  2751. var f1 = 3 * x2 - 6 * x1;
  2752. var f2 = 3 * x1;
  2753. var refinedT = t;
  2754. for (var i = 0; i < 5; i++) {
  2755. var refinedT2 = refinedT * refinedT;
  2756. var refinedT3 = refinedT2 * refinedT;
  2757. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2758. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2759. refinedT -= (x - t) * slope;
  2760. refinedT = Math.min(1, Math.max(0, refinedT));
  2761. }
  2762. // Resolve cubic bezier for the given x
  2763. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2764. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2765. Math.pow(refinedT, 3);
  2766. };
  2767. return BezierCurve;
  2768. }());
  2769. BABYLON.BezierCurve = BezierCurve;
  2770. var Orientation;
  2771. (function (Orientation) {
  2772. Orientation[Orientation["CW"] = 0] = "CW";
  2773. Orientation[Orientation["CCW"] = 1] = "CCW";
  2774. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  2775. var Angle = (function () {
  2776. function Angle(radians) {
  2777. var _this = this;
  2778. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2779. this.radians = function () { return _this._radians; };
  2780. this._radians = radians;
  2781. if (this._radians < 0)
  2782. this._radians += (2 * Math.PI);
  2783. }
  2784. Angle.BetweenTwoPoints = function (a, b) {
  2785. var delta = b.subtract(a);
  2786. var theta = Math.atan2(delta.y, delta.x);
  2787. return new Angle(theta);
  2788. };
  2789. Angle.FromRadians = function (radians) {
  2790. return new Angle(radians);
  2791. };
  2792. Angle.FromDegrees = function (degrees) {
  2793. return new Angle(degrees * Math.PI / 180);
  2794. };
  2795. return Angle;
  2796. }());
  2797. BABYLON.Angle = Angle;
  2798. var Arc2 = (function () {
  2799. function Arc2(startPoint, midPoint, endPoint) {
  2800. this.startPoint = startPoint;
  2801. this.midPoint = midPoint;
  2802. this.endPoint = endPoint;
  2803. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2804. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2805. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2806. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2807. this.centerPoint = new Vector2((startToMid * (midPoint.y - endPoint.y) - midToEnd * (startPoint.y - midPoint.y)) / det, ((startPoint.x - midPoint.x) * midToEnd - (midPoint.x - endPoint.x) * startToMid) / det);
  2808. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2809. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2810. var a1 = this.startAngle.degrees();
  2811. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2812. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2813. // angles correction
  2814. if (a2 - a1 > +180.0)
  2815. a2 -= 360.0;
  2816. if (a2 - a1 < -180.0)
  2817. a2 += 360.0;
  2818. if (a3 - a2 > +180.0)
  2819. a3 -= 360.0;
  2820. if (a3 - a2 < -180.0)
  2821. a3 += 360.0;
  2822. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2823. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2824. }
  2825. return Arc2;
  2826. }());
  2827. BABYLON.Arc2 = Arc2;
  2828. var Path2 = (function () {
  2829. function Path2(x, y) {
  2830. this._points = new Array();
  2831. this._length = 0;
  2832. this.closed = false;
  2833. this._points.push(new Vector2(x, y));
  2834. }
  2835. Path2.prototype.addLineTo = function (x, y) {
  2836. if (closed) {
  2837. //Tools.Error("cannot add lines to closed paths");
  2838. return this;
  2839. }
  2840. var newPoint = new Vector2(x, y);
  2841. var previousPoint = this._points[this._points.length - 1];
  2842. this._points.push(newPoint);
  2843. this._length += newPoint.subtract(previousPoint).length();
  2844. return this;
  2845. };
  2846. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2847. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2848. if (closed) {
  2849. //Tools.Error("cannot add arcs to closed paths");
  2850. return this;
  2851. }
  2852. var startPoint = this._points[this._points.length - 1];
  2853. var midPoint = new Vector2(midX, midY);
  2854. var endPoint = new Vector2(endX, endY);
  2855. var arc = new Arc2(startPoint, midPoint, endPoint);
  2856. var increment = arc.angle.radians() / numberOfSegments;
  2857. if (arc.orientation === Orientation.CW)
  2858. increment *= -1;
  2859. var currentAngle = arc.startAngle.radians() + increment;
  2860. for (var i = 0; i < numberOfSegments; i++) {
  2861. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2862. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2863. this.addLineTo(x, y);
  2864. currentAngle += increment;
  2865. }
  2866. return this;
  2867. };
  2868. Path2.prototype.close = function () {
  2869. this.closed = true;
  2870. return this;
  2871. };
  2872. Path2.prototype.length = function () {
  2873. var result = this._length;
  2874. if (!this.closed) {
  2875. var lastPoint = this._points[this._points.length - 1];
  2876. var firstPoint = this._points[0];
  2877. result += (firstPoint.subtract(lastPoint).length());
  2878. }
  2879. return result;
  2880. };
  2881. Path2.prototype.getPoints = function () {
  2882. return this._points;
  2883. };
  2884. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2885. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2886. //Tools.Error("normalized length position should be between 0 and 1.");
  2887. return Vector2.Zero();
  2888. }
  2889. var lengthPosition = normalizedLengthPosition * this.length();
  2890. var previousOffset = 0;
  2891. for (var i = 0; i < this._points.length; i++) {
  2892. var j = (i + 1) % this._points.length;
  2893. var a = this._points[i];
  2894. var b = this._points[j];
  2895. var bToA = b.subtract(a);
  2896. var nextOffset = (bToA.length() + previousOffset);
  2897. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2898. var dir = bToA.normalize();
  2899. var localOffset = lengthPosition - previousOffset;
  2900. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2901. }
  2902. previousOffset = nextOffset;
  2903. }
  2904. //Tools.Error("internal error");
  2905. return Vector2.Zero();
  2906. };
  2907. Path2.StartingAt = function (x, y) {
  2908. return new Path2(x, y);
  2909. };
  2910. return Path2;
  2911. }());
  2912. BABYLON.Path2 = Path2;
  2913. var Path3D = (function () {
  2914. /**
  2915. * new Path3D(path, normal, raw)
  2916. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2917. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2918. * path : an array of Vector3, the curve axis of the Path3D
  2919. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2920. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2921. */
  2922. function Path3D(path, firstNormal, raw) {
  2923. this.path = path;
  2924. this._curve = new Array();
  2925. this._distances = new Array();
  2926. this._tangents = new Array();
  2927. this._normals = new Array();
  2928. this._binormals = new Array();
  2929. for (var p = 0; p < path.length; p++) {
  2930. this._curve[p] = path[p].clone(); // hard copy
  2931. }
  2932. this._raw = raw || false;
  2933. this._compute(firstNormal);
  2934. }
  2935. /**
  2936. * Returns the Path3D array of successive Vector3 designing its curve.
  2937. */
  2938. Path3D.prototype.getCurve = function () {
  2939. return this._curve;
  2940. };
  2941. /**
  2942. * Returns an array populated with tangent vectors on each Path3D curve point.
  2943. */
  2944. Path3D.prototype.getTangents = function () {
  2945. return this._tangents;
  2946. };
  2947. /**
  2948. * Returns an array populated with normal vectors on each Path3D curve point.
  2949. */
  2950. Path3D.prototype.getNormals = function () {
  2951. return this._normals;
  2952. };
  2953. /**
  2954. * Returns an array populated with binormal vectors on each Path3D curve point.
  2955. */
  2956. Path3D.prototype.getBinormals = function () {
  2957. return this._binormals;
  2958. };
  2959. /**
  2960. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2961. */
  2962. Path3D.prototype.getDistances = function () {
  2963. return this._distances;
  2964. };
  2965. /**
  2966. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2967. * Returns the same object updated.
  2968. */
  2969. Path3D.prototype.update = function (path, firstNormal) {
  2970. for (var p = 0; p < path.length; p++) {
  2971. this._curve[p].x = path[p].x;
  2972. this._curve[p].y = path[p].y;
  2973. this._curve[p].z = path[p].z;
  2974. }
  2975. this._compute(firstNormal);
  2976. return this;
  2977. };
  2978. // private function compute() : computes tangents, normals and binormals
  2979. Path3D.prototype._compute = function (firstNormal) {
  2980. var l = this._curve.length;
  2981. // first and last tangents
  2982. this._tangents[0] = this._getFirstNonNullVector(0);
  2983. if (!this._raw) {
  2984. this._tangents[0].normalize();
  2985. }
  2986. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2987. if (!this._raw) {
  2988. this._tangents[l - 1].normalize();
  2989. }
  2990. // normals and binormals at first point : arbitrary vector with _normalVector()
  2991. var tg0 = this._tangents[0];
  2992. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2993. this._normals[0] = pp0;
  2994. if (!this._raw) {
  2995. this._normals[0].normalize();
  2996. }
  2997. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2998. if (!this._raw) {
  2999. this._binormals[0].normalize();
  3000. }
  3001. this._distances[0] = 0.0;
  3002. // normals and binormals : next points
  3003. var prev; // previous vector (segment)
  3004. var cur; // current vector (segment)
  3005. var curTang; // current tangent
  3006. // previous normal
  3007. var prevBinor; // previous binormal
  3008. for (var i = 1; i < l; i++) {
  3009. // tangents
  3010. prev = this._getLastNonNullVector(i);
  3011. if (i < l - 1) {
  3012. cur = this._getFirstNonNullVector(i);
  3013. this._tangents[i] = prev.add(cur);
  3014. this._tangents[i].normalize();
  3015. }
  3016. this._distances[i] = this._distances[i - 1] + prev.length();
  3017. // normals and binormals
  3018. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  3019. curTang = this._tangents[i];
  3020. prevBinor = this._binormals[i - 1];
  3021. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  3022. if (!this._raw) {
  3023. this._normals[i].normalize();
  3024. }
  3025. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  3026. if (!this._raw) {
  3027. this._binormals[i].normalize();
  3028. }
  3029. }
  3030. };
  3031. // private function getFirstNonNullVector(index)
  3032. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  3033. Path3D.prototype._getFirstNonNullVector = function (index) {
  3034. var i = 1;
  3035. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  3036. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  3037. i++;
  3038. nNVector = this._curve[index + i].subtract(this._curve[index]);
  3039. }
  3040. return nNVector;
  3041. };
  3042. // private function getLastNonNullVector(index)
  3043. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  3044. Path3D.prototype._getLastNonNullVector = function (index) {
  3045. var i = 1;
  3046. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  3047. while (nLVector.length() === 0 && index > i + 1) {
  3048. i++;
  3049. nLVector = this._curve[index].subtract(this._curve[index - i]);
  3050. }
  3051. return nLVector;
  3052. };
  3053. // private function normalVector(v0, vt, va) :
  3054. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  3055. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  3056. Path3D.prototype._normalVector = function (v0, vt, va) {
  3057. var normal0;
  3058. var tgl = vt.length();
  3059. if (tgl === 0.0) {
  3060. tgl = 1.0;
  3061. }
  3062. if (va === undefined || va === null) {
  3063. var point;
  3064. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3065. point = new Vector3(0.0, -1.0, 0.0);
  3066. }
  3067. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3068. point = new Vector3(1.0, 0.0, 0.0);
  3069. }
  3070. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3071. point = new Vector3(0.0, 0.0, 1.0);
  3072. }
  3073. normal0 = Vector3.Cross(vt, point);
  3074. }
  3075. else {
  3076. normal0 = Vector3.Cross(vt, va);
  3077. Vector3.CrossToRef(normal0, vt, normal0);
  3078. }
  3079. normal0.normalize();
  3080. return normal0;
  3081. };
  3082. return Path3D;
  3083. }());
  3084. BABYLON.Path3D = Path3D;
  3085. var Curve3 = (function () {
  3086. /**
  3087. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3088. * A Curve3 is designed from a series of successive Vector3.
  3089. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3090. */
  3091. function Curve3(points) {
  3092. this._length = 0.0;
  3093. this._points = points;
  3094. this._length = this._computeLength(points);
  3095. }
  3096. /**
  3097. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3098. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3099. * @param v1 (Vector3) the control point
  3100. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3101. * @param nbPoints (integer) the wanted number of points in the curve
  3102. */
  3103. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3104. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3105. var bez = new Array();
  3106. var equation = function (t, val0, val1, val2) {
  3107. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3108. return res;
  3109. };
  3110. for (var i = 0; i <= nbPoints; i++) {
  3111. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x), equation(i / nbPoints, v0.y, v1.y, v2.y), equation(i / nbPoints, v0.z, v1.z, v2.z)));
  3112. }
  3113. return new Curve3(bez);
  3114. };
  3115. /**
  3116. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3117. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3118. * @param v1 (Vector3) the first control point
  3119. * @param v2 (Vector3) the second control point
  3120. * @param v3 (Vector3) the end point of the Cubic Bezier
  3121. * @param nbPoints (integer) the wanted number of points in the curve
  3122. */
  3123. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3124. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3125. var bez = new Array();
  3126. var equation = function (t, val0, val1, val2, val3) {
  3127. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  3128. return res;
  3129. };
  3130. for (var i = 0; i <= nbPoints; i++) {
  3131. bez.push(new Vector3(equation(i / nbPoints, v0.x, v1.x, v2.x, v3.x), equation(i / nbPoints, v0.y, v1.y, v2.y, v3.y), equation(i / nbPoints, v0.z, v1.z, v2.z, v3.z)));
  3132. }
  3133. return new Curve3(bez);
  3134. };
  3135. /**
  3136. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3137. * @param p1 (Vector3) the origin point of the Hermite Spline
  3138. * @param t1 (Vector3) the tangent vector at the origin point
  3139. * @param p2 (Vector3) the end point of the Hermite Spline
  3140. * @param t2 (Vector3) the tangent vector at the end point
  3141. * @param nbPoints (integer) the wanted number of points in the curve
  3142. */
  3143. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3144. var hermite = new Array();
  3145. var step = 1.0 / nbPoints;
  3146. for (var i = 0; i <= nbPoints; i++) {
  3147. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3148. }
  3149. return new Curve3(hermite);
  3150. };
  3151. /**
  3152. * Returns the Curve3 stored array of successive Vector3
  3153. */
  3154. Curve3.prototype.getPoints = function () {
  3155. return this._points;
  3156. };
  3157. /**
  3158. * Returns the computed length (float) of the curve.
  3159. */
  3160. Curve3.prototype.length = function () {
  3161. return this._length;
  3162. };
  3163. /**
  3164. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3165. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3166. * curveA and curveB keep unchanged.
  3167. */
  3168. Curve3.prototype.continue = function (curve) {
  3169. var lastPoint = this._points[this._points.length - 1];
  3170. var continuedPoints = this._points.slice();
  3171. var curvePoints = curve.getPoints();
  3172. for (var i = 1; i < curvePoints.length; i++) {
  3173. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3174. }
  3175. var continuedCurve = new Curve3(continuedPoints);
  3176. return continuedCurve;
  3177. };
  3178. Curve3.prototype._computeLength = function (path) {
  3179. var l = 0;
  3180. for (var i = 1; i < path.length; i++) {
  3181. l += (path[i].subtract(path[i - 1])).length();
  3182. }
  3183. return l;
  3184. };
  3185. return Curve3;
  3186. }());
  3187. BABYLON.Curve3 = Curve3;
  3188. // SphericalHarmonics
  3189. var SphericalHarmonics = (function () {
  3190. function SphericalHarmonics() {
  3191. this.L00 = Vector3.Zero();
  3192. this.L1_1 = Vector3.Zero();
  3193. this.L10 = Vector3.Zero();
  3194. this.L11 = Vector3.Zero();
  3195. this.L2_2 = Vector3.Zero();
  3196. this.L2_1 = Vector3.Zero();
  3197. this.L20 = Vector3.Zero();
  3198. this.L21 = Vector3.Zero();
  3199. this.L22 = Vector3.Zero();
  3200. }
  3201. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3202. var colorVector = new Vector3(color.r, color.g, color.b);
  3203. var c = colorVector.scale(deltaSolidAngle);
  3204. this.L00 = this.L00.add(c.scale(0.282095));
  3205. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3206. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3207. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3208. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3209. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3210. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3211. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3212. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3213. };
  3214. SphericalHarmonics.prototype.scale = function (scale) {
  3215. this.L00 = this.L00.scale(scale);
  3216. this.L1_1 = this.L1_1.scale(scale);
  3217. this.L10 = this.L10.scale(scale);
  3218. this.L11 = this.L11.scale(scale);
  3219. this.L2_2 = this.L2_2.scale(scale);
  3220. this.L2_1 = this.L2_1.scale(scale);
  3221. this.L20 = this.L20.scale(scale);
  3222. this.L21 = this.L21.scale(scale);
  3223. this.L22 = this.L22.scale(scale);
  3224. };
  3225. return SphericalHarmonics;
  3226. }());
  3227. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3228. // SphericalPolynomial
  3229. var SphericalPolynomial = (function () {
  3230. function SphericalPolynomial() {
  3231. this.x = Vector3.Zero();
  3232. this.y = Vector3.Zero();
  3233. this.z = Vector3.Zero();
  3234. this.xx = Vector3.Zero();
  3235. this.yy = Vector3.Zero();
  3236. this.zz = Vector3.Zero();
  3237. this.xy = Vector3.Zero();
  3238. this.yz = Vector3.Zero();
  3239. this.zx = Vector3.Zero();
  3240. }
  3241. SphericalPolynomial.prototype.addAmbient = function (color) {
  3242. var colorVector = new Vector3(color.r, color.g, color.b);
  3243. this.xx = this.xx.add(colorVector);
  3244. this.yy = this.yy.add(colorVector);
  3245. this.zz = this.zz.add(colorVector);
  3246. };
  3247. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3248. var result = new SphericalPolynomial();
  3249. result.x = harmonics.L11.scale(1.02333);
  3250. result.y = harmonics.L1_1.scale(1.02333);
  3251. result.z = harmonics.L10.scale(1.02333);
  3252. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3253. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3254. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3255. result.yz = harmonics.L2_1.scale(0.858086);
  3256. result.zx = harmonics.L21.scale(0.858086);
  3257. result.xy = harmonics.L2_2.scale(0.858086);
  3258. return result;
  3259. };
  3260. return SphericalPolynomial;
  3261. }());
  3262. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3263. // Vertex formats
  3264. var PositionNormalVertex = (function () {
  3265. function PositionNormalVertex(position, normal) {
  3266. if (position === void 0) { position = Vector3.Zero(); }
  3267. if (normal === void 0) { normal = Vector3.Up(); }
  3268. this.position = position;
  3269. this.normal = normal;
  3270. }
  3271. PositionNormalVertex.prototype.clone = function () {
  3272. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3273. };
  3274. return PositionNormalVertex;
  3275. }());
  3276. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3277. var PositionNormalTextureVertex = (function () {
  3278. function PositionNormalTextureVertex(position, normal, uv) {
  3279. if (position === void 0) { position = Vector3.Zero(); }
  3280. if (normal === void 0) { normal = Vector3.Up(); }
  3281. if (uv === void 0) { uv = Vector2.Zero(); }
  3282. this.position = position;
  3283. this.normal = normal;
  3284. this.uv = uv;
  3285. }
  3286. PositionNormalTextureVertex.prototype.clone = function () {
  3287. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3288. };
  3289. return PositionNormalTextureVertex;
  3290. }());
  3291. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3292. // Temporary pre-allocated objects for engine internal use
  3293. // usage in any internal function :
  3294. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3295. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3296. var Tmp = (function () {
  3297. function Tmp() {
  3298. }
  3299. return Tmp;
  3300. }());
  3301. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3302. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3303. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3304. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3305. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3306. Tmp.Quaternion = [new Quaternion(0.0, 0.0, 0.0, 0.0),
  3307. new Quaternion(0.0, 0.0, 0.0, 0.0)]; // 2 temp Quaternion at once should be enough
  3308. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3309. Matrix.Zero(), Matrix.Zero(),
  3310. Matrix.Zero(), Matrix.Zero(),
  3311. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3312. BABYLON.Tmp = Tmp;
  3313. })(BABYLON || (BABYLON = {}));
  3314. //# sourceMappingURL=babylon.math.js.map
  3315. //# sourceMappingURL=babylon.mixins.js.map
  3316. var BABYLON;
  3317. (function (BABYLON) {
  3318. function generateSerializableMember(type, sourceName) {
  3319. return function (target, propertyKey) {
  3320. if (!target.__serializableMembers) {
  3321. target.__serializableMembers = {};
  3322. }
  3323. if (!target.__serializableMembers[propertyKey]) {
  3324. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3325. }
  3326. };
  3327. }
  3328. function serialize(sourceName) {
  3329. return generateSerializableMember(0, sourceName); // value member
  3330. }
  3331. BABYLON.serialize = serialize;
  3332. function serializeAsTexture(sourceName) {
  3333. return generateSerializableMember(1, sourceName); // texture member
  3334. }
  3335. BABYLON.serializeAsTexture = serializeAsTexture;
  3336. function serializeAsColor3(sourceName) {
  3337. return generateSerializableMember(2, sourceName); // color3 member
  3338. }
  3339. BABYLON.serializeAsColor3 = serializeAsColor3;
  3340. function serializeAsFresnelParameters(sourceName) {
  3341. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3342. }
  3343. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3344. function serializeAsVector2(sourceName) {
  3345. return generateSerializableMember(4, sourceName); // vector2 member
  3346. }
  3347. BABYLON.serializeAsVector2 = serializeAsVector2;
  3348. function serializeAsVector3(sourceName) {
  3349. return generateSerializableMember(5, sourceName); // vector3 member
  3350. }
  3351. BABYLON.serializeAsVector3 = serializeAsVector3;
  3352. function serializeAsMeshReference(sourceName) {
  3353. return generateSerializableMember(6, sourceName); // mesh reference member
  3354. }
  3355. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3356. function serializeAsColorCurves(sourceName) {
  3357. return generateSerializableMember(7, sourceName); // color curves
  3358. }
  3359. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3360. var SerializationHelper = (function () {
  3361. function SerializationHelper() {
  3362. }
  3363. SerializationHelper.Serialize = function (entity, serializationObject) {
  3364. if (!serializationObject) {
  3365. serializationObject = {};
  3366. }
  3367. // Tags
  3368. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3369. // Properties
  3370. for (var property in entity.__serializableMembers) {
  3371. var propertyDescriptor = entity.__serializableMembers[property];
  3372. var targetPropertyName = propertyDescriptor.sourceName || property;
  3373. var propertyType = propertyDescriptor.type;
  3374. var sourceProperty = entity[property];
  3375. if (sourceProperty !== undefined && sourceProperty !== null) {
  3376. switch (propertyType) {
  3377. case 0:
  3378. serializationObject[targetPropertyName] = sourceProperty;
  3379. break;
  3380. case 1:
  3381. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3382. break;
  3383. case 2:
  3384. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3385. break;
  3386. case 3:
  3387. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3388. break;
  3389. case 4:
  3390. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3391. break;
  3392. case 5:
  3393. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3394. break;
  3395. case 6:
  3396. serializationObject[targetPropertyName] = sourceProperty.id;
  3397. break;
  3398. case 7:
  3399. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3400. break;
  3401. }
  3402. }
  3403. }
  3404. return serializationObject;
  3405. };
  3406. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3407. var destination = creationFunction();
  3408. // Tags
  3409. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3410. // Properties
  3411. for (var property in destination.__serializableMembers) {
  3412. var propertyDescriptor = destination.__serializableMembers[property];
  3413. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3414. var propertyType = propertyDescriptor.type;
  3415. if (sourceProperty !== undefined && sourceProperty !== null) {
  3416. switch (propertyType) {
  3417. case 0:
  3418. destination[property] = sourceProperty;
  3419. break;
  3420. case 1:
  3421. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3422. break;
  3423. case 2:
  3424. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3425. break;
  3426. case 3:
  3427. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3428. break;
  3429. case 4:
  3430. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3431. break;
  3432. case 5:
  3433. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3434. break;
  3435. case 6:
  3436. destination[property] = scene.getLastMeshByID(sourceProperty);
  3437. break;
  3438. case 7:
  3439. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3440. break;
  3441. }
  3442. }
  3443. }
  3444. return destination;
  3445. };
  3446. SerializationHelper.Clone = function (creationFunction, source) {
  3447. var destination = creationFunction();
  3448. // Tags
  3449. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3450. // Properties
  3451. for (var property in destination.__serializableMembers) {
  3452. var propertyDescriptor = destination.__serializableMembers[property];
  3453. var sourceProperty = source[property];
  3454. var propertyType = propertyDescriptor.type;
  3455. if (sourceProperty !== undefined && sourceProperty !== null) {
  3456. switch (propertyType) {
  3457. case 0: // Value
  3458. case 6:
  3459. destination[property] = sourceProperty;
  3460. break;
  3461. case 1: // Texture
  3462. case 2: // Color3
  3463. case 3: // FresnelParameters
  3464. case 4: // Vector2
  3465. case 5: // Vector3
  3466. case 7:
  3467. destination[property] = sourceProperty.clone();
  3468. break;
  3469. }
  3470. }
  3471. }
  3472. return destination;
  3473. };
  3474. return SerializationHelper;
  3475. }());
  3476. BABYLON.SerializationHelper = SerializationHelper;
  3477. })(BABYLON || (BABYLON = {}));
  3478. //# sourceMappingURL=babylon.decorators.js.map
  3479. var BABYLON;
  3480. (function (BABYLON) {
  3481. /**
  3482. * A class serves as a medium between the observable and its observers
  3483. */
  3484. var EventState = (function () {
  3485. /**
  3486. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3487. */
  3488. function EventState(mask, skipNextObservers) {
  3489. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3490. this.initalize(mask, skipNextObservers);
  3491. }
  3492. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3493. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3494. this.mask = mask;
  3495. this.skipNextObservers = skipNextObservers;
  3496. return this;
  3497. };
  3498. return EventState;
  3499. }());
  3500. BABYLON.EventState = EventState;
  3501. /**
  3502. * Represent an Observer registered to a given Observable object.
  3503. */
  3504. var Observer = (function () {
  3505. function Observer(callback, mask) {
  3506. this.callback = callback;
  3507. this.mask = mask;
  3508. }
  3509. return Observer;
  3510. }());
  3511. BABYLON.Observer = Observer;
  3512. /**
  3513. * The Observable class is a simple implementation of the Observable pattern.
  3514. * 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.
  3515. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3516. * 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).
  3517. * 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.
  3518. */
  3519. var Observable = (function () {
  3520. function Observable() {
  3521. this._observers = new Array();
  3522. this._eventState = new EventState(0);
  3523. }
  3524. /**
  3525. * Create a new Observer with the specified callback
  3526. * @param callback the callback that will be executed for that Observer
  3527. * @param mask the mask used to filter observers
  3528. * @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.
  3529. */
  3530. Observable.prototype.add = function (callback, mask, insertFirst) {
  3531. if (mask === void 0) { mask = -1; }
  3532. if (insertFirst === void 0) { insertFirst = false; }
  3533. if (!callback) {
  3534. return null;
  3535. }
  3536. var observer = new Observer(callback, mask);
  3537. if (insertFirst) {
  3538. this._observers.unshift(observer);
  3539. }
  3540. else {
  3541. this._observers.push(observer);
  3542. }
  3543. return observer;
  3544. };
  3545. /**
  3546. * Remove an Observer from the Observable object
  3547. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3548. */
  3549. Observable.prototype.remove = function (observer) {
  3550. var index = this._observers.indexOf(observer);
  3551. if (index !== -1) {
  3552. this._observers.splice(index, 1);
  3553. return true;
  3554. }
  3555. return false;
  3556. };
  3557. /**
  3558. * Remove a callback from the Observable object
  3559. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3560. */
  3561. Observable.prototype.removeCallback = function (callback) {
  3562. for (var index = 0; index < this._observers.length; index++) {
  3563. if (this._observers[index].callback === callback) {
  3564. this._observers.splice(index, 1);
  3565. return true;
  3566. }
  3567. }
  3568. return false;
  3569. };
  3570. /**
  3571. * Notify all Observers by calling their respective callback with the given data
  3572. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3573. * @param eventData
  3574. * @param mask
  3575. */
  3576. Observable.prototype.notifyObservers = function (eventData, mask) {
  3577. if (mask === void 0) { mask = -1; }
  3578. var state = this._eventState;
  3579. state.mask = mask;
  3580. state.skipNextObservers = false;
  3581. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3582. var obs = _a[_i];
  3583. if (obs.mask & mask) {
  3584. obs.callback(eventData, state);
  3585. }
  3586. if (state.skipNextObservers) {
  3587. return false;
  3588. }
  3589. }
  3590. return true;
  3591. };
  3592. /**
  3593. * return true is the Observable has at least one Observer registered
  3594. */
  3595. Observable.prototype.hasObservers = function () {
  3596. return this._observers.length > 0;
  3597. };
  3598. /**
  3599. * Clear the list of observers
  3600. */
  3601. Observable.prototype.clear = function () {
  3602. this._observers = new Array();
  3603. };
  3604. /**
  3605. * Clone the current observable
  3606. */
  3607. Observable.prototype.clone = function () {
  3608. var result = new Observable();
  3609. result._observers = this._observers.slice(0);
  3610. return result;
  3611. };
  3612. return Observable;
  3613. }());
  3614. BABYLON.Observable = Observable;
  3615. })(BABYLON || (BABYLON = {}));
  3616. //# sourceMappingURL=babylon.observable.js.map
  3617. var BABYLON;
  3618. (function (BABYLON) {
  3619. var Database = (function () {
  3620. function Database(urlToScene, callbackManifestChecked) {
  3621. // Handling various flavors of prefixed version of IndexedDB
  3622. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3623. this.callbackManifestChecked = callbackManifestChecked;
  3624. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3625. this.db = null;
  3626. this.enableSceneOffline = false;
  3627. this.enableTexturesOffline = false;
  3628. this.manifestVersionFound = 0;
  3629. this.mustUpdateRessources = false;
  3630. this.hasReachedQuota = false;
  3631. if (!Database.IDBStorageEnabled) {
  3632. this.callbackManifestChecked(true);
  3633. }
  3634. else {
  3635. this.checkManifestFile();
  3636. }
  3637. }
  3638. Database.prototype.checkManifestFile = function () {
  3639. var _this = this;
  3640. function noManifestFile() {
  3641. that.enableSceneOffline = false;
  3642. that.enableTexturesOffline = false;
  3643. that.callbackManifestChecked(false);
  3644. }
  3645. var that = this;
  3646. var timeStampUsed = false;
  3647. var manifestURL = this.currentSceneUrl + ".manifest";
  3648. var xhr = new XMLHttpRequest();
  3649. if (navigator.onLine) {
  3650. // Adding a timestamp to by-pass browsers' cache
  3651. timeStampUsed = true;
  3652. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3653. }
  3654. xhr.open("GET", manifestURL, true);
  3655. xhr.addEventListener("load", function () {
  3656. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3657. try {
  3658. var manifestFile = JSON.parse(xhr.response);
  3659. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3660. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3661. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3662. _this.manifestVersionFound = manifestFile.version;
  3663. }
  3664. if (_this.callbackManifestChecked) {
  3665. _this.callbackManifestChecked(true);
  3666. }
  3667. }
  3668. catch (ex) {
  3669. noManifestFile();
  3670. }
  3671. }
  3672. else {
  3673. noManifestFile();
  3674. }
  3675. }, false);
  3676. xhr.addEventListener("error", function (event) {
  3677. if (timeStampUsed) {
  3678. timeStampUsed = false;
  3679. // Let's retry without the timeStamp
  3680. // It could fail when coupled with HTML5 Offline API
  3681. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3682. xhr.open("GET", retryManifestURL, true);
  3683. xhr.send();
  3684. }
  3685. else {
  3686. noManifestFile();
  3687. }
  3688. }, false);
  3689. try {
  3690. xhr.send();
  3691. }
  3692. catch (ex) {
  3693. BABYLON.Tools.Error("Error on XHR send request.");
  3694. that.callbackManifestChecked(false);
  3695. }
  3696. };
  3697. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3698. var _this = this;
  3699. function handleError() {
  3700. that.isSupported = false;
  3701. if (errorCallback)
  3702. errorCallback();
  3703. }
  3704. var that = this;
  3705. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3706. // Your browser doesn't support IndexedDB
  3707. this.isSupported = false;
  3708. if (errorCallback)
  3709. errorCallback();
  3710. }
  3711. else {
  3712. // If the DB hasn't been opened or created yet
  3713. if (!this.db) {
  3714. this.hasReachedQuota = false;
  3715. this.isSupported = true;
  3716. var request = this.idbFactory.open("babylonjs", 1);
  3717. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3718. request.onerror = function (event) {
  3719. handleError();
  3720. };
  3721. // executes when a version change transaction cannot complete due to other active transactions
  3722. request.onblocked = function (event) {
  3723. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3724. handleError();
  3725. };
  3726. // DB has been opened successfully
  3727. request.onsuccess = function (event) {
  3728. _this.db = request.result;
  3729. successCallback();
  3730. };
  3731. // Initialization of the DB. Creating Scenes & Textures stores
  3732. request.onupgradeneeded = function (event) {
  3733. _this.db = (event.target).result;
  3734. try {
  3735. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3736. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3737. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3738. }
  3739. catch (ex) {
  3740. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3741. handleError();
  3742. }
  3743. };
  3744. }
  3745. else {
  3746. if (successCallback)
  3747. successCallback();
  3748. }
  3749. }
  3750. };
  3751. Database.prototype.loadImageFromDB = function (url, image) {
  3752. var _this = this;
  3753. var completeURL = Database.ReturnFullUrlLocation(url);
  3754. var saveAndLoadImage = function () {
  3755. if (!_this.hasReachedQuota && _this.db !== null) {
  3756. // the texture is not yet in the DB, let's try to save it
  3757. _this._saveImageIntoDBAsync(completeURL, image);
  3758. }
  3759. else {
  3760. image.src = url;
  3761. }
  3762. };
  3763. if (!this.mustUpdateRessources) {
  3764. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3765. }
  3766. else {
  3767. saveAndLoadImage();
  3768. }
  3769. };
  3770. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3771. if (this.isSupported && this.db !== null) {
  3772. var texture;
  3773. var transaction = this.db.transaction(["textures"]);
  3774. transaction.onabort = function (event) {
  3775. image.src = url;
  3776. };
  3777. transaction.oncomplete = function (event) {
  3778. var blobTextureURL;
  3779. if (texture) {
  3780. var URL = window.URL || window.webkitURL;
  3781. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3782. image.onerror = function () {
  3783. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3784. image.src = url;
  3785. };
  3786. image.src = blobTextureURL;
  3787. }
  3788. else {
  3789. notInDBCallback();
  3790. }
  3791. };
  3792. var getRequest = transaction.objectStore("textures").get(url);
  3793. getRequest.onsuccess = function (event) {
  3794. texture = (event.target).result;
  3795. };
  3796. getRequest.onerror = function (event) {
  3797. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3798. image.src = url;
  3799. };
  3800. }
  3801. else {
  3802. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3803. image.src = url;
  3804. }
  3805. };
  3806. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3807. var _this = this;
  3808. if (this.isSupported) {
  3809. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3810. var generateBlobUrl = function () {
  3811. var blobTextureURL;
  3812. if (blob) {
  3813. var URL = window.URL || window.webkitURL;
  3814. try {
  3815. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3816. }
  3817. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3818. catch (ex) {
  3819. blobTextureURL = URL.createObjectURL(blob);
  3820. }
  3821. }
  3822. image.src = blobTextureURL;
  3823. };
  3824. if (Database.IsUASupportingBlobStorage) {
  3825. var xhr = new XMLHttpRequest(), blob;
  3826. xhr.open("GET", url, true);
  3827. xhr.responseType = "blob";
  3828. xhr.addEventListener("load", function () {
  3829. if (xhr.status === 200) {
  3830. // Blob as response (XHR2)
  3831. blob = xhr.response;
  3832. var transaction = _this.db.transaction(["textures"], "readwrite");
  3833. // the transaction could abort because of a QuotaExceededError error
  3834. transaction.onabort = function (event) {
  3835. try {
  3836. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3837. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3838. _this.hasReachedQuota = true;
  3839. }
  3840. }
  3841. catch (ex) { }
  3842. generateBlobUrl();
  3843. };
  3844. transaction.oncomplete = function (event) {
  3845. generateBlobUrl();
  3846. };
  3847. var newTexture = { textureUrl: url, data: blob };
  3848. try {
  3849. // Put the blob into the dabase
  3850. var addRequest = transaction.objectStore("textures").put(newTexture);
  3851. addRequest.onsuccess = function (event) {
  3852. };
  3853. addRequest.onerror = function (event) {
  3854. generateBlobUrl();
  3855. };
  3856. }
  3857. catch (ex) {
  3858. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3859. if (ex.code === 25) {
  3860. Database.IsUASupportingBlobStorage = false;
  3861. }
  3862. image.src = url;
  3863. }
  3864. }
  3865. else {
  3866. image.src = url;
  3867. }
  3868. }, false);
  3869. xhr.addEventListener("error", function (event) {
  3870. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3871. image.src = url;
  3872. }, false);
  3873. xhr.send();
  3874. }
  3875. else {
  3876. image.src = url;
  3877. }
  3878. }
  3879. else {
  3880. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3881. image.src = url;
  3882. }
  3883. };
  3884. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3885. var _this = this;
  3886. var updateVersion = function (event) {
  3887. // the version is not yet in the DB or we need to update it
  3888. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3889. };
  3890. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3891. };
  3892. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3893. var _this = this;
  3894. if (this.isSupported) {
  3895. var version;
  3896. try {
  3897. var transaction = this.db.transaction(["versions"]);
  3898. transaction.oncomplete = function (event) {
  3899. if (version) {
  3900. // If the version in the JSON file is > than the version in DB
  3901. if (_this.manifestVersionFound > version.data) {
  3902. _this.mustUpdateRessources = true;
  3903. updateInDBCallback();
  3904. }
  3905. else {
  3906. callback(version.data);
  3907. }
  3908. }
  3909. else {
  3910. _this.mustUpdateRessources = true;
  3911. updateInDBCallback();
  3912. }
  3913. };
  3914. transaction.onabort = function (event) {
  3915. callback(-1);
  3916. };
  3917. var getRequest = transaction.objectStore("versions").get(url);
  3918. getRequest.onsuccess = function (event) {
  3919. version = (event.target).result;
  3920. };
  3921. getRequest.onerror = function (event) {
  3922. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3923. callback(-1);
  3924. };
  3925. }
  3926. catch (ex) {
  3927. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3928. callback(-1);
  3929. }
  3930. }
  3931. else {
  3932. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3933. callback(-1);
  3934. }
  3935. };
  3936. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3937. var _this = this;
  3938. if (this.isSupported && !this.hasReachedQuota) {
  3939. try {
  3940. // Open a transaction to the database
  3941. var transaction = this.db.transaction(["versions"], "readwrite");
  3942. // the transaction could abort because of a QuotaExceededError error
  3943. transaction.onabort = function (event) {
  3944. try {
  3945. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3946. _this.hasReachedQuota = true;
  3947. }
  3948. }
  3949. catch (ex) { }
  3950. callback(-1);
  3951. };
  3952. transaction.oncomplete = function (event) {
  3953. callback(_this.manifestVersionFound);
  3954. };
  3955. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3956. // Put the scene into the database
  3957. var addRequest = transaction.objectStore("versions").put(newVersion);
  3958. addRequest.onsuccess = function (event) {
  3959. };
  3960. addRequest.onerror = function (event) {
  3961. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3962. };
  3963. }
  3964. catch (ex) {
  3965. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3966. callback(-1);
  3967. }
  3968. }
  3969. else {
  3970. callback(-1);
  3971. }
  3972. };
  3973. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3974. var _this = this;
  3975. var completeUrl = Database.ReturnFullUrlLocation(url);
  3976. var saveAndLoadFile = function (event) {
  3977. // the scene is not yet in the DB, let's try to save it
  3978. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3979. };
  3980. this._checkVersionFromDB(completeUrl, function (version) {
  3981. if (version !== -1) {
  3982. if (!_this.mustUpdateRessources) {
  3983. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3984. }
  3985. else {
  3986. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3987. }
  3988. }
  3989. else {
  3990. errorCallback();
  3991. }
  3992. });
  3993. };
  3994. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3995. if (this.isSupported) {
  3996. var targetStore;
  3997. if (url.indexOf(".babylon") !== -1) {
  3998. targetStore = "scenes";
  3999. }
  4000. else {
  4001. targetStore = "textures";
  4002. }
  4003. var file;
  4004. var transaction = this.db.transaction([targetStore]);
  4005. transaction.oncomplete = function (event) {
  4006. if (file) {
  4007. callback(file.data);
  4008. }
  4009. else {
  4010. notInDBCallback();
  4011. }
  4012. };
  4013. transaction.onabort = function (event) {
  4014. notInDBCallback();
  4015. };
  4016. var getRequest = transaction.objectStore(targetStore).get(url);
  4017. getRequest.onsuccess = function (event) {
  4018. file = (event.target).result;
  4019. };
  4020. getRequest.onerror = function (event) {
  4021. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  4022. notInDBCallback();
  4023. };
  4024. }
  4025. else {
  4026. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4027. callback();
  4028. }
  4029. };
  4030. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  4031. var _this = this;
  4032. if (this.isSupported) {
  4033. var targetStore;
  4034. if (url.indexOf(".babylon") !== -1) {
  4035. targetStore = "scenes";
  4036. }
  4037. else {
  4038. targetStore = "textures";
  4039. }
  4040. // Create XHR
  4041. var xhr = new XMLHttpRequest(), fileData;
  4042. xhr.open("GET", url, true);
  4043. if (useArrayBuffer) {
  4044. xhr.responseType = "arraybuffer";
  4045. }
  4046. xhr.onprogress = progressCallback;
  4047. xhr.addEventListener("load", function () {
  4048. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  4049. // Blob as response (XHR2)
  4050. //fileData = xhr.responseText;
  4051. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  4052. if (!_this.hasReachedQuota) {
  4053. // Open a transaction to the database
  4054. var transaction = _this.db.transaction([targetStore], "readwrite");
  4055. // the transaction could abort because of a QuotaExceededError error
  4056. transaction.onabort = function (event) {
  4057. try {
  4058. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  4059. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  4060. _this.hasReachedQuota = true;
  4061. }
  4062. }
  4063. catch (ex) { }
  4064. callback(fileData);
  4065. };
  4066. transaction.oncomplete = function (event) {
  4067. callback(fileData);
  4068. };
  4069. var newFile;
  4070. if (targetStore === "scenes") {
  4071. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4072. }
  4073. else {
  4074. newFile = { textureUrl: url, data: fileData };
  4075. }
  4076. try {
  4077. // Put the scene into the database
  4078. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4079. addRequest.onsuccess = function (event) {
  4080. };
  4081. addRequest.onerror = function (event) {
  4082. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4083. };
  4084. }
  4085. catch (ex) {
  4086. callback(fileData);
  4087. }
  4088. }
  4089. else {
  4090. callback(fileData);
  4091. }
  4092. }
  4093. else {
  4094. callback();
  4095. }
  4096. }, false);
  4097. xhr.addEventListener("error", function (event) {
  4098. BABYLON.Tools.Error("error on XHR request.");
  4099. callback();
  4100. }, false);
  4101. xhr.send();
  4102. }
  4103. else {
  4104. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4105. callback();
  4106. }
  4107. };
  4108. return Database;
  4109. }());
  4110. Database.IsUASupportingBlobStorage = true;
  4111. Database.IDBStorageEnabled = true;
  4112. Database.parseURL = function (url) {
  4113. var a = document.createElement('a');
  4114. a.href = url;
  4115. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4116. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4117. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4118. return absLocation;
  4119. };
  4120. Database.ReturnFullUrlLocation = function (url) {
  4121. if (url.indexOf("http:/") === -1) {
  4122. return (Database.parseURL(window.location.href) + url);
  4123. }
  4124. else {
  4125. return url;
  4126. }
  4127. };
  4128. BABYLON.Database = Database;
  4129. })(BABYLON || (BABYLON = {}));
  4130. //# sourceMappingURL=babylon.database.js.map
  4131. var BABYLON;
  4132. (function (BABYLON) {
  4133. var Internals;
  4134. (function (Internals) {
  4135. /*
  4136. * Based on jsTGALoader - Javascript loader for TGA file
  4137. * By Vincent Thibault
  4138. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4139. */
  4140. var TGATools = (function () {
  4141. function TGATools() {
  4142. }
  4143. TGATools.GetTGAHeader = function (data) {
  4144. var offset = 0;
  4145. var header = {
  4146. id_length: data[offset++],
  4147. colormap_type: data[offset++],
  4148. image_type: data[offset++],
  4149. colormap_index: data[offset++] | data[offset++] << 8,
  4150. colormap_length: data[offset++] | data[offset++] << 8,
  4151. colormap_size: data[offset++],
  4152. origin: [
  4153. data[offset++] | data[offset++] << 8,
  4154. data[offset++] | data[offset++] << 8
  4155. ],
  4156. width: data[offset++] | data[offset++] << 8,
  4157. height: data[offset++] | data[offset++] << 8,
  4158. pixel_size: data[offset++],
  4159. flags: data[offset++]
  4160. };
  4161. return header;
  4162. };
  4163. TGATools.UploadContent = function (gl, data) {
  4164. // Not enough data to contain header ?
  4165. if (data.length < 19) {
  4166. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4167. return;
  4168. }
  4169. // Read Header
  4170. var offset = 18;
  4171. var header = TGATools.GetTGAHeader(data);
  4172. // Assume it's a valid Targa file.
  4173. if (header.id_length + offset > data.length) {
  4174. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4175. return;
  4176. }
  4177. // Skip not needed data
  4178. offset += header.id_length;
  4179. var use_rle = false;
  4180. var use_pal = false;
  4181. var use_rgb = false;
  4182. var use_grey = false;
  4183. // Get some informations.
  4184. switch (header.image_type) {
  4185. case TGATools._TYPE_RLE_INDEXED:
  4186. use_rle = true;
  4187. case TGATools._TYPE_INDEXED:
  4188. use_pal = true;
  4189. break;
  4190. case TGATools._TYPE_RLE_RGB:
  4191. use_rle = true;
  4192. case TGATools._TYPE_RGB:
  4193. use_rgb = true;
  4194. break;
  4195. case TGATools._TYPE_RLE_GREY:
  4196. use_rle = true;
  4197. case TGATools._TYPE_GREY:
  4198. use_grey = true;
  4199. break;
  4200. }
  4201. var pixel_data;
  4202. var numAlphaBits = header.flags & 0xf;
  4203. var pixel_size = header.pixel_size >> 3;
  4204. var pixel_total = header.width * header.height * pixel_size;
  4205. // Read palettes
  4206. var palettes;
  4207. if (use_pal) {
  4208. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4209. }
  4210. // Read LRE
  4211. if (use_rle) {
  4212. pixel_data = new Uint8Array(pixel_total);
  4213. var c, count, i;
  4214. var localOffset = 0;
  4215. var pixels = new Uint8Array(pixel_size);
  4216. while (offset < pixel_total && localOffset < pixel_total) {
  4217. c = data[offset++];
  4218. count = (c & 0x7f) + 1;
  4219. // RLE pixels
  4220. if (c & 0x80) {
  4221. // Bind pixel tmp array
  4222. for (i = 0; i < pixel_size; ++i) {
  4223. pixels[i] = data[offset++];
  4224. }
  4225. // Copy pixel array
  4226. for (i = 0; i < count; ++i) {
  4227. pixel_data.set(pixels, localOffset + i * pixel_size);
  4228. }
  4229. localOffset += pixel_size * count;
  4230. }
  4231. else {
  4232. count *= pixel_size;
  4233. for (i = 0; i < count; ++i) {
  4234. pixel_data[localOffset + i] = data[offset++];
  4235. }
  4236. localOffset += count;
  4237. }
  4238. }
  4239. }
  4240. else {
  4241. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4242. }
  4243. // Load to texture
  4244. var x_start, y_start, x_step, y_step, y_end, x_end;
  4245. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4246. default:
  4247. case TGATools._ORIGIN_UL:
  4248. x_start = 0;
  4249. x_step = 1;
  4250. x_end = header.width;
  4251. y_start = 0;
  4252. y_step = 1;
  4253. y_end = header.height;
  4254. break;
  4255. case TGATools._ORIGIN_BL:
  4256. x_start = 0;
  4257. x_step = 1;
  4258. x_end = header.width;
  4259. y_start = header.height - 1;
  4260. y_step = -1;
  4261. y_end = -1;
  4262. break;
  4263. case TGATools._ORIGIN_UR:
  4264. x_start = header.width - 1;
  4265. x_step = -1;
  4266. x_end = -1;
  4267. y_start = 0;
  4268. y_step = 1;
  4269. y_end = header.height;
  4270. break;
  4271. case TGATools._ORIGIN_BR:
  4272. x_start = header.width - 1;
  4273. x_step = -1;
  4274. x_end = -1;
  4275. y_start = header.height - 1;
  4276. y_step = -1;
  4277. y_end = -1;
  4278. break;
  4279. }
  4280. // Load the specify method
  4281. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4282. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4283. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4284. };
  4285. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4286. var image = pixel_data, colormap = palettes;
  4287. var width = header.width, height = header.height;
  4288. var color, i = 0, x, y;
  4289. var imageData = new Uint8Array(width * height * 4);
  4290. for (y = y_start; y !== y_end; y += y_step) {
  4291. for (x = x_start; x !== x_end; x += x_step, i++) {
  4292. color = image[i];
  4293. imageData[(x + width * y) * 4 + 3] = 255;
  4294. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4295. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4296. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4297. }
  4298. }
  4299. return imageData;
  4300. };
  4301. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4302. var image = pixel_data;
  4303. var width = header.width, height = header.height;
  4304. var color, i = 0, x, y;
  4305. var imageData = new Uint8Array(width * height * 4);
  4306. for (y = y_start; y !== y_end; y += y_step) {
  4307. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4308. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4309. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4310. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4311. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4312. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4313. }
  4314. }
  4315. return imageData;
  4316. };
  4317. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4318. var image = pixel_data;
  4319. var width = header.width, height = header.height;
  4320. var i = 0, x, y;
  4321. var imageData = new Uint8Array(width * height * 4);
  4322. for (y = y_start; y !== y_end; y += y_step) {
  4323. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4324. imageData[(x + width * y) * 4 + 3] = 255;
  4325. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4326. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4327. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4328. }
  4329. }
  4330. return imageData;
  4331. };
  4332. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4333. var image = pixel_data;
  4334. var width = header.width, height = header.height;
  4335. var i = 0, x, y;
  4336. var imageData = new Uint8Array(width * height * 4);
  4337. for (y = y_start; y !== y_end; y += y_step) {
  4338. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4339. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4340. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4341. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4342. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4343. }
  4344. }
  4345. return imageData;
  4346. };
  4347. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4348. var image = pixel_data;
  4349. var width = header.width, height = header.height;
  4350. var color, i = 0, x, y;
  4351. var imageData = new Uint8Array(width * height * 4);
  4352. for (y = y_start; y !== y_end; y += y_step) {
  4353. for (x = x_start; x !== x_end; x += x_step, i++) {
  4354. color = image[i];
  4355. imageData[(x + width * y) * 4 + 0] = color;
  4356. imageData[(x + width * y) * 4 + 1] = color;
  4357. imageData[(x + width * y) * 4 + 2] = color;
  4358. imageData[(x + width * y) * 4 + 3] = 255;
  4359. }
  4360. }
  4361. return imageData;
  4362. };
  4363. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4364. var image = pixel_data;
  4365. var width = header.width, height = header.height;
  4366. var i = 0, x, y;
  4367. var imageData = new Uint8Array(width * height * 4);
  4368. for (y = y_start; y !== y_end; y += y_step) {
  4369. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4370. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4371. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4372. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4373. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4374. }
  4375. }
  4376. return imageData;
  4377. };
  4378. return TGATools;
  4379. }());
  4380. TGATools._TYPE_NO_DATA = 0;
  4381. TGATools._TYPE_INDEXED = 1;
  4382. TGATools._TYPE_RGB = 2;
  4383. TGATools._TYPE_GREY = 3;
  4384. TGATools._TYPE_RLE_INDEXED = 9;
  4385. TGATools._TYPE_RLE_RGB = 10;
  4386. TGATools._TYPE_RLE_GREY = 11;
  4387. TGATools._ORIGIN_MASK = 0x30;
  4388. TGATools._ORIGIN_SHIFT = 0x04;
  4389. TGATools._ORIGIN_BL = 0x00;
  4390. TGATools._ORIGIN_BR = 0x01;
  4391. TGATools._ORIGIN_UL = 0x02;
  4392. TGATools._ORIGIN_UR = 0x03;
  4393. Internals.TGATools = TGATools;
  4394. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4395. })(BABYLON || (BABYLON = {}));
  4396. //# sourceMappingURL=babylon.tools.tga.js.map
  4397. var BABYLON;
  4398. (function (BABYLON) {
  4399. var SmartArray = (function () {
  4400. function SmartArray(capacity) {
  4401. this.length = 0;
  4402. this._duplicateId = 0;
  4403. this.data = new Array(capacity);
  4404. this._id = SmartArray._GlobalId++;
  4405. }
  4406. SmartArray.prototype.push = function (value) {
  4407. this.data[this.length++] = value;
  4408. if (this.length > this.data.length) {
  4409. this.data.length *= 2;
  4410. }
  4411. if (!value.__smartArrayFlags) {
  4412. value.__smartArrayFlags = {};
  4413. }
  4414. value.__smartArrayFlags[this._id] = this._duplicateId;
  4415. };
  4416. SmartArray.prototype.pushNoDuplicate = function (value) {
  4417. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4418. return false;
  4419. }
  4420. this.push(value);
  4421. return true;
  4422. };
  4423. SmartArray.prototype.sort = function (compareFn) {
  4424. this.data.sort(compareFn);
  4425. };
  4426. SmartArray.prototype.reset = function () {
  4427. this.length = 0;
  4428. this._duplicateId++;
  4429. };
  4430. SmartArray.prototype.concat = function (array) {
  4431. if (array.length === 0) {
  4432. return;
  4433. }
  4434. if (this.length + array.length > this.data.length) {
  4435. this.data.length = (this.length + array.length) * 2;
  4436. }
  4437. for (var index = 0; index < array.length; index++) {
  4438. this.data[this.length++] = (array.data || array)[index];
  4439. }
  4440. };
  4441. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4442. if (array.length === 0) {
  4443. return;
  4444. }
  4445. if (this.length + array.length > this.data.length) {
  4446. this.data.length = (this.length + array.length) * 2;
  4447. }
  4448. for (var index = 0; index < array.length; index++) {
  4449. var item = (array.data || array)[index];
  4450. this.pushNoDuplicate(item);
  4451. }
  4452. };
  4453. SmartArray.prototype.indexOf = function (value) {
  4454. var position = this.data.indexOf(value);
  4455. if (position >= this.length) {
  4456. return -1;
  4457. }
  4458. return position;
  4459. };
  4460. return SmartArray;
  4461. }());
  4462. // Statics
  4463. SmartArray._GlobalId = 0;
  4464. BABYLON.SmartArray = SmartArray;
  4465. })(BABYLON || (BABYLON = {}));
  4466. //# sourceMappingURL=babylon.smartArray.js.map
  4467. var BABYLON;
  4468. (function (BABYLON) {
  4469. /**
  4470. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4471. * The underlying implementation relies on an associative array to ensure the best performances.
  4472. * The value can be anything including 'null' but except 'undefined'
  4473. */
  4474. var StringDictionary = (function () {
  4475. function StringDictionary() {
  4476. this._count = 0;
  4477. this._data = {};
  4478. }
  4479. /**
  4480. * This will clear this dictionary and copy the content from the 'source' one.
  4481. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4482. * @param source the dictionary to take the content from and copy to this dictionary
  4483. */
  4484. StringDictionary.prototype.copyFrom = function (source) {
  4485. var _this = this;
  4486. this.clear();
  4487. source.forEach(function (t, v) { return _this.add(t, v); });
  4488. };
  4489. /**
  4490. * Get a value based from its key
  4491. * @param key the given key to get the matching value from
  4492. * @return the value if found, otherwise undefined is returned
  4493. */
  4494. StringDictionary.prototype.get = function (key) {
  4495. var val = this._data[key];
  4496. if (val !== undefined) {
  4497. return val;
  4498. }
  4499. return undefined;
  4500. };
  4501. /**
  4502. * Get a value from its key or add it if it doesn't exist.
  4503. * This method will ensure you that a given key/data will be present in the dictionary.
  4504. * @param key the given key to get the matching value from
  4505. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4506. * The factory will only be invoked if there's no data for the given key.
  4507. * @return the value corresponding to the key.
  4508. */
  4509. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4510. var val = this.get(key);
  4511. if (val !== undefined) {
  4512. return val;
  4513. }
  4514. val = factory(key);
  4515. if (val) {
  4516. this.add(key, val);
  4517. }
  4518. return val;
  4519. };
  4520. /**
  4521. * Get a value from its key if present in the dictionary otherwise add it
  4522. * @param key the key to get the value from
  4523. * @param val if there's no such key/value pair in the dictionary add it with this value
  4524. * @return the value corresponding to the key
  4525. */
  4526. StringDictionary.prototype.getOrAdd = function (key, val) {
  4527. var curVal = this.get(key);
  4528. if (curVal !== undefined) {
  4529. return curVal;
  4530. }
  4531. this.add(key, val);
  4532. return val;
  4533. };
  4534. /**
  4535. * Check if there's a given key in the dictionary
  4536. * @param key the key to check for
  4537. * @return true if the key is present, false otherwise
  4538. */
  4539. StringDictionary.prototype.contains = function (key) {
  4540. return this._data[key] !== undefined;
  4541. };
  4542. /**
  4543. * Add a new key and its corresponding value
  4544. * @param key the key to add
  4545. * @param value the value corresponding to the key
  4546. * @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
  4547. */
  4548. StringDictionary.prototype.add = function (key, value) {
  4549. if (this._data[key] !== undefined) {
  4550. return false;
  4551. }
  4552. this._data[key] = value;
  4553. ++this._count;
  4554. return true;
  4555. };
  4556. StringDictionary.prototype.set = function (key, value) {
  4557. if (this._data[key] === undefined) {
  4558. return false;
  4559. }
  4560. this._data[key] = value;
  4561. return true;
  4562. };
  4563. /**
  4564. * Get the element of the given key and remove it from the dictionary
  4565. * @param key
  4566. */
  4567. StringDictionary.prototype.getAndRemove = function (key) {
  4568. var val = this.get(key);
  4569. if (val !== undefined) {
  4570. delete this._data[key];
  4571. --this._count;
  4572. return val;
  4573. }
  4574. return null;
  4575. };
  4576. /**
  4577. * Remove a key/value from the dictionary.
  4578. * @param key the key to remove
  4579. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4580. */
  4581. StringDictionary.prototype.remove = function (key) {
  4582. if (this.contains(key)) {
  4583. delete this._data[key];
  4584. --this._count;
  4585. return true;
  4586. }
  4587. return false;
  4588. };
  4589. /**
  4590. * Clear the whole content of the dictionary
  4591. */
  4592. StringDictionary.prototype.clear = function () {
  4593. this._data = {};
  4594. this._count = 0;
  4595. };
  4596. Object.defineProperty(StringDictionary.prototype, "count", {
  4597. get: function () {
  4598. return this._count;
  4599. },
  4600. enumerable: true,
  4601. configurable: true
  4602. });
  4603. /**
  4604. * Execute a callback on each key/val of the dictionary.
  4605. * Note that you can remove any element in this dictionary in the callback implementation
  4606. * @param callback the callback to execute on a given key/value pair
  4607. */
  4608. StringDictionary.prototype.forEach = function (callback) {
  4609. for (var cur in this._data) {
  4610. var val = this._data[cur];
  4611. callback(cur, val);
  4612. }
  4613. };
  4614. /**
  4615. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4616. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4617. * Note that you can remove any element in this dictionary in the callback implementation
  4618. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4619. */
  4620. StringDictionary.prototype.first = function (callback) {
  4621. for (var cur in this._data) {
  4622. var val = this._data[cur];
  4623. var res = callback(cur, val);
  4624. if (res) {
  4625. return res;
  4626. }
  4627. }
  4628. return null;
  4629. };
  4630. return StringDictionary;
  4631. }());
  4632. BABYLON.StringDictionary = StringDictionary;
  4633. })(BABYLON || (BABYLON = {}));
  4634. //# sourceMappingURL=babylon.stringDictionary.js.map
  4635. var BABYLON;
  4636. (function (BABYLON) {
  4637. // Screenshots
  4638. var screenshotCanvas;
  4639. var cloneValue = function (source, destinationObject) {
  4640. if (!source)
  4641. return null;
  4642. if (source instanceof BABYLON.Mesh) {
  4643. return null;
  4644. }
  4645. if (source instanceof BABYLON.SubMesh) {
  4646. return source.clone(destinationObject);
  4647. }
  4648. else if (source.clone) {
  4649. return source.clone();
  4650. }
  4651. return null;
  4652. };
  4653. var Tools = (function () {
  4654. function Tools() {
  4655. }
  4656. ;
  4657. Tools.Instantiate = function (className) {
  4658. var arr = className.split(".");
  4659. var fn = (window || this);
  4660. for (var i = 0, len = arr.length; i < len; i++) {
  4661. fn = fn[arr[i]];
  4662. }
  4663. if (typeof fn !== "function") {
  4664. return null;
  4665. }
  4666. return fn;
  4667. };
  4668. Tools.SetImmediate = function (action) {
  4669. if (window.setImmediate) {
  4670. window.setImmediate(action);
  4671. }
  4672. else {
  4673. setTimeout(action, 1);
  4674. }
  4675. };
  4676. Tools.IsExponentOfTwo = function (value) {
  4677. var count = 1;
  4678. do {
  4679. count *= 2;
  4680. } while (count < value);
  4681. return count === value;
  4682. };
  4683. Tools.GetExponentOfTwo = function (value, max) {
  4684. var count = 1;
  4685. do {
  4686. count *= 2;
  4687. } while (count < value);
  4688. if (count > max)
  4689. count = max;
  4690. return count;
  4691. };
  4692. Tools.GetFilename = function (path) {
  4693. var index = path.lastIndexOf("/");
  4694. if (index < 0)
  4695. return path;
  4696. return path.substring(index + 1);
  4697. };
  4698. Tools.GetDOMTextContent = function (element) {
  4699. var result = "";
  4700. var child = element.firstChild;
  4701. while (child) {
  4702. if (child.nodeType === 3) {
  4703. result += child.textContent;
  4704. }
  4705. child = child.nextSibling;
  4706. }
  4707. return result;
  4708. };
  4709. Tools.ToDegrees = function (angle) {
  4710. return angle * 180 / Math.PI;
  4711. };
  4712. Tools.ToRadians = function (angle) {
  4713. return angle * Math.PI / 180;
  4714. };
  4715. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4716. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4717. var output = "";
  4718. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4719. var i = 0;
  4720. var bytes = new Uint8Array(buffer);
  4721. while (i < bytes.length) {
  4722. chr1 = bytes[i++];
  4723. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4724. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4725. enc1 = chr1 >> 2;
  4726. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4727. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4728. enc4 = chr3 & 63;
  4729. if (isNaN(chr2)) {
  4730. enc3 = enc4 = 64;
  4731. }
  4732. else if (isNaN(chr3)) {
  4733. enc4 = 64;
  4734. }
  4735. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4736. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4737. }
  4738. return "data:image/png;base64," + output;
  4739. };
  4740. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4741. if (bias === void 0) { bias = null; }
  4742. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4743. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4744. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4745. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4746. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4747. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4748. }
  4749. if (bias) {
  4750. minimum.x -= minimum.x * bias.x + bias.y;
  4751. minimum.y -= minimum.y * bias.x + bias.y;
  4752. minimum.z -= minimum.z * bias.x + bias.y;
  4753. maximum.x += maximum.x * bias.x + bias.y;
  4754. maximum.y += maximum.y * bias.x + bias.y;
  4755. maximum.z += maximum.z * bias.x + bias.y;
  4756. }
  4757. return {
  4758. minimum: minimum,
  4759. maximum: maximum
  4760. };
  4761. };
  4762. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4763. if (bias === void 0) { bias = null; }
  4764. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4765. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4766. if (!stride) {
  4767. stride = 3;
  4768. }
  4769. for (var index = start; index < start + count; index++) {
  4770. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4771. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4772. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4773. }
  4774. if (bias) {
  4775. minimum.x -= minimum.x * bias.x + bias.y;
  4776. minimum.y -= minimum.y * bias.x + bias.y;
  4777. minimum.z -= minimum.z * bias.x + bias.y;
  4778. maximum.x += maximum.x * bias.x + bias.y;
  4779. maximum.y += maximum.y * bias.x + bias.y;
  4780. maximum.z += maximum.z * bias.x + bias.y;
  4781. }
  4782. return {
  4783. minimum: minimum,
  4784. maximum: maximum
  4785. };
  4786. };
  4787. Tools.Vector2ArrayFeeder = function (array) {
  4788. return function (index) {
  4789. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4790. var length = isFloatArray ? array.length / 2 : array.length;
  4791. if (index >= length) {
  4792. return null;
  4793. }
  4794. if (isFloatArray) {
  4795. var fa = array;
  4796. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4797. }
  4798. var a = array;
  4799. return a[index];
  4800. };
  4801. };
  4802. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4803. if (bias === void 0) { bias = null; }
  4804. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4805. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4806. var i = 0;
  4807. var cur = feeder(i++);
  4808. while (cur) {
  4809. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4810. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4811. cur = feeder(i++);
  4812. }
  4813. if (bias) {
  4814. minimum.x -= minimum.x * bias.x + bias.y;
  4815. minimum.y -= minimum.y * bias.x + bias.y;
  4816. maximum.x += maximum.x * bias.x + bias.y;
  4817. maximum.y += maximum.y * bias.x + bias.y;
  4818. }
  4819. return {
  4820. minimum: minimum,
  4821. maximum: maximum
  4822. };
  4823. };
  4824. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4825. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4826. return undefined;
  4827. return Array.isArray(obj) ? obj : [obj];
  4828. };
  4829. // Misc.
  4830. Tools.GetPointerPrefix = function () {
  4831. var eventPrefix = "pointer";
  4832. // Check if pointer events are supported
  4833. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4834. eventPrefix = "mouse";
  4835. }
  4836. return eventPrefix;
  4837. };
  4838. /**
  4839. * @param func - the function to be called
  4840. * @param requester - the object that will request the next frame. Falls back to window.
  4841. */
  4842. Tools.QueueNewFrame = function (func, requester) {
  4843. if (requester === void 0) { requester = window; }
  4844. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4845. /*if(requester.isPresenting) {
  4846. return;
  4847. } else*/ if (requester.requestAnimationFrame)
  4848. requester.requestAnimationFrame(func);
  4849. else if (requester.msRequestAnimationFrame)
  4850. requester.msRequestAnimationFrame(func);
  4851. else if (requester.webkitRequestAnimationFrame)
  4852. requester.webkitRequestAnimationFrame(func);
  4853. else if (requester.mozRequestAnimationFrame)
  4854. requester.mozRequestAnimationFrame(func);
  4855. else if (requester.oRequestAnimationFrame)
  4856. requester.oRequestAnimationFrame(func);
  4857. else {
  4858. window.setTimeout(func, 16);
  4859. }
  4860. };
  4861. Tools.RequestFullscreen = function (element) {
  4862. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4863. if (!requestFunction)
  4864. return;
  4865. requestFunction.call(element);
  4866. };
  4867. Tools.ExitFullscreen = function () {
  4868. if (document.exitFullscreen) {
  4869. document.exitFullscreen();
  4870. }
  4871. else if (document.mozCancelFullScreen) {
  4872. document.mozCancelFullScreen();
  4873. }
  4874. else if (document.webkitCancelFullScreen) {
  4875. document.webkitCancelFullScreen();
  4876. }
  4877. else if (document.msCancelFullScreen) {
  4878. document.msCancelFullScreen();
  4879. }
  4880. };
  4881. Tools.SetCorsBehavior = function (url, img) {
  4882. if (Tools.CorsBehavior) {
  4883. switch (typeof (Tools.CorsBehavior)) {
  4884. case "function":
  4885. var result = Tools.CorsBehavior(url);
  4886. if (result) {
  4887. return result;
  4888. }
  4889. break;
  4890. case "string":
  4891. default:
  4892. img.crossOrigin = Tools.CorsBehavior;
  4893. break;
  4894. }
  4895. }
  4896. };
  4897. // External files
  4898. Tools.CleanUrl = function (url) {
  4899. url = url.replace(/#/mg, "%23");
  4900. return url;
  4901. };
  4902. Tools.LoadImage = function (url, onload, onerror, database) {
  4903. if (url instanceof ArrayBuffer) {
  4904. url = Tools.EncodeArrayBufferTobase64(url);
  4905. }
  4906. url = Tools.CleanUrl(url);
  4907. var img = new Image();
  4908. if (url.substr(0, 5) !== "data:") {
  4909. Tools.SetCorsBehavior(url, img);
  4910. }
  4911. img.onload = function () {
  4912. onload(img);
  4913. };
  4914. img.onerror = function (err) {
  4915. Tools.Error("Error while trying to load image: " + url);
  4916. if (Tools.UseFallbackTexture) {
  4917. img.src = Tools.fallbackTexture;
  4918. onload(img);
  4919. }
  4920. else {
  4921. onerror();
  4922. }
  4923. };
  4924. var noIndexedDB = function () {
  4925. img.src = url;
  4926. };
  4927. var loadFromIndexedDB = function () {
  4928. database.loadImageFromDB(url, img);
  4929. };
  4930. //ANY database to do!
  4931. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4932. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4933. }
  4934. else {
  4935. if (url.indexOf("file:") === -1) {
  4936. noIndexedDB();
  4937. }
  4938. else {
  4939. var textureName = url.substring(5).toLowerCase();
  4940. if (BABYLON.FilesInput.FilesTextures[textureName]) {
  4941. try {
  4942. var blobURL;
  4943. try {
  4944. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4945. }
  4946. catch (ex) {
  4947. // Chrome doesn't support oneTimeOnly parameter
  4948. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4949. }
  4950. img.src = blobURL;
  4951. }
  4952. catch (e) {
  4953. img.src = null;
  4954. }
  4955. }
  4956. else {
  4957. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  4958. img.src = Tools.fallbackTexture;
  4959. }
  4960. }
  4961. }
  4962. return img;
  4963. };
  4964. //ANY
  4965. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4966. url = Tools.CleanUrl(url);
  4967. var noIndexedDB = function () {
  4968. var request = new XMLHttpRequest();
  4969. var loadUrl = Tools.BaseUrl + url;
  4970. request.open('GET', loadUrl, true);
  4971. if (useArrayBuffer) {
  4972. request.responseType = "arraybuffer";
  4973. }
  4974. request.onprogress = progressCallBack;
  4975. request.onreadystatechange = function () {
  4976. if (request.readyState === 4) {
  4977. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4978. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4979. callback(!useArrayBuffer ? request.responseText : request.response);
  4980. }
  4981. else {
  4982. if (onError) {
  4983. onError();
  4984. }
  4985. else {
  4986. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4987. }
  4988. }
  4989. }
  4990. };
  4991. request.send(null);
  4992. };
  4993. var loadFromIndexedDB = function () {
  4994. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4995. };
  4996. if (url.indexOf("file:") !== -1) {
  4997. var fileName = url.substring(5).toLowerCase();
  4998. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  4999. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5000. }
  5001. else {
  5002. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5003. }
  5004. }
  5005. else {
  5006. // Caching all files
  5007. if (database && database.enableSceneOffline) {
  5008. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5009. }
  5010. else {
  5011. noIndexedDB();
  5012. }
  5013. }
  5014. };
  5015. /**
  5016. * Load a script (identified by an url). When the url returns, the
  5017. * content of this file is added into a new script element, attached to the DOM (body element)
  5018. */
  5019. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5020. var head = document.getElementsByTagName('head')[0];
  5021. var script = document.createElement('script');
  5022. script.type = 'text/javascript';
  5023. script.src = scriptUrl;
  5024. var self = this;
  5025. script.onload = function () {
  5026. if (onSuccess) {
  5027. onSuccess();
  5028. }
  5029. };
  5030. script.onerror = function () {
  5031. if (onError) {
  5032. onError();
  5033. }
  5034. };
  5035. head.appendChild(script);
  5036. };
  5037. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5038. var reader = new FileReader();
  5039. reader.onload = function (e) {
  5040. //target doesn't have result from ts 1.3
  5041. callback(e.target['result']);
  5042. };
  5043. reader.onprogress = progressCallback;
  5044. reader.readAsDataURL(fileToLoad);
  5045. };
  5046. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5047. var reader = new FileReader();
  5048. reader.onerror = function (e) {
  5049. Tools.Log("Error while reading file: " + fileToLoad.name);
  5050. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5051. };
  5052. reader.onload = function (e) {
  5053. //target doesn't have result from ts 1.3
  5054. callback(e.target['result']);
  5055. };
  5056. reader.onprogress = progressCallBack;
  5057. if (!useArrayBuffer) {
  5058. // Asynchronous read
  5059. reader.readAsText(fileToLoad);
  5060. }
  5061. else {
  5062. reader.readAsArrayBuffer(fileToLoad);
  5063. }
  5064. };
  5065. //returns a downloadable url to a file content.
  5066. Tools.FileAsURL = function (content) {
  5067. var fileBlob = new Blob([content]);
  5068. var url = window.URL || window.webkitURL;
  5069. var link = url.createObjectURL(fileBlob);
  5070. return link;
  5071. };
  5072. // Misc.
  5073. Tools.Format = function (value, decimals) {
  5074. if (decimals === void 0) { decimals = 2; }
  5075. return value.toFixed(decimals);
  5076. };
  5077. Tools.CheckExtends = function (v, min, max) {
  5078. if (v.x < min.x)
  5079. min.x = v.x;
  5080. if (v.y < min.y)
  5081. min.y = v.y;
  5082. if (v.z < min.z)
  5083. min.z = v.z;
  5084. if (v.x > max.x)
  5085. max.x = v.x;
  5086. if (v.y > max.y)
  5087. max.y = v.y;
  5088. if (v.z > max.z)
  5089. max.z = v.z;
  5090. };
  5091. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5092. for (var prop in source) {
  5093. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5094. continue;
  5095. }
  5096. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5097. continue;
  5098. }
  5099. var sourceValue = source[prop];
  5100. var typeOfSourceValue = typeof sourceValue;
  5101. if (typeOfSourceValue === "function") {
  5102. continue;
  5103. }
  5104. if (typeOfSourceValue === "object") {
  5105. if (sourceValue instanceof Array) {
  5106. destination[prop] = [];
  5107. if (sourceValue.length > 0) {
  5108. if (typeof sourceValue[0] == "object") {
  5109. for (var index = 0; index < sourceValue.length; index++) {
  5110. var clonedValue = cloneValue(sourceValue[index], destination);
  5111. if (destination[prop].indexOf(clonedValue) === -1) {
  5112. destination[prop].push(clonedValue);
  5113. }
  5114. }
  5115. }
  5116. else {
  5117. destination[prop] = sourceValue.slice(0);
  5118. }
  5119. }
  5120. }
  5121. else {
  5122. destination[prop] = cloneValue(sourceValue, destination);
  5123. }
  5124. }
  5125. else {
  5126. destination[prop] = sourceValue;
  5127. }
  5128. }
  5129. };
  5130. Tools.IsEmpty = function (obj) {
  5131. for (var i in obj) {
  5132. return false;
  5133. }
  5134. return true;
  5135. };
  5136. Tools.RegisterTopRootEvents = function (events) {
  5137. for (var index = 0; index < events.length; index++) {
  5138. var event = events[index];
  5139. window.addEventListener(event.name, event.handler, false);
  5140. try {
  5141. if (window.parent) {
  5142. window.parent.addEventListener(event.name, event.handler, false);
  5143. }
  5144. }
  5145. catch (e) {
  5146. }
  5147. }
  5148. };
  5149. Tools.UnregisterTopRootEvents = function (events) {
  5150. for (var index = 0; index < events.length; index++) {
  5151. var event = events[index];
  5152. window.removeEventListener(event.name, event.handler);
  5153. try {
  5154. if (window.parent) {
  5155. window.parent.removeEventListener(event.name, event.handler);
  5156. }
  5157. }
  5158. catch (e) {
  5159. }
  5160. }
  5161. };
  5162. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5163. if (mimeType === void 0) { mimeType = "image/png"; }
  5164. // Read the contents of the framebuffer
  5165. var numberOfChannelsByLine = width * 4;
  5166. var halfHeight = height / 2;
  5167. //Reading datas from WebGL
  5168. var data = engine.readPixels(0, 0, width, height);
  5169. //To flip image on Y axis.
  5170. for (var i = 0; i < halfHeight; i++) {
  5171. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5172. var currentCell = j + i * numberOfChannelsByLine;
  5173. var targetLine = height - i - 1;
  5174. var targetCell = j + targetLine * numberOfChannelsByLine;
  5175. var temp = data[currentCell];
  5176. data[currentCell] = data[targetCell];
  5177. data[targetCell] = temp;
  5178. }
  5179. }
  5180. // Create a 2D canvas to store the result
  5181. if (!screenshotCanvas) {
  5182. screenshotCanvas = document.createElement('canvas');
  5183. }
  5184. screenshotCanvas.width = width;
  5185. screenshotCanvas.height = height;
  5186. var context = screenshotCanvas.getContext('2d');
  5187. // Copy the pixels to a 2D canvas
  5188. var imageData = context.createImageData(width, height);
  5189. var castData = (imageData.data);
  5190. castData.set(data);
  5191. context.putImageData(imageData, 0, 0);
  5192. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5193. };
  5194. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5195. if (mimeType === void 0) { mimeType = "image/png"; }
  5196. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5197. if (successCallback) {
  5198. successCallback(base64Image);
  5199. }
  5200. else {
  5201. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5202. if (("download" in document.createElement("a"))) {
  5203. var a = window.document.createElement("a");
  5204. a.href = base64Image;
  5205. var date = new Date();
  5206. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5207. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5208. window.document.body.appendChild(a);
  5209. a.addEventListener("click", function () {
  5210. a.parentElement.removeChild(a);
  5211. });
  5212. a.click();
  5213. }
  5214. else {
  5215. var newWindow = window.open("");
  5216. var img = newWindow.document.createElement("img");
  5217. img.src = base64Image;
  5218. newWindow.document.body.appendChild(img);
  5219. }
  5220. }
  5221. };
  5222. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5223. if (mimeType === void 0) { mimeType = "image/png"; }
  5224. var width;
  5225. var height;
  5226. // If a precision value is specified
  5227. if (size.precision) {
  5228. width = Math.round(engine.getRenderWidth() * size.precision);
  5229. height = Math.round(width / engine.getAspectRatio(camera));
  5230. }
  5231. else if (size.width && size.height) {
  5232. width = size.width;
  5233. height = size.height;
  5234. }
  5235. else if (size.width && !size.height) {
  5236. width = size.width;
  5237. height = Math.round(width / engine.getAspectRatio(camera));
  5238. }
  5239. else if (size.height && !size.width) {
  5240. height = size.height;
  5241. width = Math.round(height * engine.getAspectRatio(camera));
  5242. }
  5243. else if (!isNaN(size)) {
  5244. height = size;
  5245. width = size;
  5246. }
  5247. else {
  5248. Tools.Error("Invalid 'size' parameter !");
  5249. return;
  5250. }
  5251. if (!screenshotCanvas) {
  5252. screenshotCanvas = document.createElement('canvas');
  5253. }
  5254. screenshotCanvas.width = width;
  5255. screenshotCanvas.height = height;
  5256. var renderContext = screenshotCanvas.getContext("2d");
  5257. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5258. var newWidth = width;
  5259. var newHeight = newWidth / ratio;
  5260. if (newHeight > height) {
  5261. newHeight = height;
  5262. newWidth = newHeight * ratio;
  5263. }
  5264. var offsetX = Math.max(0, width - newWidth) / 2;
  5265. var offsetY = Math.max(0, height - newHeight) / 2;
  5266. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5267. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5268. };
  5269. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5270. if (mimeType === void 0) { mimeType = "image/png"; }
  5271. var width;
  5272. var height;
  5273. //If a precision value is specified
  5274. if (size.precision) {
  5275. width = Math.round(engine.getRenderWidth() * size.precision);
  5276. height = Math.round(width / engine.getAspectRatio(camera));
  5277. size = { width: width, height: height };
  5278. }
  5279. else if (size.width && size.height) {
  5280. width = size.width;
  5281. height = size.height;
  5282. }
  5283. else if (size.width && !size.height) {
  5284. width = size.width;
  5285. height = Math.round(width / engine.getAspectRatio(camera));
  5286. size = { width: width, height: height };
  5287. }
  5288. else if (size.height && !size.width) {
  5289. height = size.height;
  5290. width = Math.round(height * engine.getAspectRatio(camera));
  5291. size = { width: width, height: height };
  5292. }
  5293. else if (!isNaN(size)) {
  5294. height = size;
  5295. width = size;
  5296. }
  5297. else {
  5298. Tools.Error("Invalid 'size' parameter !");
  5299. return;
  5300. }
  5301. var scene = camera.getScene();
  5302. var previousCamera = null;
  5303. if (scene.activeCamera !== camera) {
  5304. previousCamera = scene.activeCamera;
  5305. scene.activeCamera = camera;
  5306. }
  5307. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5308. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5309. texture.renderList = scene.meshes;
  5310. texture.onAfterRenderObservable.add(function () {
  5311. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5312. });
  5313. scene.incrementRenderId();
  5314. scene.resetCachedMaterial();
  5315. texture.render(true);
  5316. texture.dispose();
  5317. if (previousCamera) {
  5318. scene.activeCamera = previousCamera;
  5319. }
  5320. camera.getProjectionMatrix(true); // Force cache refresh;
  5321. };
  5322. // XHR response validator for local file scenario
  5323. Tools.ValidateXHRData = function (xhr, dataType) {
  5324. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5325. if (dataType === void 0) { dataType = 7; }
  5326. try {
  5327. if (dataType & 1) {
  5328. if (xhr.responseText && xhr.responseText.length > 0) {
  5329. return true;
  5330. }
  5331. else if (dataType === 1) {
  5332. return false;
  5333. }
  5334. }
  5335. if (dataType & 2) {
  5336. // Check header width and height since there is no "TGA" magic number
  5337. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5338. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5339. return true;
  5340. }
  5341. else if (dataType === 2) {
  5342. return false;
  5343. }
  5344. }
  5345. if (dataType & 4) {
  5346. // Check for the "DDS" magic number
  5347. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5348. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5349. return true;
  5350. }
  5351. else {
  5352. return false;
  5353. }
  5354. }
  5355. }
  5356. catch (e) {
  5357. }
  5358. return false;
  5359. };
  5360. /**
  5361. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5362. * Be aware Math.random() could cause collisions, but:
  5363. * "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"
  5364. */
  5365. Tools.RandomId = function () {
  5366. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5367. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5368. return v.toString(16);
  5369. });
  5370. };
  5371. Object.defineProperty(Tools, "NoneLogLevel", {
  5372. get: function () {
  5373. return Tools._NoneLogLevel;
  5374. },
  5375. enumerable: true,
  5376. configurable: true
  5377. });
  5378. Object.defineProperty(Tools, "MessageLogLevel", {
  5379. get: function () {
  5380. return Tools._MessageLogLevel;
  5381. },
  5382. enumerable: true,
  5383. configurable: true
  5384. });
  5385. Object.defineProperty(Tools, "WarningLogLevel", {
  5386. get: function () {
  5387. return Tools._WarningLogLevel;
  5388. },
  5389. enumerable: true,
  5390. configurable: true
  5391. });
  5392. Object.defineProperty(Tools, "ErrorLogLevel", {
  5393. get: function () {
  5394. return Tools._ErrorLogLevel;
  5395. },
  5396. enumerable: true,
  5397. configurable: true
  5398. });
  5399. Object.defineProperty(Tools, "AllLogLevel", {
  5400. get: function () {
  5401. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5402. },
  5403. enumerable: true,
  5404. configurable: true
  5405. });
  5406. Tools._AddLogEntry = function (entry) {
  5407. Tools._LogCache = entry + Tools._LogCache;
  5408. if (Tools.OnNewCacheEntry) {
  5409. Tools.OnNewCacheEntry(entry);
  5410. }
  5411. };
  5412. Tools._FormatMessage = function (message) {
  5413. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5414. var date = new Date();
  5415. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5416. };
  5417. Tools._LogDisabled = function (message) {
  5418. // nothing to do
  5419. };
  5420. Tools._LogEnabled = function (message) {
  5421. var formattedMessage = Tools._FormatMessage(message);
  5422. console.log("BJS - " + formattedMessage);
  5423. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5424. Tools._AddLogEntry(entry);
  5425. };
  5426. Tools._WarnDisabled = function (message) {
  5427. // nothing to do
  5428. };
  5429. Tools._WarnEnabled = function (message) {
  5430. var formattedMessage = Tools._FormatMessage(message);
  5431. console.warn("BJS - " + formattedMessage);
  5432. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5433. Tools._AddLogEntry(entry);
  5434. };
  5435. Tools._ErrorDisabled = function (message) {
  5436. // nothing to do
  5437. };
  5438. Tools._ErrorEnabled = function (message) {
  5439. Tools.errorsCount++;
  5440. var formattedMessage = Tools._FormatMessage(message);
  5441. console.error("BJS - " + formattedMessage);
  5442. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5443. Tools._AddLogEntry(entry);
  5444. };
  5445. Object.defineProperty(Tools, "LogCache", {
  5446. get: function () {
  5447. return Tools._LogCache;
  5448. },
  5449. enumerable: true,
  5450. configurable: true
  5451. });
  5452. Tools.ClearLogCache = function () {
  5453. Tools._LogCache = "";
  5454. Tools.errorsCount = 0;
  5455. };
  5456. Object.defineProperty(Tools, "LogLevels", {
  5457. set: function (level) {
  5458. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5459. Tools.Log = Tools._LogEnabled;
  5460. }
  5461. else {
  5462. Tools.Log = Tools._LogDisabled;
  5463. }
  5464. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5465. Tools.Warn = Tools._WarnEnabled;
  5466. }
  5467. else {
  5468. Tools.Warn = Tools._WarnDisabled;
  5469. }
  5470. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5471. Tools.Error = Tools._ErrorEnabled;
  5472. }
  5473. else {
  5474. Tools.Error = Tools._ErrorDisabled;
  5475. }
  5476. },
  5477. enumerable: true,
  5478. configurable: true
  5479. });
  5480. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5481. get: function () {
  5482. return Tools._PerformanceNoneLogLevel;
  5483. },
  5484. enumerable: true,
  5485. configurable: true
  5486. });
  5487. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5488. get: function () {
  5489. return Tools._PerformanceUserMarkLogLevel;
  5490. },
  5491. enumerable: true,
  5492. configurable: true
  5493. });
  5494. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5495. get: function () {
  5496. return Tools._PerformanceConsoleLogLevel;
  5497. },
  5498. enumerable: true,
  5499. configurable: true
  5500. });
  5501. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5502. set: function (level) {
  5503. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5504. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5505. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5506. return;
  5507. }
  5508. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5509. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5510. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5511. return;
  5512. }
  5513. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5514. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5515. },
  5516. enumerable: true,
  5517. configurable: true
  5518. });
  5519. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5520. };
  5521. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5522. };
  5523. Tools._StartUserMark = function (counterName, condition) {
  5524. if (condition === void 0) { condition = true; }
  5525. if (!condition || !Tools._performance.mark) {
  5526. return;
  5527. }
  5528. Tools._performance.mark(counterName + "-Begin");
  5529. };
  5530. Tools._EndUserMark = function (counterName, condition) {
  5531. if (condition === void 0) { condition = true; }
  5532. if (!condition || !Tools._performance.mark) {
  5533. return;
  5534. }
  5535. Tools._performance.mark(counterName + "-End");
  5536. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5537. };
  5538. Tools._StartPerformanceConsole = function (counterName, condition) {
  5539. if (condition === void 0) { condition = true; }
  5540. if (!condition) {
  5541. return;
  5542. }
  5543. Tools._StartUserMark(counterName, condition);
  5544. if (console.time) {
  5545. console.time(counterName);
  5546. }
  5547. };
  5548. Tools._EndPerformanceConsole = function (counterName, condition) {
  5549. if (condition === void 0) { condition = true; }
  5550. if (!condition) {
  5551. return;
  5552. }
  5553. Tools._EndUserMark(counterName, condition);
  5554. if (console.time) {
  5555. console.timeEnd(counterName);
  5556. }
  5557. };
  5558. Object.defineProperty(Tools, "Now", {
  5559. get: function () {
  5560. if (window.performance && window.performance.now) {
  5561. return window.performance.now();
  5562. }
  5563. return new Date().getTime();
  5564. },
  5565. enumerable: true,
  5566. configurable: true
  5567. });
  5568. /**
  5569. * This method will return the name of the class used to create the instance of the given object.
  5570. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5571. * @param object the object to get the class name from
  5572. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5573. */
  5574. Tools.getClassName = function (object, isType) {
  5575. if (isType === void 0) { isType = false; }
  5576. var name = null;
  5577. if (!isType && object.getClassName) {
  5578. name = object.getClassName();
  5579. }
  5580. else {
  5581. if (object instanceof Object) {
  5582. var classObj = isType ? object : Object.getPrototypeOf(object);
  5583. name = classObj.constructor["__bjsclassName__"];
  5584. }
  5585. if (!name) {
  5586. name = typeof object;
  5587. }
  5588. }
  5589. return name;
  5590. };
  5591. Tools.first = function (array, predicate) {
  5592. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5593. var el = array_1[_i];
  5594. if (predicate(el)) {
  5595. return el;
  5596. }
  5597. }
  5598. };
  5599. /**
  5600. * This method will return the name of the full name of the class, including its owning module (if any).
  5601. * 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).
  5602. * @param object the object to get the class name from
  5603. * @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.
  5604. */
  5605. Tools.getFullClassName = function (object, isType) {
  5606. if (isType === void 0) { isType = false; }
  5607. var className = null;
  5608. var moduleName = null;
  5609. if (!isType && object.getClassName) {
  5610. className = object.getClassName();
  5611. }
  5612. else {
  5613. if (object instanceof Object) {
  5614. var classObj = isType ? object : Object.getPrototypeOf(object);
  5615. className = classObj.constructor["__bjsclassName__"];
  5616. moduleName = classObj.constructor["__bjsmoduleName__"];
  5617. }
  5618. if (!className) {
  5619. className = typeof object;
  5620. }
  5621. }
  5622. if (!className) {
  5623. return null;
  5624. }
  5625. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5626. };
  5627. /**
  5628. * 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.
  5629. * @param array
  5630. */
  5631. Tools.arrayOrStringFeeder = function (array) {
  5632. return function (index) {
  5633. if (index >= array.length) {
  5634. return null;
  5635. }
  5636. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5637. if (val && val.getHashCode) {
  5638. val = val.getHashCode();
  5639. }
  5640. if (typeof val === "string") {
  5641. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5642. }
  5643. return val;
  5644. };
  5645. };
  5646. /**
  5647. * Compute the hashCode of a stream of number
  5648. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5649. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5650. * @return the hash code computed
  5651. */
  5652. Tools.hashCodeFromStream = function (feeder) {
  5653. // Based from here: http://stackoverflow.com/a/7616484/802124
  5654. var hash = 0;
  5655. var index = 0;
  5656. var chr = feeder(index++);
  5657. while (chr != null) {
  5658. hash = ((hash << 5) - hash) + chr;
  5659. hash |= 0; // Convert to 32bit integer
  5660. chr = feeder(index++);
  5661. }
  5662. return hash;
  5663. };
  5664. return Tools;
  5665. }());
  5666. Tools.BaseUrl = "";
  5667. Tools.CorsBehavior = "anonymous";
  5668. Tools.UseFallbackTexture = true;
  5669. // Used in case of a texture loading problem
  5670. Tools.fallbackTexture = "data:image/jpg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QBmRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUAAAABAAAARgEoAAMAAAABAAIAAAExAAIAAAAQAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQubmV0IDQuMC41AP/bAEMABAIDAwMCBAMDAwQEBAQFCQYFBQUFCwgIBgkNCw0NDQsMDA4QFBEODxMPDAwSGBITFRYXFxcOERkbGRYaFBYXFv/bAEMBBAQEBQUFCgYGChYPDA8WFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFv/AABEIAQABAAMBIgACEQEDEQH/xAAfAAABBQEBAQEBAQAAAAAAAAAAAQIDBAUGBwgJCgv/xAC1EAACAQMDAgQDBQUEBAAAAX0BAgMABBEFEiExQQYTUWEHInEUMoGRoQgjQrHBFVLR8CQzYnKCCQoWFxgZGiUmJygpKjQ1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4eLj5OXm5+jp6vHy8/T19vf4+fr/xAAfAQADAQEBAQEBAQEBAAAAAAAAAQIDBAUGBwgJCgv/xAC1EQACAQIEBAMEBwUEBAABAncAAQIDEQQFITEGEkFRB2FxEyIygQgUQpGhscEJIzNS8BVictEKFiQ04SXxFxgZGiYnKCkqNTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqCg4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2dri4+Tl5ufo6ery8/T19vf4+fr/2gAMAwEAAhEDEQA/APH6KKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76CiiigD5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BQooooA+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/voKKKKAPl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FCiiigD6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++gooooA+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gUKKKKAPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76Pl+iiivuj+BT6gooor4U/vo+X6KKK+6P4FPqCiiivhT++j5fooor7o/gU+oKKKK+FP76P//Z";
  5671. // Logs
  5672. Tools._NoneLogLevel = 0;
  5673. Tools._MessageLogLevel = 1;
  5674. Tools._WarningLogLevel = 2;
  5675. Tools._ErrorLogLevel = 4;
  5676. Tools._LogCache = "";
  5677. Tools.errorsCount = 0;
  5678. Tools.Log = Tools._LogEnabled;
  5679. Tools.Warn = Tools._WarnEnabled;
  5680. Tools.Error = Tools._ErrorEnabled;
  5681. // Performances
  5682. Tools._PerformanceNoneLogLevel = 0;
  5683. Tools._PerformanceUserMarkLogLevel = 1;
  5684. Tools._PerformanceConsoleLogLevel = 2;
  5685. Tools._performance = window.performance;
  5686. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5687. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5688. BABYLON.Tools = Tools;
  5689. /**
  5690. * This class is used to track a performance counter which is number based.
  5691. * The user has access to many properties which give statistics of different nature
  5692. *
  5693. * The implementer can track two kinds of Performance Counter: time and count
  5694. * 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.
  5695. * 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.
  5696. */
  5697. var PerfCounter = (function () {
  5698. function PerfCounter() {
  5699. this._startMonitoringTime = 0;
  5700. this._min = 0;
  5701. this._max = 0;
  5702. this._average = 0;
  5703. this._lastSecAverage = 0;
  5704. this._current = 0;
  5705. this._totalValueCount = 0;
  5706. this._totalAccumulated = 0;
  5707. this._lastSecAccumulated = 0;
  5708. this._lastSecTime = 0;
  5709. this._lastSecValueCount = 0;
  5710. }
  5711. Object.defineProperty(PerfCounter.prototype, "min", {
  5712. /**
  5713. * Returns the smallest value ever
  5714. */
  5715. get: function () {
  5716. return this._min;
  5717. },
  5718. enumerable: true,
  5719. configurable: true
  5720. });
  5721. Object.defineProperty(PerfCounter.prototype, "max", {
  5722. /**
  5723. * Returns the biggest value ever
  5724. */
  5725. get: function () {
  5726. return this._max;
  5727. },
  5728. enumerable: true,
  5729. configurable: true
  5730. });
  5731. Object.defineProperty(PerfCounter.prototype, "average", {
  5732. /**
  5733. * Returns the average value since the performance counter is running
  5734. */
  5735. get: function () {
  5736. return this._average;
  5737. },
  5738. enumerable: true,
  5739. configurable: true
  5740. });
  5741. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5742. /**
  5743. * Returns the average value of the last second the counter was monitored
  5744. */
  5745. get: function () {
  5746. return this._lastSecAverage;
  5747. },
  5748. enumerable: true,
  5749. configurable: true
  5750. });
  5751. Object.defineProperty(PerfCounter.prototype, "current", {
  5752. /**
  5753. * Returns the current value
  5754. */
  5755. get: function () {
  5756. return this._current;
  5757. },
  5758. enumerable: true,
  5759. configurable: true
  5760. });
  5761. Object.defineProperty(PerfCounter.prototype, "total", {
  5762. get: function () {
  5763. return this._totalAccumulated;
  5764. },
  5765. enumerable: true,
  5766. configurable: true
  5767. });
  5768. /**
  5769. * Call this method to start monitoring a new frame.
  5770. * 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.
  5771. */
  5772. PerfCounter.prototype.fetchNewFrame = function () {
  5773. this._totalValueCount++;
  5774. this._current = 0;
  5775. this._lastSecValueCount++;
  5776. };
  5777. /**
  5778. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5779. * @param newCount the count value to add to the monitored count
  5780. * @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.
  5781. */
  5782. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5783. this._current += newCount;
  5784. if (fetchResult) {
  5785. this._fetchResult();
  5786. }
  5787. };
  5788. /**
  5789. * Start monitoring this performance counter
  5790. */
  5791. PerfCounter.prototype.beginMonitoring = function () {
  5792. this._startMonitoringTime = Tools.Now;
  5793. };
  5794. /**
  5795. * Compute the time lapsed since the previous beginMonitoring() call.
  5796. * @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
  5797. */
  5798. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5799. if (newFrame === void 0) { newFrame = true; }
  5800. if (newFrame) {
  5801. this.fetchNewFrame();
  5802. }
  5803. var currentTime = Tools.Now;
  5804. this._current = currentTime - this._startMonitoringTime;
  5805. if (newFrame) {
  5806. this._fetchResult();
  5807. }
  5808. };
  5809. PerfCounter.prototype._fetchResult = function () {
  5810. this._totalAccumulated += this._current;
  5811. this._lastSecAccumulated += this._current;
  5812. // Min/Max update
  5813. this._min = Math.min(this._min, this._current);
  5814. this._max = Math.max(this._max, this._current);
  5815. this._average = this._totalAccumulated / this._totalValueCount;
  5816. // Reset last sec?
  5817. var now = Tools.Now;
  5818. if ((now - this._lastSecTime) > 1000) {
  5819. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5820. this._lastSecTime = now;
  5821. this._lastSecAccumulated = 0;
  5822. this._lastSecValueCount = 0;
  5823. }
  5824. };
  5825. return PerfCounter;
  5826. }());
  5827. BABYLON.PerfCounter = PerfCounter;
  5828. /**
  5829. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5830. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5831. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5832. * @param name The name of the class, case should be preserved
  5833. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5834. */
  5835. function className(name, module) {
  5836. return function (target) {
  5837. target["__bjsclassName__"] = name;
  5838. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5839. };
  5840. }
  5841. BABYLON.className = className;
  5842. /**
  5843. * An implementation of a loop for asynchronous functions.
  5844. */
  5845. var AsyncLoop = (function () {
  5846. /**
  5847. * Constroctor.
  5848. * @param iterations the number of iterations.
  5849. * @param _fn the function to run each iteration
  5850. * @param _successCallback the callback that will be called upon succesful execution
  5851. * @param offset starting offset.
  5852. */
  5853. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5854. if (offset === void 0) { offset = 0; }
  5855. this.iterations = iterations;
  5856. this._fn = _fn;
  5857. this._successCallback = _successCallback;
  5858. this.index = offset - 1;
  5859. this._done = false;
  5860. }
  5861. /**
  5862. * Execute the next iteration. Must be called after the last iteration was finished.
  5863. */
  5864. AsyncLoop.prototype.executeNext = function () {
  5865. if (!this._done) {
  5866. if (this.index + 1 < this.iterations) {
  5867. ++this.index;
  5868. this._fn(this);
  5869. }
  5870. else {
  5871. this.breakLoop();
  5872. }
  5873. }
  5874. };
  5875. /**
  5876. * Break the loop and run the success callback.
  5877. */
  5878. AsyncLoop.prototype.breakLoop = function () {
  5879. this._done = true;
  5880. this._successCallback();
  5881. };
  5882. /**
  5883. * Helper function
  5884. */
  5885. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5886. if (offset === void 0) { offset = 0; }
  5887. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5888. loop.executeNext();
  5889. return loop;
  5890. };
  5891. /**
  5892. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5893. * @param iterations total number of iterations
  5894. * @param syncedIterations number of synchronous iterations in each async iteration.
  5895. * @param fn the function to call each iteration.
  5896. * @param callback a success call back that will be called when iterating stops.
  5897. * @param breakFunction a break condition (optional)
  5898. * @param timeout timeout settings for the setTimeout function. default - 0.
  5899. * @constructor
  5900. */
  5901. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5902. if (timeout === void 0) { timeout = 0; }
  5903. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5904. if (breakFunction && breakFunction())
  5905. loop.breakLoop();
  5906. else {
  5907. setTimeout(function () {
  5908. for (var i = 0; i < syncedIterations; ++i) {
  5909. var iteration = (loop.index * syncedIterations) + i;
  5910. if (iteration >= iterations)
  5911. break;
  5912. fn(iteration);
  5913. if (breakFunction && breakFunction()) {
  5914. loop.breakLoop();
  5915. break;
  5916. }
  5917. }
  5918. loop.executeNext();
  5919. }, timeout);
  5920. }
  5921. }, callback);
  5922. };
  5923. return AsyncLoop;
  5924. }());
  5925. BABYLON.AsyncLoop = AsyncLoop;
  5926. })(BABYLON || (BABYLON = {}));
  5927. //# sourceMappingURL=babylon.tools.js.map
  5928. var BABYLON;
  5929. (function (BABYLON) {
  5930. var Internals;
  5931. (function (Internals) {
  5932. var _AlphaState = (function () {
  5933. /**
  5934. * Initializes the state.
  5935. */
  5936. function _AlphaState() {
  5937. this._isAlphaBlendDirty = false;
  5938. this._isBlendFunctionParametersDirty = false;
  5939. this._alphaBlend = false;
  5940. this._blendFunctionParameters = new Array(4);
  5941. this.reset();
  5942. }
  5943. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5944. get: function () {
  5945. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5946. },
  5947. enumerable: true,
  5948. configurable: true
  5949. });
  5950. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5951. get: function () {
  5952. return this._alphaBlend;
  5953. },
  5954. set: function (value) {
  5955. if (this._alphaBlend === value) {
  5956. return;
  5957. }
  5958. this._alphaBlend = value;
  5959. this._isAlphaBlendDirty = true;
  5960. },
  5961. enumerable: true,
  5962. configurable: true
  5963. });
  5964. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5965. if (this._blendFunctionParameters[0] === value0 &&
  5966. this._blendFunctionParameters[1] === value1 &&
  5967. this._blendFunctionParameters[2] === value2 &&
  5968. this._blendFunctionParameters[3] === value3) {
  5969. return;
  5970. }
  5971. this._blendFunctionParameters[0] = value0;
  5972. this._blendFunctionParameters[1] = value1;
  5973. this._blendFunctionParameters[2] = value2;
  5974. this._blendFunctionParameters[3] = value3;
  5975. this._isBlendFunctionParametersDirty = true;
  5976. };
  5977. _AlphaState.prototype.reset = function () {
  5978. this._alphaBlend = false;
  5979. this._blendFunctionParameters[0] = null;
  5980. this._blendFunctionParameters[1] = null;
  5981. this._blendFunctionParameters[2] = null;
  5982. this._blendFunctionParameters[3] = null;
  5983. this._isAlphaBlendDirty = true;
  5984. this._isBlendFunctionParametersDirty = false;
  5985. };
  5986. _AlphaState.prototype.apply = function (gl) {
  5987. if (!this.isDirty) {
  5988. return;
  5989. }
  5990. // Alpha blend
  5991. if (this._isAlphaBlendDirty) {
  5992. if (this._alphaBlend) {
  5993. gl.enable(gl.BLEND);
  5994. }
  5995. else {
  5996. gl.disable(gl.BLEND);
  5997. }
  5998. this._isAlphaBlendDirty = false;
  5999. }
  6000. // Alpha function
  6001. if (this._isBlendFunctionParametersDirty) {
  6002. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6003. this._isBlendFunctionParametersDirty = false;
  6004. }
  6005. };
  6006. return _AlphaState;
  6007. }());
  6008. Internals._AlphaState = _AlphaState;
  6009. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6010. })(BABYLON || (BABYLON = {}));
  6011. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6012. var BABYLON;
  6013. (function (BABYLON) {
  6014. var Internals;
  6015. (function (Internals) {
  6016. var _DepthCullingState = (function () {
  6017. /**
  6018. * Initializes the state.
  6019. */
  6020. function _DepthCullingState() {
  6021. this._isDepthTestDirty = false;
  6022. this._isDepthMaskDirty = false;
  6023. this._isDepthFuncDirty = false;
  6024. this._isCullFaceDirty = false;
  6025. this._isCullDirty = false;
  6026. this._isZOffsetDirty = false;
  6027. this.reset();
  6028. }
  6029. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6030. get: function () {
  6031. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6032. },
  6033. enumerable: true,
  6034. configurable: true
  6035. });
  6036. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6037. get: function () {
  6038. return this._zOffset;
  6039. },
  6040. set: function (value) {
  6041. if (this._zOffset === value) {
  6042. return;
  6043. }
  6044. this._zOffset = value;
  6045. this._isZOffsetDirty = true;
  6046. },
  6047. enumerable: true,
  6048. configurable: true
  6049. });
  6050. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6051. get: function () {
  6052. return this._cullFace;
  6053. },
  6054. set: function (value) {
  6055. if (this._cullFace === value) {
  6056. return;
  6057. }
  6058. this._cullFace = value;
  6059. this._isCullFaceDirty = true;
  6060. },
  6061. enumerable: true,
  6062. configurable: true
  6063. });
  6064. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6065. get: function () {
  6066. return this._cull;
  6067. },
  6068. set: function (value) {
  6069. if (this._cull === value) {
  6070. return;
  6071. }
  6072. this._cull = value;
  6073. this._isCullDirty = true;
  6074. },
  6075. enumerable: true,
  6076. configurable: true
  6077. });
  6078. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6079. get: function () {
  6080. return this._depthFunc;
  6081. },
  6082. set: function (value) {
  6083. if (this._depthFunc === value) {
  6084. return;
  6085. }
  6086. this._depthFunc = value;
  6087. this._isDepthFuncDirty = true;
  6088. },
  6089. enumerable: true,
  6090. configurable: true
  6091. });
  6092. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6093. get: function () {
  6094. return this._depthMask;
  6095. },
  6096. set: function (value) {
  6097. if (this._depthMask === value) {
  6098. return;
  6099. }
  6100. this._depthMask = value;
  6101. this._isDepthMaskDirty = true;
  6102. },
  6103. enumerable: true,
  6104. configurable: true
  6105. });
  6106. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6107. get: function () {
  6108. return this._depthTest;
  6109. },
  6110. set: function (value) {
  6111. if (this._depthTest === value) {
  6112. return;
  6113. }
  6114. this._depthTest = value;
  6115. this._isDepthTestDirty = true;
  6116. },
  6117. enumerable: true,
  6118. configurable: true
  6119. });
  6120. _DepthCullingState.prototype.reset = function () {
  6121. this._depthMask = true;
  6122. this._depthTest = true;
  6123. this._depthFunc = null;
  6124. this._cullFace = null;
  6125. this._cull = null;
  6126. this._zOffset = 0;
  6127. this._isDepthTestDirty = true;
  6128. this._isDepthMaskDirty = true;
  6129. this._isDepthFuncDirty = false;
  6130. this._isCullFaceDirty = false;
  6131. this._isCullDirty = false;
  6132. this._isZOffsetDirty = false;
  6133. };
  6134. _DepthCullingState.prototype.apply = function (gl) {
  6135. if (!this.isDirty) {
  6136. return;
  6137. }
  6138. // Cull
  6139. if (this._isCullDirty) {
  6140. if (this.cull) {
  6141. gl.enable(gl.CULL_FACE);
  6142. }
  6143. else {
  6144. gl.disable(gl.CULL_FACE);
  6145. }
  6146. this._isCullDirty = false;
  6147. }
  6148. // Cull face
  6149. if (this._isCullFaceDirty) {
  6150. gl.cullFace(this.cullFace);
  6151. this._isCullFaceDirty = false;
  6152. }
  6153. // Depth mask
  6154. if (this._isDepthMaskDirty) {
  6155. gl.depthMask(this.depthMask);
  6156. this._isDepthMaskDirty = false;
  6157. }
  6158. // Depth test
  6159. if (this._isDepthTestDirty) {
  6160. if (this.depthTest) {
  6161. gl.enable(gl.DEPTH_TEST);
  6162. }
  6163. else {
  6164. gl.disable(gl.DEPTH_TEST);
  6165. }
  6166. this._isDepthTestDirty = false;
  6167. }
  6168. // Depth func
  6169. if (this._isDepthFuncDirty) {
  6170. gl.depthFunc(this.depthFunc);
  6171. this._isDepthFuncDirty = false;
  6172. }
  6173. // zOffset
  6174. if (this._isZOffsetDirty) {
  6175. if (this.zOffset) {
  6176. gl.enable(gl.POLYGON_OFFSET_FILL);
  6177. gl.polygonOffset(this.zOffset, 0);
  6178. }
  6179. else {
  6180. gl.disable(gl.POLYGON_OFFSET_FILL);
  6181. }
  6182. this._isZOffsetDirty = false;
  6183. }
  6184. };
  6185. return _DepthCullingState;
  6186. }());
  6187. Internals._DepthCullingState = _DepthCullingState;
  6188. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6189. })(BABYLON || (BABYLON = {}));
  6190. //# sourceMappingURL=babylon.depthCullingState.js.map
  6191. var BABYLON;
  6192. (function (BABYLON) {
  6193. var Internals;
  6194. (function (Internals) {
  6195. var _StencilState = (function () {
  6196. function _StencilState() {
  6197. this._isStencilTestDirty = false;
  6198. this._isStencilMaskDirty = false;
  6199. this._isStencilFuncDirty = false;
  6200. this._isStencilOpDirty = false;
  6201. this.reset();
  6202. }
  6203. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6204. get: function () {
  6205. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6206. },
  6207. enumerable: true,
  6208. configurable: true
  6209. });
  6210. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6211. get: function () {
  6212. return this._stencilFunc;
  6213. },
  6214. set: function (value) {
  6215. if (this._stencilFunc === value) {
  6216. return;
  6217. }
  6218. this._stencilFunc = value;
  6219. this._isStencilFuncDirty = true;
  6220. },
  6221. enumerable: true,
  6222. configurable: true
  6223. });
  6224. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6225. get: function () {
  6226. return this._stencilFuncRef;
  6227. },
  6228. set: function (value) {
  6229. if (this._stencilFuncRef === value) {
  6230. return;
  6231. }
  6232. this._stencilFuncRef = value;
  6233. this._isStencilFuncDirty = true;
  6234. },
  6235. enumerable: true,
  6236. configurable: true
  6237. });
  6238. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6239. get: function () {
  6240. return this._stencilFuncMask;
  6241. },
  6242. set: function (value) {
  6243. if (this._stencilFuncMask === value) {
  6244. return;
  6245. }
  6246. this._stencilFuncMask = value;
  6247. this._isStencilFuncDirty = true;
  6248. },
  6249. enumerable: true,
  6250. configurable: true
  6251. });
  6252. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6253. get: function () {
  6254. return this._stencilOpStencilFail;
  6255. },
  6256. set: function (value) {
  6257. if (this._stencilOpStencilFail === value) {
  6258. return;
  6259. }
  6260. this._stencilOpStencilFail = value;
  6261. this._isStencilOpDirty = true;
  6262. },
  6263. enumerable: true,
  6264. configurable: true
  6265. });
  6266. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6267. get: function () {
  6268. return this._stencilOpDepthFail;
  6269. },
  6270. set: function (value) {
  6271. if (this._stencilOpDepthFail === value) {
  6272. return;
  6273. }
  6274. this._stencilOpDepthFail = value;
  6275. this._isStencilOpDirty = true;
  6276. },
  6277. enumerable: true,
  6278. configurable: true
  6279. });
  6280. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6281. get: function () {
  6282. return this._stencilOpStencilDepthPass;
  6283. },
  6284. set: function (value) {
  6285. if (this._stencilOpStencilDepthPass === value) {
  6286. return;
  6287. }
  6288. this._stencilOpStencilDepthPass = value;
  6289. this._isStencilOpDirty = true;
  6290. },
  6291. enumerable: true,
  6292. configurable: true
  6293. });
  6294. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6295. get: function () {
  6296. return this._stencilMask;
  6297. },
  6298. set: function (value) {
  6299. if (this._stencilMask === value) {
  6300. return;
  6301. }
  6302. this._stencilMask = value;
  6303. this._isStencilMaskDirty = true;
  6304. },
  6305. enumerable: true,
  6306. configurable: true
  6307. });
  6308. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6309. get: function () {
  6310. return this._stencilTest;
  6311. },
  6312. set: function (value) {
  6313. if (this._stencilTest === value) {
  6314. return;
  6315. }
  6316. this._stencilTest = value;
  6317. this._isStencilTestDirty = true;
  6318. },
  6319. enumerable: true,
  6320. configurable: true
  6321. });
  6322. _StencilState.prototype.reset = function () {
  6323. this._stencilTest = false;
  6324. this._stencilMask = 0xFF;
  6325. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6326. this._stencilFuncRef = 1;
  6327. this._stencilFuncMask = 0xFF;
  6328. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6329. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6330. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6331. this._isStencilTestDirty = true;
  6332. this._isStencilMaskDirty = true;
  6333. this._isStencilFuncDirty = true;
  6334. this._isStencilOpDirty = true;
  6335. };
  6336. _StencilState.prototype.apply = function (gl) {
  6337. if (!this.isDirty) {
  6338. return;
  6339. }
  6340. // Stencil test
  6341. if (this._isStencilTestDirty) {
  6342. if (this.stencilTest) {
  6343. gl.enable(gl.STENCIL_TEST);
  6344. }
  6345. else {
  6346. gl.disable(gl.STENCIL_TEST);
  6347. }
  6348. this._isStencilTestDirty = false;
  6349. }
  6350. // Stencil mask
  6351. if (this._isStencilMaskDirty) {
  6352. gl.stencilMask(this.stencilMask);
  6353. this._isStencilMaskDirty = false;
  6354. }
  6355. // Stencil func
  6356. if (this._isStencilFuncDirty) {
  6357. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6358. this._isStencilFuncDirty = false;
  6359. }
  6360. // Stencil op
  6361. if (this._isStencilOpDirty) {
  6362. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6363. this._isStencilOpDirty = false;
  6364. }
  6365. };
  6366. return _StencilState;
  6367. }());
  6368. Internals._StencilState = _StencilState;
  6369. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6370. })(BABYLON || (BABYLON = {}));
  6371. //# sourceMappingURL=babylon.stencilState.js.map
  6372. var BABYLON;
  6373. (function (BABYLON) {
  6374. var compileShader = function (gl, source, type, defines, shaderVersion) {
  6375. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6376. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  6377. gl.compileShader(shader);
  6378. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6379. throw new Error(gl.getShaderInfoLog(shader));
  6380. }
  6381. return shader;
  6382. };
  6383. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6384. var magFilter = gl.NEAREST;
  6385. var minFilter = gl.NEAREST;
  6386. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6387. magFilter = gl.LINEAR;
  6388. if (generateMipMaps) {
  6389. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6390. }
  6391. else {
  6392. minFilter = gl.LINEAR;
  6393. }
  6394. }
  6395. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6396. magFilter = gl.LINEAR;
  6397. if (generateMipMaps) {
  6398. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6399. }
  6400. else {
  6401. minFilter = gl.LINEAR;
  6402. }
  6403. }
  6404. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6405. magFilter = gl.NEAREST;
  6406. if (generateMipMaps) {
  6407. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6408. }
  6409. else {
  6410. minFilter = gl.NEAREST;
  6411. }
  6412. }
  6413. return {
  6414. min: minFilter,
  6415. mag: magFilter
  6416. };
  6417. };
  6418. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6419. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6420. var engine = scene.getEngine();
  6421. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6422. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6423. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6424. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6425. texture._baseWidth = width;
  6426. texture._baseHeight = height;
  6427. texture._width = potWidth;
  6428. texture._height = potHeight;
  6429. texture.isReady = true;
  6430. processFunction(potWidth, potHeight);
  6431. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6432. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6433. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6434. if (!noMipmap && !isCompressed) {
  6435. gl.generateMipmap(gl.TEXTURE_2D);
  6436. }
  6437. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6438. engine.resetTextureCache();
  6439. scene._removePendingData(texture);
  6440. texture.onLoadedCallbacks.forEach(function (callback) {
  6441. callback();
  6442. });
  6443. texture.onLoadedCallbacks = [];
  6444. };
  6445. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6446. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6447. var img;
  6448. var onload = function () {
  6449. loadedImages[index] = img;
  6450. loadedImages._internalCount++;
  6451. scene._removePendingData(img);
  6452. if (loadedImages._internalCount === 6) {
  6453. onfinish(loadedImages);
  6454. }
  6455. };
  6456. var onerror = function () {
  6457. scene._removePendingData(img);
  6458. if (onErrorCallBack) {
  6459. onErrorCallBack();
  6460. }
  6461. };
  6462. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6463. scene._addPendingData(img);
  6464. };
  6465. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6466. if (onError === void 0) { onError = null; }
  6467. var loadedImages = [];
  6468. loadedImages._internalCount = 0;
  6469. for (var index = 0; index < 6; index++) {
  6470. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6471. }
  6472. };
  6473. var InstancingAttributeInfo = (function () {
  6474. function InstancingAttributeInfo() {
  6475. }
  6476. return InstancingAttributeInfo;
  6477. }());
  6478. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6479. var EngineCapabilities = (function () {
  6480. function EngineCapabilities() {
  6481. }
  6482. return EngineCapabilities;
  6483. }());
  6484. BABYLON.EngineCapabilities = EngineCapabilities;
  6485. /**
  6486. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6487. */
  6488. var Engine = (function () {
  6489. /**
  6490. * @constructor
  6491. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6492. * @param {boolean} [antialias] - enable antialias
  6493. * @param options - further options to be sent to the getContext function
  6494. */
  6495. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6496. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  6497. var _this = this;
  6498. // Public members
  6499. this.isFullscreen = false;
  6500. this.isPointerLock = false;
  6501. this.cullBackFaces = true;
  6502. this.renderEvenInBackground = true;
  6503. // To enable/disable IDB support and avoid XHR on .manifest
  6504. this.enableOfflineSupport = true;
  6505. this.scenes = new Array();
  6506. this._windowIsBackground = false;
  6507. this._webGLVersion = 1.0;
  6508. this._badOS = false;
  6509. this._drawCalls = new BABYLON.PerfCounter();
  6510. this._renderingQueueLaunched = false;
  6511. this._activeRenderLoops = [];
  6512. // FPS
  6513. this.fpsRange = 60;
  6514. this.previousFramesDuration = [];
  6515. this.fps = 60;
  6516. this.deltaTime = 0;
  6517. // States
  6518. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6519. this._stencilState = new BABYLON.Internals._StencilState();
  6520. this._alphaState = new BABYLON.Internals._AlphaState();
  6521. this._alphaMode = Engine.ALPHA_DISABLE;
  6522. // Cache
  6523. this._loadedTexturesCache = new Array();
  6524. this._maxTextureChannels = 16;
  6525. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6526. this._compiledEffects = {};
  6527. this._vertexAttribArraysEnabled = [];
  6528. this._uintIndicesCurrentlySet = false;
  6529. this._currentBoundBuffer = new Array();
  6530. this._currentBufferPointers = [];
  6531. this._currentInstanceLocations = new Array();
  6532. this._currentInstanceBuffers = new Array();
  6533. this._vaoRecordInProgress = false;
  6534. this._mustWipeVertexAttributes = false;
  6535. // Hardware supported Compressed Textures
  6536. this._texturesSupported = new Array();
  6537. this._onVRFullScreenTriggered = function () {
  6538. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6539. //get the old size before we change
  6540. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6541. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6542. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6543. //But actually, no browser follow the specs...
  6544. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6545. //get the width and height, change the render size
  6546. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6547. var width, height;
  6548. _this.setHardwareScalingLevel(1);
  6549. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6550. }
  6551. else {
  6552. //When the specs are implemented, need to uncomment this.
  6553. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6554. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6555. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6556. _this._vrDisplayEnabled = undefined;
  6557. }
  6558. };
  6559. this._renderingCanvas = canvas;
  6560. this._externalData = new BABYLON.StringDictionary();
  6561. options = options || {};
  6562. if (antialias != null) {
  6563. options.antialias = antialias;
  6564. }
  6565. if (options.preserveDrawingBuffer === undefined) {
  6566. options.preserveDrawingBuffer = false;
  6567. }
  6568. // GL
  6569. if (!options.disableWebGL2Support) {
  6570. try {
  6571. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6572. if (this._gl) {
  6573. this._webGLVersion = 2.0;
  6574. }
  6575. }
  6576. catch (e) {
  6577. }
  6578. }
  6579. if (!this._gl) {
  6580. if (!canvas) {
  6581. throw new Error("The provided canvas is null or undefined.");
  6582. }
  6583. try {
  6584. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6585. }
  6586. catch (e) {
  6587. throw new Error("WebGL not supported");
  6588. }
  6589. }
  6590. if (!this._gl) {
  6591. throw new Error("WebGL not supported");
  6592. }
  6593. this._onBlur = function () {
  6594. _this._windowIsBackground = true;
  6595. };
  6596. this._onFocus = function () {
  6597. _this._windowIsBackground = false;
  6598. };
  6599. window.addEventListener("blur", this._onBlur);
  6600. window.addEventListener("focus", this._onFocus);
  6601. // Viewport
  6602. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6603. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6604. this.resize();
  6605. // Caps
  6606. this._isStencilEnable = options.stencil;
  6607. this._caps = new EngineCapabilities();
  6608. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6609. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6610. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6611. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6612. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6613. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  6614. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  6615. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  6616. // Infos
  6617. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6618. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6619. if (rendererInfo != null) {
  6620. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6621. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6622. }
  6623. if (!this._glVendor) {
  6624. this._glVendor = "Unknown vendor";
  6625. }
  6626. if (!this._glRenderer) {
  6627. this._glRenderer = "Unknown renderer";
  6628. }
  6629. // Extensions
  6630. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  6631. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  6632. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  6633. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  6634. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  6635. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  6636. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  6637. this._caps.atc = this._gl.getExtension('WEBGL_compressed_texture_atc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_atc');
  6638. this._caps.textureAnisotropicFilterExtension = this._gl.getExtension('EXT_texture_filter_anisotropic') || this._gl.getExtension('WEBKIT_EXT_texture_filter_anisotropic') || this._gl.getExtension('MOZ_EXT_texture_filter_anisotropic');
  6639. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6640. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  6641. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  6642. this._caps.highPrecisionShaderSupported = true;
  6643. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  6644. // Checks if some of the format renders first to allow the use of webgl inspector.
  6645. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  6646. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  6647. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  6648. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  6649. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  6650. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  6651. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  6652. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  6653. // Vertex array object
  6654. if (this._webGLVersion > 1) {
  6655. this._caps.vertexArrayObject = true;
  6656. }
  6657. else {
  6658. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  6659. if (vertexArrayObjectExtension != null) {
  6660. this._caps.vertexArrayObject = true;
  6661. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  6662. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  6663. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  6664. }
  6665. else {
  6666. this._caps.vertexArrayObject = false;
  6667. }
  6668. }
  6669. // Instances count
  6670. if (this._webGLVersion > 1) {
  6671. this._caps.instancedArrays = true;
  6672. }
  6673. else {
  6674. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  6675. if (instanceExtension != null) {
  6676. this._caps.instancedArrays = true;
  6677. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  6678. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  6679. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  6680. }
  6681. else {
  6682. this._caps.instancedArrays = false;
  6683. }
  6684. }
  6685. // Intelligently add supported compressed formats in order to check for.
  6686. // Check for ASTC support first as it is most powerful and to be very cross platform.
  6687. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  6688. // Likely no hardware which supports both PVR & DXT, so order matters little.
  6689. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  6690. // ATC before ETC1, since both old (widely supported), but ATC supports alpha, but ETC1 does not
  6691. if (this._caps.astc)
  6692. this.texturesSupported.push('-astc.ktx');
  6693. if (this._caps.s3tc)
  6694. this.texturesSupported.push('-dxt.ktx');
  6695. if (this._caps.pvrtc)
  6696. this.texturesSupported.push('-pvrtc.ktx');
  6697. if (this._caps.etc2)
  6698. this.texturesSupported.push('-etc2.ktx');
  6699. if (this._caps.atc)
  6700. this.texturesSupported.push('-atc.ktx');
  6701. if (this._caps.etc1)
  6702. this.texturesSupported.push('-etc1.ktx');
  6703. if (this._gl.getShaderPrecisionFormat) {
  6704. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6705. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6706. }
  6707. // Depth buffer
  6708. this.setDepthBuffer(true);
  6709. this.setDepthFunctionToLessOrEqual();
  6710. this.setDepthWrite(true);
  6711. // Fullscreen
  6712. this._onFullscreenChange = function () {
  6713. if (document.fullscreen !== undefined) {
  6714. _this.isFullscreen = document.fullscreen;
  6715. }
  6716. else if (document.mozFullScreen !== undefined) {
  6717. _this.isFullscreen = document.mozFullScreen;
  6718. }
  6719. else if (document.webkitIsFullScreen !== undefined) {
  6720. _this.isFullscreen = document.webkitIsFullScreen;
  6721. }
  6722. else if (document.msIsFullScreen !== undefined) {
  6723. _this.isFullscreen = document.msIsFullScreen;
  6724. }
  6725. // Pointer lock
  6726. if (_this.isFullscreen && _this._pointerLockRequested) {
  6727. canvas.requestPointerLock = canvas.requestPointerLock ||
  6728. canvas.msRequestPointerLock ||
  6729. canvas.mozRequestPointerLock ||
  6730. canvas.webkitRequestPointerLock;
  6731. if (canvas.requestPointerLock) {
  6732. canvas.requestPointerLock();
  6733. }
  6734. }
  6735. };
  6736. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6737. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6738. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6739. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6740. // Pointer lock
  6741. this._onPointerLockChange = function () {
  6742. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6743. document.webkitPointerLockElement === canvas ||
  6744. document.msPointerLockElement === canvas ||
  6745. document.pointerLockElement === canvas);
  6746. };
  6747. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6748. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6749. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6750. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6751. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6752. Engine.audioEngine = new BABYLON.AudioEngine();
  6753. }
  6754. //default loading screen
  6755. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6756. //Load WebVR Devices
  6757. if (options.autoEnableWebVR) {
  6758. this.initWebVR();
  6759. }
  6760. //Detect if we are running on a faulty buggy OS.
  6761. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6762. //ua sniffing is the tool of the devil.
  6763. this._badOS = regexp.test(navigator.userAgent);
  6764. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6765. }
  6766. Object.defineProperty(Engine, "NEVER", {
  6767. get: function () {
  6768. return Engine._NEVER;
  6769. },
  6770. enumerable: true,
  6771. configurable: true
  6772. });
  6773. Object.defineProperty(Engine, "ALWAYS", {
  6774. get: function () {
  6775. return Engine._ALWAYS;
  6776. },
  6777. enumerable: true,
  6778. configurable: true
  6779. });
  6780. Object.defineProperty(Engine, "LESS", {
  6781. get: function () {
  6782. return Engine._LESS;
  6783. },
  6784. enumerable: true,
  6785. configurable: true
  6786. });
  6787. Object.defineProperty(Engine, "EQUAL", {
  6788. get: function () {
  6789. return Engine._EQUAL;
  6790. },
  6791. enumerable: true,
  6792. configurable: true
  6793. });
  6794. Object.defineProperty(Engine, "LEQUAL", {
  6795. get: function () {
  6796. return Engine._LEQUAL;
  6797. },
  6798. enumerable: true,
  6799. configurable: true
  6800. });
  6801. Object.defineProperty(Engine, "GREATER", {
  6802. get: function () {
  6803. return Engine._GREATER;
  6804. },
  6805. enumerable: true,
  6806. configurable: true
  6807. });
  6808. Object.defineProperty(Engine, "GEQUAL", {
  6809. get: function () {
  6810. return Engine._GEQUAL;
  6811. },
  6812. enumerable: true,
  6813. configurable: true
  6814. });
  6815. Object.defineProperty(Engine, "NOTEQUAL", {
  6816. get: function () {
  6817. return Engine._NOTEQUAL;
  6818. },
  6819. enumerable: true,
  6820. configurable: true
  6821. });
  6822. Object.defineProperty(Engine, "KEEP", {
  6823. get: function () {
  6824. return Engine._KEEP;
  6825. },
  6826. enumerable: true,
  6827. configurable: true
  6828. });
  6829. Object.defineProperty(Engine, "REPLACE", {
  6830. get: function () {
  6831. return Engine._REPLACE;
  6832. },
  6833. enumerable: true,
  6834. configurable: true
  6835. });
  6836. Object.defineProperty(Engine, "INCR", {
  6837. get: function () {
  6838. return Engine._INCR;
  6839. },
  6840. enumerable: true,
  6841. configurable: true
  6842. });
  6843. Object.defineProperty(Engine, "DECR", {
  6844. get: function () {
  6845. return Engine._DECR;
  6846. },
  6847. enumerable: true,
  6848. configurable: true
  6849. });
  6850. Object.defineProperty(Engine, "INVERT", {
  6851. get: function () {
  6852. return Engine._INVERT;
  6853. },
  6854. enumerable: true,
  6855. configurable: true
  6856. });
  6857. Object.defineProperty(Engine, "INCR_WRAP", {
  6858. get: function () {
  6859. return Engine._INCR_WRAP;
  6860. },
  6861. enumerable: true,
  6862. configurable: true
  6863. });
  6864. Object.defineProperty(Engine, "DECR_WRAP", {
  6865. get: function () {
  6866. return Engine._DECR_WRAP;
  6867. },
  6868. enumerable: true,
  6869. configurable: true
  6870. });
  6871. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6872. get: function () {
  6873. return Engine._ALPHA_DISABLE;
  6874. },
  6875. enumerable: true,
  6876. configurable: true
  6877. });
  6878. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6879. get: function () {
  6880. return Engine._ALPHA_ONEONE;
  6881. },
  6882. enumerable: true,
  6883. configurable: true
  6884. });
  6885. Object.defineProperty(Engine, "ALPHA_ADD", {
  6886. get: function () {
  6887. return Engine._ALPHA_ADD;
  6888. },
  6889. enumerable: true,
  6890. configurable: true
  6891. });
  6892. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6893. get: function () {
  6894. return Engine._ALPHA_COMBINE;
  6895. },
  6896. enumerable: true,
  6897. configurable: true
  6898. });
  6899. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6900. get: function () {
  6901. return Engine._ALPHA_SUBTRACT;
  6902. },
  6903. enumerable: true,
  6904. configurable: true
  6905. });
  6906. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6907. get: function () {
  6908. return Engine._ALPHA_MULTIPLY;
  6909. },
  6910. enumerable: true,
  6911. configurable: true
  6912. });
  6913. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6914. get: function () {
  6915. return Engine._ALPHA_MAXIMIZED;
  6916. },
  6917. enumerable: true,
  6918. configurable: true
  6919. });
  6920. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  6921. get: function () {
  6922. return Engine._ALPHA_PREMULTIPLIED;
  6923. },
  6924. enumerable: true,
  6925. configurable: true
  6926. });
  6927. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6928. get: function () {
  6929. return Engine._DELAYLOADSTATE_NONE;
  6930. },
  6931. enumerable: true,
  6932. configurable: true
  6933. });
  6934. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6935. get: function () {
  6936. return Engine._DELAYLOADSTATE_LOADED;
  6937. },
  6938. enumerable: true,
  6939. configurable: true
  6940. });
  6941. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6942. get: function () {
  6943. return Engine._DELAYLOADSTATE_LOADING;
  6944. },
  6945. enumerable: true,
  6946. configurable: true
  6947. });
  6948. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6949. get: function () {
  6950. return Engine._DELAYLOADSTATE_NOTLOADED;
  6951. },
  6952. enumerable: true,
  6953. configurable: true
  6954. });
  6955. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6956. get: function () {
  6957. return Engine._TEXTUREFORMAT_ALPHA;
  6958. },
  6959. enumerable: true,
  6960. configurable: true
  6961. });
  6962. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6963. get: function () {
  6964. return Engine._TEXTUREFORMAT_LUMINANCE;
  6965. },
  6966. enumerable: true,
  6967. configurable: true
  6968. });
  6969. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6970. get: function () {
  6971. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6972. },
  6973. enumerable: true,
  6974. configurable: true
  6975. });
  6976. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6977. get: function () {
  6978. return Engine._TEXTUREFORMAT_RGB;
  6979. },
  6980. enumerable: true,
  6981. configurable: true
  6982. });
  6983. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6984. get: function () {
  6985. return Engine._TEXTUREFORMAT_RGBA;
  6986. },
  6987. enumerable: true,
  6988. configurable: true
  6989. });
  6990. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6991. get: function () {
  6992. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6993. },
  6994. enumerable: true,
  6995. configurable: true
  6996. });
  6997. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6998. get: function () {
  6999. return Engine._TEXTURETYPE_FLOAT;
  7000. },
  7001. enumerable: true,
  7002. configurable: true
  7003. });
  7004. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7005. get: function () {
  7006. return Engine._TEXTURETYPE_HALF_FLOAT;
  7007. },
  7008. enumerable: true,
  7009. configurable: true
  7010. });
  7011. Object.defineProperty(Engine, "Version", {
  7012. get: function () {
  7013. return "2.6-alpha";
  7014. },
  7015. enumerable: true,
  7016. configurable: true
  7017. });
  7018. Object.defineProperty(Engine.prototype, "texturesSupported", {
  7019. get: function () {
  7020. return this._texturesSupported;
  7021. },
  7022. enumerable: true,
  7023. configurable: true
  7024. });
  7025. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  7026. get: function () {
  7027. return this._textureFormatInUse;
  7028. },
  7029. enumerable: true,
  7030. configurable: true
  7031. });
  7032. Object.defineProperty(Engine.prototype, "webGLVersion", {
  7033. get: function () {
  7034. return this._webGLVersion;
  7035. },
  7036. enumerable: true,
  7037. configurable: true
  7038. });
  7039. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  7040. /**
  7041. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7042. */
  7043. get: function () {
  7044. return this._isStencilEnable;
  7045. },
  7046. enumerable: true,
  7047. configurable: true
  7048. });
  7049. Engine.prototype._prepareWorkingCanvas = function () {
  7050. if (this._workingCanvas) {
  7051. return;
  7052. }
  7053. this._workingCanvas = document.createElement("canvas");
  7054. this._workingContext = this._workingCanvas.getContext("2d");
  7055. };
  7056. Engine.prototype.resetTextureCache = function () {
  7057. for (var index = 0; index < this._maxTextureChannels; index++) {
  7058. this._activeTexturesCache[index] = null;
  7059. }
  7060. };
  7061. Engine.prototype.getGlInfo = function () {
  7062. return {
  7063. vendor: this._glVendor,
  7064. renderer: this._glRenderer,
  7065. version: this._glVersion
  7066. };
  7067. };
  7068. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7069. if (useScreen === void 0) { useScreen = false; }
  7070. var viewport = camera.viewport;
  7071. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7072. };
  7073. Engine.prototype.getRenderWidth = function (useScreen) {
  7074. if (useScreen === void 0) { useScreen = false; }
  7075. if (!useScreen && this._currentRenderTarget) {
  7076. return this._currentRenderTarget._width;
  7077. }
  7078. return this._renderingCanvas.width;
  7079. };
  7080. Engine.prototype.getRenderHeight = function (useScreen) {
  7081. if (useScreen === void 0) { useScreen = false; }
  7082. if (!useScreen && this._currentRenderTarget) {
  7083. return this._currentRenderTarget._height;
  7084. }
  7085. return this._renderingCanvas.height;
  7086. };
  7087. Engine.prototype.getRenderingCanvas = function () {
  7088. return this._renderingCanvas;
  7089. };
  7090. Engine.prototype.getRenderingCanvasClientRect = function () {
  7091. return this._renderingCanvas.getBoundingClientRect();
  7092. };
  7093. Engine.prototype.setHardwareScalingLevel = function (level) {
  7094. this._hardwareScalingLevel = level;
  7095. this.resize();
  7096. };
  7097. Engine.prototype.getHardwareScalingLevel = function () {
  7098. return this._hardwareScalingLevel;
  7099. };
  7100. Engine.prototype.getLoadedTexturesCache = function () {
  7101. return this._loadedTexturesCache;
  7102. };
  7103. Engine.prototype.getCaps = function () {
  7104. return this._caps;
  7105. };
  7106. Object.defineProperty(Engine.prototype, "drawCalls", {
  7107. get: function () {
  7108. return this._drawCalls.current;
  7109. },
  7110. enumerable: true,
  7111. configurable: true
  7112. });
  7113. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7114. get: function () {
  7115. return this._drawCalls;
  7116. },
  7117. enumerable: true,
  7118. configurable: true
  7119. });
  7120. Engine.prototype.getDepthFunction = function () {
  7121. return this._depthCullingState.depthFunc;
  7122. };
  7123. Engine.prototype.setDepthFunction = function (depthFunc) {
  7124. this._depthCullingState.depthFunc = depthFunc;
  7125. };
  7126. Engine.prototype.setDepthFunctionToGreater = function () {
  7127. this._depthCullingState.depthFunc = this._gl.GREATER;
  7128. };
  7129. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7130. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7131. };
  7132. Engine.prototype.setDepthFunctionToLess = function () {
  7133. this._depthCullingState.depthFunc = this._gl.LESS;
  7134. };
  7135. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7136. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7137. };
  7138. Engine.prototype.getStencilBuffer = function () {
  7139. return this._stencilState.stencilTest;
  7140. };
  7141. Engine.prototype.setStencilBuffer = function (enable) {
  7142. this._stencilState.stencilTest = enable;
  7143. };
  7144. Engine.prototype.getStencilMask = function () {
  7145. return this._stencilState.stencilMask;
  7146. };
  7147. Engine.prototype.setStencilMask = function (mask) {
  7148. this._stencilState.stencilMask = mask;
  7149. };
  7150. Engine.prototype.getStencilFunction = function () {
  7151. return this._stencilState.stencilFunc;
  7152. };
  7153. Engine.prototype.getStencilFunctionReference = function () {
  7154. return this._stencilState.stencilFuncRef;
  7155. };
  7156. Engine.prototype.getStencilFunctionMask = function () {
  7157. return this._stencilState.stencilFuncMask;
  7158. };
  7159. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7160. this._stencilState.stencilFunc = stencilFunc;
  7161. };
  7162. Engine.prototype.setStencilFunctionReference = function (reference) {
  7163. this._stencilState.stencilFuncRef = reference;
  7164. };
  7165. Engine.prototype.setStencilFunctionMask = function (mask) {
  7166. this._stencilState.stencilFuncMask = mask;
  7167. };
  7168. Engine.prototype.getStencilOperationFail = function () {
  7169. return this._stencilState.stencilOpStencilFail;
  7170. };
  7171. Engine.prototype.getStencilOperationDepthFail = function () {
  7172. return this._stencilState.stencilOpDepthFail;
  7173. };
  7174. Engine.prototype.getStencilOperationPass = function () {
  7175. return this._stencilState.stencilOpStencilDepthPass;
  7176. };
  7177. Engine.prototype.setStencilOperationFail = function (operation) {
  7178. this._stencilState.stencilOpStencilFail = operation;
  7179. };
  7180. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7181. this._stencilState.stencilOpDepthFail = operation;
  7182. };
  7183. Engine.prototype.setStencilOperationPass = function (operation) {
  7184. this._stencilState.stencilOpStencilDepthPass = operation;
  7185. };
  7186. /**
  7187. * stop executing a render loop function and remove it from the execution array
  7188. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7189. */
  7190. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7191. if (!renderFunction) {
  7192. this._activeRenderLoops = [];
  7193. return;
  7194. }
  7195. var index = this._activeRenderLoops.indexOf(renderFunction);
  7196. if (index >= 0) {
  7197. this._activeRenderLoops.splice(index, 1);
  7198. }
  7199. };
  7200. Engine.prototype._renderLoop = function () {
  7201. var shouldRender = true;
  7202. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7203. shouldRender = false;
  7204. }
  7205. if (shouldRender) {
  7206. // Start new frame
  7207. this.beginFrame();
  7208. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7209. var renderFunction = this._activeRenderLoops[index];
  7210. renderFunction();
  7211. }
  7212. // Present
  7213. this.endFrame();
  7214. }
  7215. if (this._activeRenderLoops.length > 0) {
  7216. // Register new frame
  7217. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7218. }
  7219. else {
  7220. this._renderingQueueLaunched = false;
  7221. }
  7222. };
  7223. /**
  7224. * Register and execute a render loop. The engine can have more than one render function.
  7225. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7226. * @example
  7227. * engine.runRenderLoop(function () {
  7228. * scene.render()
  7229. * })
  7230. */
  7231. Engine.prototype.runRenderLoop = function (renderFunction) {
  7232. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7233. return;
  7234. }
  7235. this._activeRenderLoops.push(renderFunction);
  7236. if (!this._renderingQueueLaunched) {
  7237. this._renderingQueueLaunched = true;
  7238. this._bindedRenderFunction = this._renderLoop.bind(this);
  7239. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7240. }
  7241. };
  7242. /**
  7243. * Toggle full screen mode.
  7244. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7245. * @param {any} options - an options object to be sent to the requestFullscreen function
  7246. */
  7247. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7248. if (this.isFullscreen) {
  7249. BABYLON.Tools.ExitFullscreen();
  7250. }
  7251. else {
  7252. this._pointerLockRequested = requestPointerLock;
  7253. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7254. }
  7255. };
  7256. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7257. if (stencil === void 0) { stencil = false; }
  7258. this.applyStates();
  7259. var mode = 0;
  7260. if (backBuffer && color) {
  7261. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  7262. mode |= this._gl.COLOR_BUFFER_BIT;
  7263. }
  7264. if (depth) {
  7265. this._gl.clearDepth(1.0);
  7266. mode |= this._gl.DEPTH_BUFFER_BIT;
  7267. }
  7268. if (stencil) {
  7269. this._gl.clearStencil(0);
  7270. mode |= this._gl.STENCIL_BUFFER_BIT;
  7271. }
  7272. this._gl.clear(mode);
  7273. };
  7274. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7275. var gl = this._gl;
  7276. // Save state
  7277. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7278. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7279. // Change state
  7280. gl.enable(gl.SCISSOR_TEST);
  7281. gl.scissor(x, y, width, height);
  7282. // Clear
  7283. this.clear(clearColor, true, true, true);
  7284. // Restore state
  7285. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7286. if (curScissor === true) {
  7287. gl.enable(gl.SCISSOR_TEST);
  7288. }
  7289. else {
  7290. gl.disable(gl.SCISSOR_TEST);
  7291. }
  7292. };
  7293. /**
  7294. * Set the WebGL's viewport
  7295. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7296. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7297. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7298. */
  7299. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7300. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7301. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7302. var x = viewport.x || 0;
  7303. var y = viewport.y || 0;
  7304. this._cachedViewport = viewport;
  7305. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7306. };
  7307. /**
  7308. * Directly set the WebGL Viewport
  7309. * The x, y, width & height are directly passed to the WebGL call
  7310. * @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.
  7311. */
  7312. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7313. var currentViewport = this._cachedViewport;
  7314. this._cachedViewport = null;
  7315. this._gl.viewport(x, y, width, height);
  7316. return currentViewport;
  7317. };
  7318. Engine.prototype.beginFrame = function () {
  7319. this._measureFps();
  7320. };
  7321. Engine.prototype.endFrame = function () {
  7322. //force a flush in case we are using a bad OS.
  7323. if (this._badOS) {
  7324. this.flushFramebuffer();
  7325. }
  7326. //submit frame to the vr device, if enabled
  7327. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7328. this._vrDisplayEnabled.submitFrame();
  7329. }
  7330. };
  7331. /**
  7332. * resize the view according to the canvas' size.
  7333. * @example
  7334. * window.addEventListener("resize", function () {
  7335. * engine.resize();
  7336. * });
  7337. */
  7338. Engine.prototype.resize = function () {
  7339. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7340. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7341. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7342. };
  7343. /**
  7344. * force a specific size of the canvas
  7345. * @param {number} width - the new canvas' width
  7346. * @param {number} height - the new canvas' height
  7347. */
  7348. Engine.prototype.setSize = function (width, height) {
  7349. this._renderingCanvas.width = width;
  7350. this._renderingCanvas.height = height;
  7351. for (var index = 0; index < this.scenes.length; index++) {
  7352. var scene = this.scenes[index];
  7353. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7354. var cam = scene.cameras[camIndex];
  7355. cam._currentRenderId = 0;
  7356. }
  7357. }
  7358. };
  7359. //WebVR functions
  7360. Engine.prototype.initWebVR = function () {
  7361. if (!this.vrDisplaysPromise) {
  7362. this._getVRDisplays();
  7363. }
  7364. };
  7365. Engine.prototype.enableVR = function (vrDevice) {
  7366. this._vrDisplayEnabled = vrDevice;
  7367. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7368. };
  7369. Engine.prototype.disableVR = function () {
  7370. if (this._vrDisplayEnabled) {
  7371. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7372. }
  7373. };
  7374. Engine.prototype._getVRDisplays = function () {
  7375. var _this = this;
  7376. var getWebVRDevices = function (devices) {
  7377. var size = devices.length;
  7378. var i = 0;
  7379. _this._vrDisplays = devices.filter(function (device) {
  7380. return devices[i] instanceof VRDisplay;
  7381. });
  7382. return _this._vrDisplays;
  7383. };
  7384. //using a key due to typescript
  7385. if (navigator.getVRDisplays) {
  7386. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7387. }
  7388. };
  7389. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7390. this._currentRenderTarget = texture;
  7391. this.bindUnboundFramebuffer(texture._framebuffer);
  7392. var gl = this._gl;
  7393. if (texture.isCube) {
  7394. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7395. }
  7396. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7397. this.wipeCaches();
  7398. };
  7399. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7400. if (this._currentFramebuffer !== framebuffer) {
  7401. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7402. this._currentFramebuffer = framebuffer;
  7403. }
  7404. };
  7405. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7406. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7407. this._currentRenderTarget = null;
  7408. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7409. var gl = this._gl;
  7410. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7411. gl.generateMipmap(gl.TEXTURE_2D);
  7412. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7413. }
  7414. this.bindUnboundFramebuffer(null);
  7415. };
  7416. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7417. if (texture.generateMipMaps) {
  7418. var gl = this._gl;
  7419. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7420. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7421. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7422. }
  7423. };
  7424. Engine.prototype.flushFramebuffer = function () {
  7425. this._gl.flush();
  7426. };
  7427. Engine.prototype.restoreDefaultFramebuffer = function () {
  7428. this._currentRenderTarget = null;
  7429. this.bindUnboundFramebuffer(null);
  7430. this.setViewport(this._cachedViewport);
  7431. this.wipeCaches();
  7432. };
  7433. // VBOs
  7434. Engine.prototype._resetVertexBufferBinding = function () {
  7435. this.bindArrayBuffer(null);
  7436. this._cachedVertexBuffers = null;
  7437. };
  7438. Engine.prototype.createVertexBuffer = function (vertices) {
  7439. var vbo = this._gl.createBuffer();
  7440. this.bindArrayBuffer(vbo);
  7441. if (vertices instanceof Float32Array) {
  7442. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7443. }
  7444. else {
  7445. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7446. }
  7447. this._resetVertexBufferBinding();
  7448. vbo.references = 1;
  7449. return vbo;
  7450. };
  7451. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7452. var vbo = this._gl.createBuffer();
  7453. this.bindArrayBuffer(vbo);
  7454. if (vertices instanceof Float32Array) {
  7455. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7456. }
  7457. else {
  7458. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7459. }
  7460. this._resetVertexBufferBinding();
  7461. vbo.references = 1;
  7462. return vbo;
  7463. };
  7464. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7465. this.bindArrayBuffer(vertexBuffer);
  7466. if (offset === undefined) {
  7467. offset = 0;
  7468. }
  7469. if (count === undefined) {
  7470. if (vertices instanceof Float32Array) {
  7471. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7472. }
  7473. else {
  7474. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7475. }
  7476. }
  7477. else {
  7478. if (vertices instanceof Float32Array) {
  7479. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7480. }
  7481. else {
  7482. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7483. }
  7484. }
  7485. this._resetVertexBufferBinding();
  7486. };
  7487. Engine.prototype._resetIndexBufferBinding = function () {
  7488. this.bindIndexBuffer(null);
  7489. this._cachedIndexBuffer = null;
  7490. };
  7491. Engine.prototype.createIndexBuffer = function (indices) {
  7492. var vbo = this._gl.createBuffer();
  7493. this.bindIndexBuffer(vbo);
  7494. // Check for 32 bits indices
  7495. var arrayBuffer;
  7496. var need32Bits = false;
  7497. if (indices instanceof Uint16Array) {
  7498. arrayBuffer = indices;
  7499. }
  7500. else {
  7501. //check 32 bit support
  7502. if (this._caps.uintIndices) {
  7503. if (indices instanceof Uint32Array) {
  7504. arrayBuffer = indices;
  7505. need32Bits = true;
  7506. }
  7507. else {
  7508. //number[] or Int32Array, check if 32 bit is necessary
  7509. for (var index = 0; index < indices.length; index++) {
  7510. if (indices[index] > 65535) {
  7511. need32Bits = true;
  7512. break;
  7513. }
  7514. }
  7515. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7516. }
  7517. }
  7518. else {
  7519. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  7520. arrayBuffer = new Uint16Array(indices);
  7521. }
  7522. }
  7523. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7524. this._resetIndexBufferBinding();
  7525. vbo.references = 1;
  7526. vbo.is32Bits = need32Bits;
  7527. return vbo;
  7528. };
  7529. Engine.prototype.bindArrayBuffer = function (buffer) {
  7530. if (!this._vaoRecordInProgress) {
  7531. this._unBindVertexArrayObject();
  7532. }
  7533. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7534. };
  7535. Engine.prototype.bindIndexBuffer = function (buffer) {
  7536. if (!this._vaoRecordInProgress) {
  7537. this._unBindVertexArrayObject();
  7538. }
  7539. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7540. };
  7541. Engine.prototype.bindBuffer = function (buffer, target) {
  7542. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  7543. this._gl.bindBuffer(target, buffer);
  7544. this._currentBoundBuffer[target] = buffer;
  7545. }
  7546. };
  7547. Engine.prototype.updateArrayBuffer = function (data) {
  7548. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7549. };
  7550. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7551. var pointer = this._currentBufferPointers[indx];
  7552. var changed = false;
  7553. if (!pointer) {
  7554. changed = true;
  7555. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7556. }
  7557. else {
  7558. if (pointer.buffer !== buffer) {
  7559. pointer.buffer = buffer;
  7560. changed = true;
  7561. }
  7562. if (pointer.size !== size) {
  7563. pointer.size = size;
  7564. changed = true;
  7565. }
  7566. if (pointer.type !== type) {
  7567. pointer.type = type;
  7568. changed = true;
  7569. }
  7570. if (pointer.normalized !== normalized) {
  7571. pointer.normalized = normalized;
  7572. changed = true;
  7573. }
  7574. if (pointer.stride !== stride) {
  7575. pointer.stride = stride;
  7576. changed = true;
  7577. }
  7578. if (pointer.offset !== offset) {
  7579. pointer.offset = offset;
  7580. changed = true;
  7581. }
  7582. }
  7583. if (changed || this._vaoRecordInProgress) {
  7584. this.bindArrayBuffer(buffer);
  7585. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7586. }
  7587. };
  7588. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  7589. if (indexBuffer == null) {
  7590. return;
  7591. }
  7592. if (this._cachedIndexBuffer !== indexBuffer) {
  7593. this._cachedIndexBuffer = indexBuffer;
  7594. this.bindIndexBuffer(indexBuffer);
  7595. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7596. }
  7597. };
  7598. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  7599. var attributes = effect.getAttributesNames();
  7600. if (!this._vaoRecordInProgress) {
  7601. this._unBindVertexArrayObject();
  7602. }
  7603. this.unbindAllAttributes();
  7604. for (var index = 0; index < attributes.length; index++) {
  7605. var order = effect.getAttributeLocation(index);
  7606. if (order >= 0) {
  7607. var vertexBuffer = vertexBuffers[attributes[index]];
  7608. if (!vertexBuffer) {
  7609. continue;
  7610. }
  7611. this._gl.enableVertexAttribArray(order);
  7612. if (!this._vaoRecordInProgress) {
  7613. this._vertexAttribArraysEnabled[order] = true;
  7614. }
  7615. var buffer = vertexBuffer.getBuffer();
  7616. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7617. if (vertexBuffer.getIsInstanced()) {
  7618. this._gl.vertexAttribDivisor(order, 1);
  7619. if (!this._vaoRecordInProgress) {
  7620. this._currentInstanceLocations.push(order);
  7621. this._currentInstanceBuffers.push(buffer);
  7622. }
  7623. }
  7624. }
  7625. }
  7626. };
  7627. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  7628. var vao = this._gl.createVertexArray();
  7629. this._vaoRecordInProgress = true;
  7630. this._gl.bindVertexArray(vao);
  7631. this._mustWipeVertexAttributes = true;
  7632. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  7633. this.bindIndexBuffer(indexBuffer);
  7634. this._vaoRecordInProgress = false;
  7635. this._gl.bindVertexArray(null);
  7636. return vao;
  7637. };
  7638. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  7639. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  7640. this._cachedVertexArrayObject = vertexArrayObject;
  7641. this._gl.bindVertexArray(vertexArrayObject);
  7642. this._cachedVertexBuffers = null;
  7643. this._cachedIndexBuffer = null;
  7644. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  7645. this._mustWipeVertexAttributes = true;
  7646. }
  7647. };
  7648. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7649. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7650. this._cachedVertexBuffers = vertexBuffer;
  7651. this._cachedEffectForVertexBuffers = effect;
  7652. var attributesCount = effect.getAttributesCount();
  7653. this._unBindVertexArrayObject();
  7654. this.unbindAllAttributes();
  7655. var offset = 0;
  7656. for (var index = 0; index < attributesCount; index++) {
  7657. if (index < vertexDeclaration.length) {
  7658. var order = effect.getAttributeLocation(index);
  7659. if (order >= 0) {
  7660. this._gl.enableVertexAttribArray(order);
  7661. this._vertexAttribArraysEnabled[order] = true;
  7662. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7663. }
  7664. offset += vertexDeclaration[index] * 4;
  7665. }
  7666. }
  7667. }
  7668. this._bindIndexBufferWithCache(indexBuffer);
  7669. };
  7670. Engine.prototype._unBindVertexArrayObject = function () {
  7671. if (!this._cachedVertexArrayObject) {
  7672. return;
  7673. }
  7674. this._cachedVertexArrayObject = null;
  7675. this._gl.bindVertexArray(null);
  7676. };
  7677. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7678. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7679. this._cachedVertexBuffers = vertexBuffers;
  7680. this._cachedEffectForVertexBuffers = effect;
  7681. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  7682. }
  7683. this._bindIndexBufferWithCache(indexBuffer);
  7684. };
  7685. Engine.prototype.unbindInstanceAttributes = function () {
  7686. var boundBuffer;
  7687. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7688. var instancesBuffer = this._currentInstanceBuffers[i];
  7689. if (boundBuffer != instancesBuffer) {
  7690. boundBuffer = instancesBuffer;
  7691. this.bindArrayBuffer(instancesBuffer);
  7692. }
  7693. var offsetLocation = this._currentInstanceLocations[i];
  7694. this._gl.vertexAttribDivisor(offsetLocation, 0);
  7695. }
  7696. this._currentInstanceBuffers.length = 0;
  7697. this._currentInstanceLocations.length = 0;
  7698. };
  7699. Engine.prototype.releaseVertexArrayObject = function (vao) {
  7700. this._gl.deleteVertexArray(vao);
  7701. };
  7702. Engine.prototype._releaseBuffer = function (buffer) {
  7703. buffer.references--;
  7704. if (buffer.references === 0) {
  7705. this._gl.deleteBuffer(buffer);
  7706. return true;
  7707. }
  7708. return false;
  7709. };
  7710. Engine.prototype.createInstancesBuffer = function (capacity) {
  7711. var buffer = this._gl.createBuffer();
  7712. buffer.capacity = capacity;
  7713. this.bindArrayBuffer(buffer);
  7714. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7715. return buffer;
  7716. };
  7717. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7718. this._gl.deleteBuffer(buffer);
  7719. };
  7720. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7721. this.bindArrayBuffer(instancesBuffer);
  7722. if (data) {
  7723. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7724. }
  7725. if (offsetLocations[0].index !== undefined) {
  7726. var stride = 0;
  7727. for (var i = 0; i < offsetLocations.length; i++) {
  7728. var ai = offsetLocations[i];
  7729. stride += ai.attributeSize * 4;
  7730. }
  7731. for (var i = 0; i < offsetLocations.length; i++) {
  7732. var ai = offsetLocations[i];
  7733. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7734. this._gl.enableVertexAttribArray(ai.index);
  7735. this._vertexAttribArraysEnabled[ai.index] = true;
  7736. }
  7737. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7738. this._gl.vertexAttribDivisor(ai.index, 1);
  7739. this._currentInstanceLocations.push(ai.index);
  7740. this._currentInstanceBuffers.push(instancesBuffer);
  7741. }
  7742. }
  7743. else {
  7744. for (var index = 0; index < 4; index++) {
  7745. var offsetLocation = offsetLocations[index];
  7746. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7747. this._gl.enableVertexAttribArray(offsetLocation);
  7748. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7749. }
  7750. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7751. this._gl.vertexAttribDivisor(offsetLocation, 1);
  7752. this._currentInstanceLocations.push(offsetLocation);
  7753. this._currentInstanceBuffers.push(instancesBuffer);
  7754. }
  7755. }
  7756. };
  7757. Engine.prototype.applyStates = function () {
  7758. this._depthCullingState.apply(this._gl);
  7759. this._stencilState.apply(this._gl);
  7760. this._alphaState.apply(this._gl);
  7761. };
  7762. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7763. // Apply states
  7764. this.applyStates();
  7765. this._drawCalls.addCount(1, false);
  7766. // Render
  7767. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7768. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7769. if (instancesCount) {
  7770. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7771. return;
  7772. }
  7773. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7774. };
  7775. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7776. // Apply states
  7777. this.applyStates();
  7778. this._drawCalls.addCount(1, false);
  7779. if (instancesCount) {
  7780. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7781. return;
  7782. }
  7783. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7784. };
  7785. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7786. // Apply states
  7787. this.applyStates();
  7788. this._drawCalls.addCount(1, false);
  7789. if (instancesCount) {
  7790. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7791. return;
  7792. }
  7793. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7794. };
  7795. // Shaders
  7796. Engine.prototype._releaseEffect = function (effect) {
  7797. if (this._compiledEffects[effect._key]) {
  7798. delete this._compiledEffects[effect._key];
  7799. if (effect.getProgram()) {
  7800. this._gl.deleteProgram(effect.getProgram());
  7801. }
  7802. }
  7803. };
  7804. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7805. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7806. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7807. var name = vertex + "+" + fragment + "@" + defines;
  7808. if (this._compiledEffects[name]) {
  7809. return this._compiledEffects[name];
  7810. }
  7811. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7812. effect._key = name;
  7813. this._compiledEffects[name] = effect;
  7814. return effect;
  7815. };
  7816. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7817. if (uniformsNames === void 0) { uniformsNames = []; }
  7818. if (samplers === void 0) { samplers = []; }
  7819. if (defines === void 0) { defines = ""; }
  7820. return this.createEffect({
  7821. vertex: "particles",
  7822. fragmentElement: fragmentName
  7823. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7824. };
  7825. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7826. context = context || this._gl;
  7827. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  7828. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  7829. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  7830. var shaderProgram = context.createProgram();
  7831. context.attachShader(shaderProgram, vertexShader);
  7832. context.attachShader(shaderProgram, fragmentShader);
  7833. context.linkProgram(shaderProgram);
  7834. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7835. if (!linked) {
  7836. var error = context.getProgramInfoLog(shaderProgram);
  7837. if (error) {
  7838. throw new Error(error);
  7839. }
  7840. }
  7841. context.deleteShader(vertexShader);
  7842. context.deleteShader(fragmentShader);
  7843. return shaderProgram;
  7844. };
  7845. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7846. var results = [];
  7847. for (var index = 0; index < uniformsNames.length; index++) {
  7848. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7849. }
  7850. return results;
  7851. };
  7852. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7853. var results = [];
  7854. for (var index = 0; index < attributesNames.length; index++) {
  7855. try {
  7856. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7857. }
  7858. catch (e) {
  7859. results.push(-1);
  7860. }
  7861. }
  7862. return results;
  7863. };
  7864. Engine.prototype.enableEffect = function (effect) {
  7865. // Use program
  7866. this.setProgram(effect.getProgram());
  7867. this._currentEffect = effect;
  7868. if (effect.onBind) {
  7869. effect.onBind(effect);
  7870. }
  7871. };
  7872. Engine.prototype.setIntArray = function (uniform, array) {
  7873. if (!uniform)
  7874. return;
  7875. this._gl.uniform1iv(uniform, array);
  7876. };
  7877. Engine.prototype.setIntArray2 = function (uniform, array) {
  7878. if (!uniform || array.length % 2 !== 0)
  7879. return;
  7880. this._gl.uniform2iv(uniform, array);
  7881. };
  7882. Engine.prototype.setIntArray3 = function (uniform, array) {
  7883. if (!uniform || array.length % 3 !== 0)
  7884. return;
  7885. this._gl.uniform3iv(uniform, array);
  7886. };
  7887. Engine.prototype.setIntArray4 = function (uniform, array) {
  7888. if (!uniform || array.length % 4 !== 0)
  7889. return;
  7890. this._gl.uniform4iv(uniform, array);
  7891. };
  7892. Engine.prototype.setFloatArray = function (uniform, array) {
  7893. if (!uniform)
  7894. return;
  7895. this._gl.uniform1fv(uniform, array);
  7896. };
  7897. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7898. if (!uniform || array.length % 2 !== 0)
  7899. return;
  7900. this._gl.uniform2fv(uniform, array);
  7901. };
  7902. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7903. if (!uniform || array.length % 3 !== 0)
  7904. return;
  7905. this._gl.uniform3fv(uniform, array);
  7906. };
  7907. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7908. if (!uniform || array.length % 4 !== 0)
  7909. return;
  7910. this._gl.uniform4fv(uniform, array);
  7911. };
  7912. Engine.prototype.setArray = function (uniform, array) {
  7913. if (!uniform)
  7914. return;
  7915. this._gl.uniform1fv(uniform, array);
  7916. };
  7917. Engine.prototype.setArray2 = function (uniform, array) {
  7918. if (!uniform || array.length % 2 !== 0)
  7919. return;
  7920. this._gl.uniform2fv(uniform, array);
  7921. };
  7922. Engine.prototype.setArray3 = function (uniform, array) {
  7923. if (!uniform || array.length % 3 !== 0)
  7924. return;
  7925. this._gl.uniform3fv(uniform, array);
  7926. };
  7927. Engine.prototype.setArray4 = function (uniform, array) {
  7928. if (!uniform || array.length % 4 !== 0)
  7929. return;
  7930. this._gl.uniform4fv(uniform, array);
  7931. };
  7932. Engine.prototype.setMatrices = function (uniform, matrices) {
  7933. if (!uniform)
  7934. return;
  7935. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7936. };
  7937. Engine.prototype.setMatrix = function (uniform, matrix) {
  7938. if (!uniform)
  7939. return;
  7940. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7941. };
  7942. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7943. if (!uniform)
  7944. return;
  7945. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7946. };
  7947. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7948. if (!uniform)
  7949. return;
  7950. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7951. };
  7952. Engine.prototype.setFloat = function (uniform, value) {
  7953. if (!uniform)
  7954. return;
  7955. this._gl.uniform1f(uniform, value);
  7956. };
  7957. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7958. if (!uniform)
  7959. return;
  7960. this._gl.uniform2f(uniform, x, y);
  7961. };
  7962. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7963. if (!uniform)
  7964. return;
  7965. this._gl.uniform3f(uniform, x, y, z);
  7966. };
  7967. Engine.prototype.setBool = function (uniform, bool) {
  7968. if (!uniform)
  7969. return;
  7970. this._gl.uniform1i(uniform, bool);
  7971. };
  7972. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7973. if (!uniform)
  7974. return;
  7975. this._gl.uniform4f(uniform, x, y, z, w);
  7976. };
  7977. Engine.prototype.setColor3 = function (uniform, color3) {
  7978. if (!uniform)
  7979. return;
  7980. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7981. };
  7982. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7983. if (!uniform)
  7984. return;
  7985. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7986. };
  7987. // States
  7988. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7989. if (zOffset === void 0) { zOffset = 0; }
  7990. if (reverseSide === void 0) { reverseSide = false; }
  7991. // Culling
  7992. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7993. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7994. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7995. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7996. if (culling) {
  7997. this._depthCullingState.cullFace = cullFace;
  7998. this._depthCullingState.cull = true;
  7999. }
  8000. else {
  8001. this._depthCullingState.cull = false;
  8002. }
  8003. }
  8004. // Z offset
  8005. this._depthCullingState.zOffset = zOffset;
  8006. };
  8007. Engine.prototype.setDepthBuffer = function (enable) {
  8008. this._depthCullingState.depthTest = enable;
  8009. };
  8010. Engine.prototype.getDepthWrite = function () {
  8011. return this._depthCullingState.depthMask;
  8012. };
  8013. Engine.prototype.setDepthWrite = function (enable) {
  8014. this._depthCullingState.depthMask = enable;
  8015. };
  8016. Engine.prototype.setColorWrite = function (enable) {
  8017. this._gl.colorMask(enable, enable, enable, enable);
  8018. };
  8019. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  8020. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  8021. if (this._alphaMode === mode) {
  8022. return;
  8023. }
  8024. switch (mode) {
  8025. case Engine.ALPHA_DISABLE:
  8026. this._alphaState.alphaBlend = false;
  8027. break;
  8028. case Engine.ALPHA_PREMULTIPLIED:
  8029. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  8030. this._alphaState.alphaBlend = true;
  8031. break;
  8032. case Engine.ALPHA_COMBINE:
  8033. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  8034. this._alphaState.alphaBlend = true;
  8035. break;
  8036. case Engine.ALPHA_ONEONE:
  8037. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8038. this._alphaState.alphaBlend = true;
  8039. break;
  8040. case Engine.ALPHA_ADD:
  8041. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  8042. this._alphaState.alphaBlend = true;
  8043. break;
  8044. case Engine.ALPHA_SUBTRACT:
  8045. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8046. this._alphaState.alphaBlend = true;
  8047. break;
  8048. case Engine.ALPHA_MULTIPLY:
  8049. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  8050. this._alphaState.alphaBlend = true;
  8051. break;
  8052. case Engine.ALPHA_MAXIMIZED:
  8053. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  8054. this._alphaState.alphaBlend = true;
  8055. break;
  8056. }
  8057. if (!noDepthWriteChange) {
  8058. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  8059. }
  8060. this._alphaMode = mode;
  8061. };
  8062. Engine.prototype.getAlphaMode = function () {
  8063. return this._alphaMode;
  8064. };
  8065. Engine.prototype.setAlphaTesting = function (enable) {
  8066. this._alphaTest = enable;
  8067. };
  8068. Engine.prototype.getAlphaTesting = function () {
  8069. return this._alphaTest;
  8070. };
  8071. // Textures
  8072. Engine.prototype.wipeCaches = function () {
  8073. this.resetTextureCache();
  8074. this._currentEffect = null;
  8075. this._stencilState.reset();
  8076. this._depthCullingState.reset();
  8077. this.setDepthFunctionToLessOrEqual();
  8078. this._alphaState.reset();
  8079. this._cachedVertexBuffers = null;
  8080. this._cachedIndexBuffer = null;
  8081. this._cachedEffectForVertexBuffers = null;
  8082. this._unBindVertexArrayObject();
  8083. this.bindIndexBuffer(null);
  8084. this.bindArrayBuffer(null);
  8085. };
  8086. /**
  8087. * Set the compressed texture format to use, based on the formats you have, and the formats
  8088. * supported by the hardware / browser.
  8089. *
  8090. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  8091. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  8092. * to API arguments needed to compressed textures. This puts the burden on the container
  8093. * generator to house the arcane code for determining these for current & future formats.
  8094. *
  8095. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  8096. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  8097. *
  8098. * Note: The result of this call is not taken into account when a texture is base64.
  8099. *
  8100. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  8101. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  8102. *
  8103. * Current families are astc, dxt, pvrtc, etc2, atc, & etc1.
  8104. * @returns The extension selected.
  8105. */
  8106. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8107. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8108. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8109. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8110. return this._textureFormatInUse = this._texturesSupported[i];
  8111. }
  8112. }
  8113. }
  8114. // actively set format to nothing, to allow this to be called more than once
  8115. // and possibly fail the 2nd time
  8116. return this._textureFormatInUse = null;
  8117. };
  8118. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack) {
  8119. var _this = this;
  8120. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8121. if (onLoad === void 0) { onLoad = null; }
  8122. if (onError === void 0) { onError = null; }
  8123. if (buffer === void 0) { buffer = null; }
  8124. var texture = fallBack ? fallBack : this._gl.createTexture();
  8125. var extension;
  8126. var isKTX = false;
  8127. var fromData = false;
  8128. var url = String(urlArg);
  8129. if (url.substr(0, 5) === "data:") {
  8130. fromData = true;
  8131. }
  8132. if (!fromData) {
  8133. var lastDot = url.lastIndexOf('.');
  8134. extension = url.substring(lastDot).toLowerCase();
  8135. if (this._textureFormatInUse && !fromData && !fallBack) {
  8136. extension = this._textureFormatInUse;
  8137. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8138. isKTX = true;
  8139. }
  8140. }
  8141. else {
  8142. var oldUrl = url;
  8143. fromData = oldUrl.split(':');
  8144. url = oldUrl;
  8145. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  8146. }
  8147. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8148. var isTGA = (extension === ".tga");
  8149. scene._addPendingData(texture);
  8150. texture.url = url;
  8151. texture.noMipmap = noMipmap;
  8152. texture.references = 1;
  8153. texture.samplingMode = samplingMode;
  8154. texture.onLoadedCallbacks = [];
  8155. if (onLoad) {
  8156. texture.onLoadedCallbacks.push(onLoad);
  8157. }
  8158. if (!fallBack)
  8159. this._loadedTexturesCache.push(texture);
  8160. var onerror = function () {
  8161. scene._removePendingData(texture);
  8162. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  8163. if (isKTX) {
  8164. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, texture);
  8165. }
  8166. else if (onError) {
  8167. onError();
  8168. }
  8169. };
  8170. var callback;
  8171. if (isKTX || isTGA || isDDS) {
  8172. if (isKTX) {
  8173. callback = function (data) {
  8174. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  8175. prepareWebGLTexture(texture, _this._gl, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  8176. ktx.uploadLevels(_this._gl, !noMipmap);
  8177. }, samplingMode);
  8178. };
  8179. }
  8180. else if (isTGA) {
  8181. callback = function (arrayBuffer) {
  8182. var data = new Uint8Array(arrayBuffer);
  8183. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8184. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8185. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8186. }, samplingMode);
  8187. };
  8188. }
  8189. else if (isDDS) {
  8190. callback = function (data) {
  8191. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8192. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8193. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8194. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8195. }, samplingMode);
  8196. };
  8197. }
  8198. if (!(fromData instanceof Array))
  8199. BABYLON.Tools.LoadFile(url, function (data) {
  8200. callback(data);
  8201. }, null, scene.database, true, onerror);
  8202. else
  8203. callback(buffer);
  8204. }
  8205. else {
  8206. var onload = function (img) {
  8207. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8208. var isPot = (img.width === potWidth && img.height === potHeight);
  8209. if (!isPot) {
  8210. _this._prepareWorkingCanvas();
  8211. _this._workingCanvas.width = potWidth;
  8212. _this._workingCanvas.height = potHeight;
  8213. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8214. _this._workingContext.imageSmoothingEnabled = false;
  8215. _this._workingContext.mozImageSmoothingEnabled = false;
  8216. _this._workingContext.oImageSmoothingEnabled = false;
  8217. _this._workingContext.webkitImageSmoothingEnabled = false;
  8218. _this._workingContext.msImageSmoothingEnabled = false;
  8219. }
  8220. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8221. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8222. _this._workingContext.imageSmoothingEnabled = true;
  8223. _this._workingContext.mozImageSmoothingEnabled = true;
  8224. _this._workingContext.oImageSmoothingEnabled = true;
  8225. _this._workingContext.webkitImageSmoothingEnabled = true;
  8226. _this._workingContext.msImageSmoothingEnabled = true;
  8227. }
  8228. }
  8229. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8230. }, samplingMode);
  8231. };
  8232. if (!(fromData instanceof Array))
  8233. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8234. else
  8235. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8236. }
  8237. return texture;
  8238. };
  8239. Engine.prototype._getInternalFormat = function (format) {
  8240. var internalFormat = this._gl.RGBA;
  8241. switch (format) {
  8242. case Engine.TEXTUREFORMAT_ALPHA:
  8243. internalFormat = this._gl.ALPHA;
  8244. break;
  8245. case Engine.TEXTUREFORMAT_LUMINANCE:
  8246. internalFormat = this._gl.LUMINANCE;
  8247. break;
  8248. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8249. internalFormat = this._gl.LUMINANCE_ALPHA;
  8250. break;
  8251. case Engine.TEXTUREFORMAT_RGB:
  8252. internalFormat = this._gl.RGB;
  8253. break;
  8254. case Engine.TEXTUREFORMAT_RGBA:
  8255. internalFormat = this._gl.RGBA;
  8256. break;
  8257. }
  8258. return internalFormat;
  8259. };
  8260. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8261. if (compression === void 0) { compression = null; }
  8262. var internalFormat = this._getInternalFormat(format);
  8263. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8264. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8265. if (texture._width % 4 !== 0) {
  8266. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8267. }
  8268. if (compression) {
  8269. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8270. }
  8271. else {
  8272. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8273. }
  8274. if (texture.generateMipMaps) {
  8275. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8276. }
  8277. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8278. this.resetTextureCache();
  8279. texture.isReady = true;
  8280. };
  8281. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8282. if (compression === void 0) { compression = null; }
  8283. var texture = this._gl.createTexture();
  8284. texture._baseWidth = width;
  8285. texture._baseHeight = height;
  8286. texture._width = width;
  8287. texture._height = height;
  8288. texture.references = 1;
  8289. this.updateRawTexture(texture, data, format, invertY, compression);
  8290. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8291. // Filters
  8292. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8293. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8294. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8295. if (generateMipMaps) {
  8296. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8297. }
  8298. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8299. texture.samplingMode = samplingMode;
  8300. this._loadedTexturesCache.push(texture);
  8301. return texture;
  8302. };
  8303. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8304. var texture = this._gl.createTexture();
  8305. texture._baseWidth = width;
  8306. texture._baseHeight = height;
  8307. if (generateMipMaps) {
  8308. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8309. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8310. }
  8311. this.resetTextureCache();
  8312. texture._width = width;
  8313. texture._height = height;
  8314. texture.isReady = false;
  8315. texture.generateMipMaps = generateMipMaps;
  8316. texture.references = 1;
  8317. texture.samplingMode = samplingMode;
  8318. this.updateTextureSamplingMode(samplingMode, texture);
  8319. this._loadedTexturesCache.push(texture);
  8320. return texture;
  8321. };
  8322. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8323. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8324. if (texture.isCube) {
  8325. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8326. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8327. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8328. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8329. }
  8330. else {
  8331. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8332. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8333. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8334. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8335. }
  8336. texture.samplingMode = samplingMode;
  8337. };
  8338. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8339. if (premulAlpha === void 0) { premulAlpha = false; }
  8340. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8341. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8342. if (premulAlpha) {
  8343. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8344. }
  8345. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8346. if (texture.generateMipMaps) {
  8347. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8348. }
  8349. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8350. if (premulAlpha) {
  8351. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8352. }
  8353. this.resetTextureCache();
  8354. texture.isReady = true;
  8355. };
  8356. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8357. if (texture._isDisabled) {
  8358. return;
  8359. }
  8360. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8361. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8362. try {
  8363. // Testing video texture support
  8364. if (this._videoTextureSupported === undefined) {
  8365. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8366. if (this._gl.getError() !== 0) {
  8367. this._videoTextureSupported = false;
  8368. }
  8369. else {
  8370. this._videoTextureSupported = true;
  8371. }
  8372. }
  8373. // Copy video through the current working canvas if video texture is not supported
  8374. if (!this._videoTextureSupported) {
  8375. if (!texture._workingCanvas) {
  8376. texture._workingCanvas = document.createElement("canvas");
  8377. texture._workingContext = texture._workingCanvas.getContext("2d");
  8378. texture._workingCanvas.width = texture._width;
  8379. texture._workingCanvas.height = texture._height;
  8380. }
  8381. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8382. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8383. }
  8384. else {
  8385. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8386. }
  8387. if (texture.generateMipMaps) {
  8388. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8389. }
  8390. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8391. this.resetTextureCache();
  8392. texture.isReady = true;
  8393. }
  8394. catch (ex) {
  8395. // Something unexpected
  8396. // Let's disable the texture
  8397. texture._isDisabled = true;
  8398. }
  8399. };
  8400. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8401. // old version had a "generateMipMaps" arg instead of options.
  8402. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8403. // in the same way, generateDepthBuffer is defaulted to true
  8404. var generateMipMaps = false;
  8405. var generateDepthBuffer = true;
  8406. var generateStencilBuffer = false;
  8407. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8408. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8409. if (options !== undefined) {
  8410. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8411. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8412. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8413. type = options.type === undefined ? type : options.type;
  8414. if (options.samplingMode !== undefined) {
  8415. samplingMode = options.samplingMode;
  8416. }
  8417. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8418. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8419. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8420. }
  8421. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8422. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8423. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8424. }
  8425. }
  8426. var gl = this._gl;
  8427. var texture = gl.createTexture();
  8428. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8429. var width = size.width || size;
  8430. var height = size.height || size;
  8431. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8432. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8433. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8434. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8435. }
  8436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8438. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8439. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8440. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  8441. var depthStencilBuffer;
  8442. // Create the depth/stencil buffer
  8443. if (generateStencilBuffer) {
  8444. depthStencilBuffer = gl.createRenderbuffer();
  8445. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8446. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8447. }
  8448. else if (generateDepthBuffer) {
  8449. depthStencilBuffer = gl.createRenderbuffer();
  8450. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8451. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8452. }
  8453. // Create the framebuffer
  8454. var framebuffer = gl.createFramebuffer();
  8455. this.bindUnboundFramebuffer(framebuffer);
  8456. // Manage attachments
  8457. if (generateStencilBuffer) {
  8458. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8459. }
  8460. else if (generateDepthBuffer) {
  8461. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8462. }
  8463. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8464. if (generateMipMaps) {
  8465. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8466. }
  8467. // Unbind
  8468. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8469. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8470. this.bindUnboundFramebuffer(null);
  8471. texture._framebuffer = framebuffer;
  8472. if (generateDepthBuffer) {
  8473. texture._depthBuffer = depthStencilBuffer;
  8474. }
  8475. texture._baseWidth = width;
  8476. texture._baseHeight = height;
  8477. texture._width = width;
  8478. texture._height = height;
  8479. texture.isReady = true;
  8480. texture.generateMipMaps = generateMipMaps;
  8481. texture.references = 1;
  8482. texture.samplingMode = samplingMode;
  8483. texture.type = type;
  8484. this.resetTextureCache();
  8485. this._loadedTexturesCache.push(texture);
  8486. return texture;
  8487. };
  8488. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8489. var gl = this._gl;
  8490. var texture = gl.createTexture();
  8491. var generateMipMaps = true;
  8492. var generateDepthBuffer = true;
  8493. var generateStencilBuffer = false;
  8494. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8495. if (options !== undefined) {
  8496. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8497. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8498. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8499. if (options.samplingMode !== undefined) {
  8500. samplingMode = options.samplingMode;
  8501. }
  8502. }
  8503. texture.isCube = true;
  8504. texture.references = 1;
  8505. texture.generateMipMaps = generateMipMaps;
  8506. texture.references = 1;
  8507. texture.samplingMode = samplingMode;
  8508. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8509. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8510. for (var face = 0; face < 6; face++) {
  8511. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8512. }
  8513. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8517. // Create the depth buffer
  8518. var depthStencilBuffer;
  8519. // Create the depth/stencil buffer
  8520. if (generateStencilBuffer) {
  8521. depthStencilBuffer = gl.createRenderbuffer();
  8522. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8523. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8524. }
  8525. else if (generateDepthBuffer) {
  8526. depthStencilBuffer = gl.createRenderbuffer();
  8527. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8528. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8529. }
  8530. // Create the framebuffer
  8531. var framebuffer = gl.createFramebuffer();
  8532. this.bindUnboundFramebuffer(framebuffer);
  8533. // Manage attachments
  8534. if (generateStencilBuffer) {
  8535. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8536. }
  8537. else if (generateDepthBuffer) {
  8538. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8539. }
  8540. // Mipmaps
  8541. if (texture.generateMipMaps) {
  8542. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8543. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8544. }
  8545. // Unbind
  8546. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8547. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8548. this.bindUnboundFramebuffer(null);
  8549. texture._framebuffer = framebuffer;
  8550. if (generateDepthBuffer) {
  8551. texture._depthBuffer = depthStencilBuffer;
  8552. }
  8553. texture._width = size;
  8554. texture._height = size;
  8555. texture.isReady = true;
  8556. this.resetTextureCache();
  8557. this._loadedTexturesCache.push(texture);
  8558. return texture;
  8559. };
  8560. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8561. var _this = this;
  8562. if (onLoad === void 0) { onLoad = null; }
  8563. if (onError === void 0) { onError = null; }
  8564. var gl = this._gl;
  8565. var texture = gl.createTexture();
  8566. texture.isCube = true;
  8567. texture.url = rootUrl;
  8568. texture.references = 1;
  8569. texture.onLoadedCallbacks = [];
  8570. var isKTX = false;
  8571. var lastDot = rootUrl.lastIndexOf('.');
  8572. var extension = rootUrl.substring(lastDot).toLowerCase();
  8573. if (this._textureFormatInUse) {
  8574. extension = this._textureFormatInUse;
  8575. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  8576. isKTX = true;
  8577. }
  8578. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8579. if (isKTX) {
  8580. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8581. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  8582. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  8583. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8584. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8585. ktx.uploadLevels(_this._gl, !noMipmap);
  8586. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8587. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8588. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8589. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8590. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8591. _this.resetTextureCache();
  8592. texture._width = ktx.pixelWidth;
  8593. texture._height = ktx.pixelHeight;
  8594. texture.isReady = true;
  8595. }, null, null, true, onError);
  8596. }
  8597. else if (isDDS) {
  8598. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8599. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8600. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8601. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8602. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8603. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8604. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8605. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8606. }
  8607. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8608. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8609. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8610. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8611. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8612. _this.resetTextureCache();
  8613. texture._width = info.width;
  8614. texture._height = info.height;
  8615. texture.isReady = true;
  8616. }, null, null, true, onError);
  8617. }
  8618. else {
  8619. cascadeLoad(rootUrl, scene, function (imgs) {
  8620. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8621. var height = width;
  8622. _this._prepareWorkingCanvas();
  8623. _this._workingCanvas.width = width;
  8624. _this._workingCanvas.height = height;
  8625. var faces = [
  8626. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8627. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8628. ];
  8629. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8630. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8631. for (var index = 0; index < faces.length; index++) {
  8632. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8633. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8634. }
  8635. if (!noMipmap) {
  8636. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8637. }
  8638. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8639. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8640. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8641. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8642. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8643. _this.resetTextureCache();
  8644. texture._width = width;
  8645. texture._height = height;
  8646. texture.isReady = true;
  8647. texture.onLoadedCallbacks.forEach(function (callback) {
  8648. callback();
  8649. });
  8650. if (onLoad) {
  8651. onLoad();
  8652. }
  8653. }, files, onError);
  8654. }
  8655. this._loadedTexturesCache.push(texture);
  8656. return texture;
  8657. };
  8658. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8659. texture._width = width;
  8660. texture._height = height;
  8661. texture._size = width * height;
  8662. texture._baseWidth = width;
  8663. texture._baseHeight = height;
  8664. };
  8665. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError) {
  8666. var _this = this;
  8667. if (onLoad === void 0) { onLoad = null; }
  8668. if (onError === void 0) { onError = null; }
  8669. var gl = this._gl;
  8670. var texture = gl.createTexture();
  8671. scene._addPendingData(texture);
  8672. texture.isCube = true;
  8673. texture.references = 1;
  8674. texture.url = url;
  8675. var textureType = gl.UNSIGNED_BYTE;
  8676. if (type === Engine.TEXTURETYPE_FLOAT) {
  8677. textureType = gl.FLOAT;
  8678. }
  8679. var internalFormat = this._getInternalFormat(format);
  8680. var needConversion = false;
  8681. if (internalFormat === gl.RGB) {
  8682. internalFormat = gl.RGBA;
  8683. needConversion = true;
  8684. }
  8685. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  8686. var width = size;
  8687. var height = width;
  8688. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8689. texture._width = width;
  8690. texture._height = height;
  8691. var onerror = function () {
  8692. scene._removePendingData(texture);
  8693. if (onError) {
  8694. onError();
  8695. }
  8696. };
  8697. var internalCallback = function (data) {
  8698. var rgbeDataArrays = callback(data);
  8699. var facesIndex = [
  8700. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8701. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8702. ];
  8703. width = texture._width;
  8704. height = texture._height;
  8705. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8706. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8707. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8708. if (mipmmapGenerator) {
  8709. var arrayTemp = [];
  8710. // Data are known to be in +X +Y +Z -X -Y -Z
  8711. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8712. arrayTemp.push(rgbeDataArrays[0]); // +X
  8713. arrayTemp.push(rgbeDataArrays[3]); // -X
  8714. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8715. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8716. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8717. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8718. var mipData = mipmmapGenerator(arrayTemp);
  8719. // mipData is order in +X -X +Y -Y +Z -Z
  8720. var mipFaces = [0, 2, 4, 1, 3, 5];
  8721. for (var level = 0; level < mipData.length; level++) {
  8722. var mipSize = width >> level;
  8723. for (var mipIndex in mipFaces) {
  8724. var mipFaceData = mipData[level][mipFaces[mipIndex]];
  8725. if (needConversion) {
  8726. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  8727. }
  8728. gl.texImage2D(facesIndex[mipIndex], level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  8729. }
  8730. }
  8731. }
  8732. else {
  8733. // Data are known to be in +X +Y +Z -X -Y -Z
  8734. for (var index = 0; index < facesIndex.length; index++) {
  8735. var faceData = rgbeDataArrays[index];
  8736. if (needConversion) {
  8737. faceData = _this._convertRGBtoRGBATextureData(faceData, width, height, type);
  8738. }
  8739. gl.texImage2D(facesIndex[index], 0, internalSizedFomat, width, height, 0, internalFormat, textureType, faceData);
  8740. }
  8741. if (!noMipmap && isPot) {
  8742. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8743. }
  8744. else {
  8745. noMipmap = true;
  8746. }
  8747. }
  8748. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8749. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8750. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8751. }
  8752. else if (textureType === Engine.HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8753. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8754. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8755. }
  8756. else {
  8757. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8758. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8759. }
  8760. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8761. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8762. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8763. texture.isReady = true;
  8764. _this.resetTextureCache();
  8765. scene._removePendingData(texture);
  8766. if (onLoad) {
  8767. onLoad();
  8768. }
  8769. };
  8770. BABYLON.Tools.LoadFile(url, function (data) {
  8771. internalCallback(data);
  8772. }, onerror, scene.database, true);
  8773. return texture;
  8774. };
  8775. ;
  8776. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  8777. // Create new RGBA data container.
  8778. var rgbaData;
  8779. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  8780. rgbaData = new Float32Array(width * height * 4);
  8781. }
  8782. else {
  8783. rgbaData = new Uint32Array(width * height * 4);
  8784. }
  8785. // Convert each pixel.
  8786. for (var x = 0; x < width; x++) {
  8787. for (var y = 0; y < height; y++) {
  8788. var index = (y * width + x) * 3;
  8789. var newIndex = (y * width + x) * 4;
  8790. // Map Old Value to new value.
  8791. rgbaData[newIndex + 0] = rgbData[index + 0];
  8792. rgbaData[newIndex + 1] = rgbData[index + 1];
  8793. rgbaData[newIndex + 2] = rgbData[index + 2];
  8794. // Add fully opaque alpha channel.
  8795. rgbaData[newIndex + 3] = 1;
  8796. }
  8797. }
  8798. return rgbaData;
  8799. };
  8800. Engine.prototype._releaseTexture = function (texture) {
  8801. var gl = this._gl;
  8802. if (texture._framebuffer) {
  8803. gl.deleteFramebuffer(texture._framebuffer);
  8804. }
  8805. if (texture._depthBuffer) {
  8806. gl.deleteRenderbuffer(texture._depthBuffer);
  8807. }
  8808. gl.deleteTexture(texture);
  8809. // Unbind channels
  8810. this.unbindAllTextures();
  8811. var index = this._loadedTexturesCache.indexOf(texture);
  8812. if (index !== -1) {
  8813. this._loadedTexturesCache.splice(index, 1);
  8814. }
  8815. };
  8816. Engine.prototype.setProgram = function (program) {
  8817. if (this._currentProgram !== program) {
  8818. this._gl.useProgram(program);
  8819. this._currentProgram = program;
  8820. }
  8821. };
  8822. Engine.prototype.bindSamplers = function (effect) {
  8823. this.setProgram(effect.getProgram());
  8824. var samplers = effect.getSamplers();
  8825. for (var index = 0; index < samplers.length; index++) {
  8826. var uniform = effect.getUniform(samplers[index]);
  8827. this._gl.uniform1i(uniform, index);
  8828. }
  8829. this._currentEffect = null;
  8830. };
  8831. Engine.prototype.activateTexture = function (texture) {
  8832. if (this._activeTexture !== texture) {
  8833. this._gl.activeTexture(texture);
  8834. this._activeTexture = texture;
  8835. }
  8836. };
  8837. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8838. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8839. this._gl.bindTexture(target, texture);
  8840. this._activeTexturesCache[this._activeTexture] = texture;
  8841. }
  8842. };
  8843. Engine.prototype._bindTexture = function (channel, texture) {
  8844. if (channel < 0) {
  8845. return;
  8846. }
  8847. this.activateTexture(this._gl.TEXTURE0 + channel);
  8848. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8849. };
  8850. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8851. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8852. };
  8853. Engine.prototype.unbindAllTextures = function () {
  8854. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8855. this.activateTexture(this._gl["TEXTURE" + channel]);
  8856. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8857. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8858. }
  8859. };
  8860. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8861. if (channel < 0) {
  8862. return;
  8863. }
  8864. this._gl.uniform1i(uniform, channel);
  8865. this._setTexture(channel, texture);
  8866. };
  8867. Engine.prototype._setTexture = function (channel, texture) {
  8868. // Not ready?
  8869. if (!texture || !texture.isReady()) {
  8870. if (this._activeTexturesCache[channel] != null) {
  8871. this.activateTexture(this._gl["TEXTURE" + channel]);
  8872. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8873. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8874. }
  8875. return;
  8876. }
  8877. // Video
  8878. var alreadyActivated = false;
  8879. if (texture instanceof BABYLON.VideoTexture) {
  8880. this.activateTexture(this._gl["TEXTURE" + channel]);
  8881. alreadyActivated = true;
  8882. texture.update();
  8883. }
  8884. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8885. texture.delayLoad();
  8886. return;
  8887. }
  8888. var internalTexture = texture.getInternalTexture();
  8889. if (this._activeTexturesCache[channel] === internalTexture) {
  8890. return;
  8891. }
  8892. if (!alreadyActivated) {
  8893. this.activateTexture(this._gl["TEXTURE" + channel]);
  8894. }
  8895. if (internalTexture.isCube) {
  8896. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8897. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8898. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8899. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8900. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8901. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8902. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8903. }
  8904. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8905. }
  8906. else {
  8907. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8908. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8909. internalTexture._cachedWrapU = texture.wrapU;
  8910. switch (texture.wrapU) {
  8911. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8912. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8913. break;
  8914. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8915. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8916. break;
  8917. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8918. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8919. break;
  8920. }
  8921. }
  8922. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8923. internalTexture._cachedWrapV = texture.wrapV;
  8924. switch (texture.wrapV) {
  8925. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8926. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8927. break;
  8928. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8929. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8930. break;
  8931. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8932. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8933. break;
  8934. }
  8935. }
  8936. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8937. }
  8938. };
  8939. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8940. if (channel < 0) {
  8941. return;
  8942. }
  8943. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8944. this._textureUnits = new Int32Array(textures.length);
  8945. }
  8946. for (var i = 0; i < textures.length; i++) {
  8947. this._textureUnits[i] = channel + i;
  8948. }
  8949. this._gl.uniform1iv(uniform, this._textureUnits);
  8950. for (var index = 0; index < textures.length; index++) {
  8951. this._setTexture(channel + index, textures[index]);
  8952. }
  8953. };
  8954. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8955. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8956. var value = texture.anisotropicFilteringLevel;
  8957. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8958. value = 1;
  8959. }
  8960. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8961. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8962. texture._cachedAnisotropicFilteringLevel = value;
  8963. }
  8964. };
  8965. Engine.prototype.readPixels = function (x, y, width, height) {
  8966. var data = new Uint8Array(height * width * 4);
  8967. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8968. return data;
  8969. };
  8970. /**
  8971. * Add an externaly attached data from its key.
  8972. * This method call will fail and return false, if such key already exists.
  8973. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8974. * @param key the unique key that identifies the data
  8975. * @param data the data object to associate to the key for this Engine instance
  8976. * @return true if no such key were already present and the data was added successfully, false otherwise
  8977. */
  8978. Engine.prototype.addExternalData = function (key, data) {
  8979. return this._externalData.add(key, data);
  8980. };
  8981. /**
  8982. * Get an externaly attached data from its key
  8983. * @param key the unique key that identifies the data
  8984. * @return the associated data, if present (can be null), or undefined if not present
  8985. */
  8986. Engine.prototype.getExternalData = function (key) {
  8987. return this._externalData.get(key);
  8988. };
  8989. /**
  8990. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8991. * @param key the unique key that identifies the data
  8992. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8993. * @return the associated data, can be null if the factory returned null.
  8994. */
  8995. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8996. return this._externalData.getOrAddWithFactory(key, factory);
  8997. };
  8998. /**
  8999. * Remove an externaly attached data from the Engine instance
  9000. * @param key the unique key that identifies the data
  9001. * @return true if the data was successfully removed, false if it doesn't exist
  9002. */
  9003. Engine.prototype.removeExternalData = function (key) {
  9004. return this._externalData.remove(key);
  9005. };
  9006. Engine.prototype.releaseInternalTexture = function (texture) {
  9007. if (!texture) {
  9008. return;
  9009. }
  9010. texture.references--;
  9011. // Final reference ?
  9012. if (texture.references === 0) {
  9013. var texturesCache = this.getLoadedTexturesCache();
  9014. var index = texturesCache.indexOf(texture);
  9015. if (index > -1) {
  9016. texturesCache.splice(index, 1);
  9017. }
  9018. this._releaseTexture(texture);
  9019. }
  9020. };
  9021. Engine.prototype.unbindAllAttributes = function () {
  9022. if (this._mustWipeVertexAttributes) {
  9023. this._mustWipeVertexAttributes = false;
  9024. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  9025. this._gl.disableVertexAttribArray(i);
  9026. this._vertexAttribArraysEnabled[i] = false;
  9027. this._currentBufferPointers[i] = null;
  9028. }
  9029. return;
  9030. }
  9031. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  9032. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  9033. continue;
  9034. }
  9035. this._gl.disableVertexAttribArray(i);
  9036. this._vertexAttribArraysEnabled[i] = false;
  9037. this._currentBufferPointers[i] = null;
  9038. }
  9039. };
  9040. // Dispose
  9041. Engine.prototype.dispose = function () {
  9042. this.hideLoadingUI();
  9043. this.stopRenderLoop();
  9044. // Release scenes
  9045. while (this.scenes.length) {
  9046. this.scenes[0].dispose();
  9047. }
  9048. // Release audio engine
  9049. Engine.audioEngine.dispose();
  9050. // Release effects
  9051. for (var name in this._compiledEffects) {
  9052. this._gl.deleteProgram(this._compiledEffects[name]._program);
  9053. }
  9054. // Unbind
  9055. this.unbindAllAttributes();
  9056. this._gl = null;
  9057. //WebVR
  9058. this.disableVR();
  9059. // Events
  9060. window.removeEventListener("blur", this._onBlur);
  9061. window.removeEventListener("focus", this._onFocus);
  9062. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  9063. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  9064. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  9065. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  9066. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  9067. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  9068. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  9069. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  9070. };
  9071. // Loading screen
  9072. Engine.prototype.displayLoadingUI = function () {
  9073. this._loadingScreen.displayLoadingUI();
  9074. };
  9075. Engine.prototype.hideLoadingUI = function () {
  9076. this._loadingScreen.hideLoadingUI();
  9077. };
  9078. Object.defineProperty(Engine.prototype, "loadingScreen", {
  9079. get: function () {
  9080. return this._loadingScreen;
  9081. },
  9082. set: function (loadingScreen) {
  9083. this._loadingScreen = loadingScreen;
  9084. },
  9085. enumerable: true,
  9086. configurable: true
  9087. });
  9088. Object.defineProperty(Engine.prototype, "loadingUIText", {
  9089. set: function (text) {
  9090. this._loadingScreen.loadingUIText = text;
  9091. },
  9092. enumerable: true,
  9093. configurable: true
  9094. });
  9095. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  9096. set: function (color) {
  9097. this._loadingScreen.loadingUIBackgroundColor = color;
  9098. },
  9099. enumerable: true,
  9100. configurable: true
  9101. });
  9102. Engine.prototype.attachContextLostEvent = function (callback) {
  9103. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  9104. };
  9105. Engine.prototype.attachContextRestoredEvent = function (callback) {
  9106. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  9107. };
  9108. Engine.prototype.getVertexShaderSource = function (program) {
  9109. var shaders = this._gl.getAttachedShaders(program);
  9110. return this._gl.getShaderSource(shaders[0]);
  9111. };
  9112. Engine.prototype.getFragmentShaderSource = function (program) {
  9113. var shaders = this._gl.getAttachedShaders(program);
  9114. return this._gl.getShaderSource(shaders[1]);
  9115. };
  9116. // FPS
  9117. Engine.prototype.getFps = function () {
  9118. return this.fps;
  9119. };
  9120. Engine.prototype.getDeltaTime = function () {
  9121. return this.deltaTime;
  9122. };
  9123. Engine.prototype._measureFps = function () {
  9124. this.previousFramesDuration.push(BABYLON.Tools.Now);
  9125. var length = this.previousFramesDuration.length;
  9126. if (length >= 2) {
  9127. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  9128. }
  9129. if (length >= this.fpsRange) {
  9130. if (length > this.fpsRange) {
  9131. this.previousFramesDuration.splice(0, 1);
  9132. length = this.previousFramesDuration.length;
  9133. }
  9134. var sum = 0;
  9135. for (var id = 0; id < length - 1; id++) {
  9136. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  9137. }
  9138. this.fps = 1000.0 / (sum / (length - 1));
  9139. }
  9140. };
  9141. Engine.prototype._canRenderToFloatFramebuffer = function () {
  9142. if (this._webGLVersion > 1) {
  9143. return this._caps.colorBufferFloat;
  9144. }
  9145. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  9146. };
  9147. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  9148. if (this._webGLVersion > 1) {
  9149. return this._caps.colorBufferFloat;
  9150. }
  9151. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  9152. };
  9153. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9154. Engine.prototype._canRenderToFramebuffer = function (type) {
  9155. var gl = this._gl;
  9156. //clear existing errors
  9157. while (gl.getError() !== gl.NO_ERROR) { }
  9158. var successful = true;
  9159. var texture = gl.createTexture();
  9160. gl.bindTexture(gl.TEXTURE_2D, texture);
  9161. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9162. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9163. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9164. var fb = gl.createFramebuffer();
  9165. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9166. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  9167. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9168. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  9169. successful = successful && (gl.getError() === gl.NO_ERROR);
  9170. //try render by clearing frame buffer's color buffer
  9171. if (successful) {
  9172. gl.clear(gl.COLOR_BUFFER_BIT);
  9173. successful = successful && (gl.getError() === gl.NO_ERROR);
  9174. }
  9175. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  9176. if (successful) {
  9177. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  9178. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9179. var readFormat = gl.RGBA;
  9180. var readType = gl.UNSIGNED_BYTE;
  9181. var buffer = new Uint8Array(4);
  9182. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  9183. successful = successful && (gl.getError() === gl.NO_ERROR);
  9184. }
  9185. //clean up
  9186. gl.deleteTexture(texture);
  9187. gl.deleteFramebuffer(fb);
  9188. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9189. //clear accumulated errors
  9190. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  9191. return successful;
  9192. };
  9193. Engine.prototype._getWebGLTextureType = function (type) {
  9194. if (type === Engine.TEXTURETYPE_FLOAT) {
  9195. return this._gl.FLOAT;
  9196. }
  9197. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9198. // Add Half Float Constant.
  9199. return Engine.HALF_FLOAT_OES;
  9200. }
  9201. return this._gl.UNSIGNED_BYTE;
  9202. };
  9203. ;
  9204. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  9205. if (this._webGLVersion === 1) {
  9206. return this._gl.RGBA;
  9207. }
  9208. if (type === Engine.TEXTURETYPE_FLOAT) {
  9209. return Engine.RGBA32F;
  9210. }
  9211. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  9212. return Engine.RGBA16F;
  9213. }
  9214. return this._gl.RGBA;
  9215. };
  9216. ;
  9217. // Statics
  9218. Engine.isSupported = function () {
  9219. try {
  9220. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9221. if (navigator.isCocoonJS) {
  9222. return true;
  9223. }
  9224. var tempcanvas = document.createElement("canvas");
  9225. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9226. return gl != null && !!window.WebGLRenderingContext;
  9227. }
  9228. catch (e) {
  9229. return false;
  9230. }
  9231. };
  9232. return Engine;
  9233. }());
  9234. // Const statics
  9235. Engine._ALPHA_DISABLE = 0;
  9236. Engine._ALPHA_ADD = 1;
  9237. Engine._ALPHA_COMBINE = 2;
  9238. Engine._ALPHA_SUBTRACT = 3;
  9239. Engine._ALPHA_MULTIPLY = 4;
  9240. Engine._ALPHA_MAXIMIZED = 5;
  9241. Engine._ALPHA_ONEONE = 6;
  9242. Engine._ALPHA_PREMULTIPLIED = 7;
  9243. Engine._DELAYLOADSTATE_NONE = 0;
  9244. Engine._DELAYLOADSTATE_LOADED = 1;
  9245. Engine._DELAYLOADSTATE_LOADING = 2;
  9246. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9247. Engine._TEXTUREFORMAT_ALPHA = 0;
  9248. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9249. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9250. Engine._TEXTUREFORMAT_RGB = 4;
  9251. Engine._TEXTUREFORMAT_RGBA = 5;
  9252. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9253. Engine._TEXTURETYPE_FLOAT = 1;
  9254. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9255. // Depht or Stencil test Constants.
  9256. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9257. 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.
  9258. 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.
  9259. 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.
  9260. 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.
  9261. 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.
  9262. 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.
  9263. 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.
  9264. Engine.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  9265. Engine.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  9266. Engine.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  9267. // Stencil Actions Constants.
  9268. Engine._KEEP = 0x1E00;
  9269. Engine._REPLACE = 0x1E01;
  9270. Engine._INCR = 0x1E02;
  9271. Engine._DECR = 0x1E03;
  9272. Engine._INVERT = 0x150A;
  9273. Engine._INCR_WRAP = 0x8507;
  9274. Engine._DECR_WRAP = 0x8508;
  9275. // Updatable statics so stick with vars here
  9276. Engine.CollisionsEpsilon = 0.001;
  9277. Engine.CodeRepository = "src/";
  9278. Engine.ShadersRepository = "src/Shaders/";
  9279. BABYLON.Engine = Engine;
  9280. })(BABYLON || (BABYLON = {}));
  9281. //# sourceMappingURL=babylon.engine.js.map
  9282. var BABYLON;
  9283. (function (BABYLON) {
  9284. /**
  9285. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9286. */
  9287. var Node = (function () {
  9288. /**
  9289. * @constructor
  9290. * @param {string} name - the name and id to be given to this node
  9291. * @param {BABYLON.Scene} the scene this node will be added to
  9292. */
  9293. function Node(name, scene) {
  9294. this.state = "";
  9295. this.metadata = null;
  9296. this.doNotSerialize = false;
  9297. this.animations = new Array();
  9298. this._ranges = {};
  9299. this._childrenFlag = -1;
  9300. this._isEnabled = true;
  9301. this._isReady = true;
  9302. this._currentRenderId = -1;
  9303. this._parentRenderId = -1;
  9304. /**
  9305. * An event triggered when the mesh is disposed.
  9306. * @type {BABYLON.Observable}
  9307. */
  9308. this.onDisposeObservable = new BABYLON.Observable();
  9309. this.name = name;
  9310. this.id = name;
  9311. this._scene = scene;
  9312. this._initCache();
  9313. }
  9314. Object.defineProperty(Node.prototype, "parent", {
  9315. get: function () {
  9316. return this._parentNode;
  9317. },
  9318. set: function (parent) {
  9319. if (this._parentNode === parent) {
  9320. return;
  9321. }
  9322. if (this._parentNode) {
  9323. var index = this._parentNode._children.indexOf(this);
  9324. if (index !== -1) {
  9325. this._parentNode._children.splice(index, 1);
  9326. }
  9327. }
  9328. this._parentNode = parent;
  9329. if (this._parentNode) {
  9330. if (!this._parentNode._children) {
  9331. this._parentNode._children = new Array();
  9332. }
  9333. this._parentNode._children.push(this);
  9334. }
  9335. },
  9336. enumerable: true,
  9337. configurable: true
  9338. });
  9339. Node.prototype.getClassName = function () {
  9340. return "Node";
  9341. };
  9342. Object.defineProperty(Node.prototype, "onDispose", {
  9343. set: function (callback) {
  9344. if (this._onDisposeObserver) {
  9345. this.onDisposeObservable.remove(this._onDisposeObserver);
  9346. }
  9347. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9348. },
  9349. enumerable: true,
  9350. configurable: true
  9351. });
  9352. Node.prototype.getScene = function () {
  9353. return this._scene;
  9354. };
  9355. Node.prototype.getEngine = function () {
  9356. return this._scene.getEngine();
  9357. };
  9358. // override it in derived class
  9359. Node.prototype.getWorldMatrix = function () {
  9360. return BABYLON.Matrix.Identity();
  9361. };
  9362. // override it in derived class if you add new variables to the cache
  9363. // and call the parent class method
  9364. Node.prototype._initCache = function () {
  9365. this._cache = {};
  9366. this._cache.parent = undefined;
  9367. };
  9368. Node.prototype.updateCache = function (force) {
  9369. if (!force && this.isSynchronized())
  9370. return;
  9371. this._cache.parent = this.parent;
  9372. this._updateCache();
  9373. };
  9374. // override it in derived class if you add new variables to the cache
  9375. // and call the parent class method if !ignoreParentClass
  9376. Node.prototype._updateCache = function (ignoreParentClass) {
  9377. };
  9378. // override it in derived class if you add new variables to the cache
  9379. Node.prototype._isSynchronized = function () {
  9380. return true;
  9381. };
  9382. Node.prototype._markSyncedWithParent = function () {
  9383. this._parentRenderId = this.parent._currentRenderId;
  9384. };
  9385. Node.prototype.isSynchronizedWithParent = function () {
  9386. if (!this.parent) {
  9387. return true;
  9388. }
  9389. if (this._parentRenderId !== this.parent._currentRenderId) {
  9390. return false;
  9391. }
  9392. return this.parent.isSynchronized();
  9393. };
  9394. Node.prototype.isSynchronized = function (updateCache) {
  9395. var check = this.hasNewParent();
  9396. check = check || !this.isSynchronizedWithParent();
  9397. check = check || !this._isSynchronized();
  9398. if (updateCache)
  9399. this.updateCache(true);
  9400. return !check;
  9401. };
  9402. Node.prototype.hasNewParent = function (update) {
  9403. if (this._cache.parent === this.parent)
  9404. return false;
  9405. if (update)
  9406. this._cache.parent = this.parent;
  9407. return true;
  9408. };
  9409. /**
  9410. * Is this node ready to be used/rendered
  9411. * @return {boolean} is it ready
  9412. */
  9413. Node.prototype.isReady = function () {
  9414. return this._isReady;
  9415. };
  9416. /**
  9417. * Is this node enabled.
  9418. * If the node has a parent and is enabled, the parent will be inspected as well.
  9419. * @return {boolean} whether this node (and its parent) is enabled.
  9420. * @see setEnabled
  9421. */
  9422. Node.prototype.isEnabled = function () {
  9423. if (!this._isEnabled) {
  9424. return false;
  9425. }
  9426. if (this.parent) {
  9427. return this.parent.isEnabled();
  9428. }
  9429. return true;
  9430. };
  9431. /**
  9432. * Set the enabled state of this node.
  9433. * @param {boolean} value - the new enabled state
  9434. * @see isEnabled
  9435. */
  9436. Node.prototype.setEnabled = function (value) {
  9437. this._isEnabled = value;
  9438. };
  9439. /**
  9440. * Is this node a descendant of the given node.
  9441. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9442. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9443. * @see parent
  9444. */
  9445. Node.prototype.isDescendantOf = function (ancestor) {
  9446. if (this.parent) {
  9447. if (this.parent === ancestor) {
  9448. return true;
  9449. }
  9450. return this.parent.isDescendantOf(ancestor);
  9451. }
  9452. return false;
  9453. };
  9454. /**
  9455. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9456. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9457. * @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.
  9458. * @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.
  9459. */
  9460. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9461. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9462. if (!this._children) {
  9463. return;
  9464. }
  9465. for (var index = 0; index < this._children.length; index++) {
  9466. var item = this._children[index];
  9467. if (!predicate || predicate(item)) {
  9468. results.push(item);
  9469. }
  9470. if (!directDescendantsOnly) {
  9471. item._getDescendants(results, false, predicate);
  9472. }
  9473. }
  9474. };
  9475. /**
  9476. * Will return all nodes that have this node as ascendant.
  9477. * @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.
  9478. * @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.
  9479. * @return {BABYLON.Node[]} all children nodes of all types.
  9480. */
  9481. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9482. var results = [];
  9483. this._getDescendants(results, directDescendantsOnly, predicate);
  9484. return results;
  9485. };
  9486. /**
  9487. * @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.
  9488. * @Deprecated, legacy support.
  9489. * use getDecendants instead.
  9490. */
  9491. Node.prototype.getChildren = function (predicate) {
  9492. return this.getDescendants(true, predicate);
  9493. };
  9494. /**
  9495. * Get all child-meshes of this node.
  9496. */
  9497. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9498. var results = [];
  9499. this._getDescendants(results, directDecendantsOnly, function (node) {
  9500. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9501. });
  9502. return results;
  9503. };
  9504. Node.prototype._setReady = function (state) {
  9505. if (state === this._isReady) {
  9506. return;
  9507. }
  9508. if (!state) {
  9509. this._isReady = false;
  9510. return;
  9511. }
  9512. this._isReady = true;
  9513. if (this.onReady) {
  9514. this.onReady(this);
  9515. }
  9516. };
  9517. Node.prototype.getAnimationByName = function (name) {
  9518. for (var i = 0; i < this.animations.length; i++) {
  9519. var animation = this.animations[i];
  9520. if (animation.name === name) {
  9521. return animation;
  9522. }
  9523. }
  9524. return null;
  9525. };
  9526. Node.prototype.createAnimationRange = function (name, from, to) {
  9527. // check name not already in use
  9528. if (!this._ranges[name]) {
  9529. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9530. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9531. if (this.animations[i]) {
  9532. this.animations[i].createRange(name, from, to);
  9533. }
  9534. }
  9535. }
  9536. };
  9537. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9538. if (deleteFrames === void 0) { deleteFrames = true; }
  9539. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9540. if (this.animations[i]) {
  9541. this.animations[i].deleteRange(name, deleteFrames);
  9542. }
  9543. }
  9544. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9545. };
  9546. Node.prototype.getAnimationRange = function (name) {
  9547. return this._ranges[name];
  9548. };
  9549. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9550. var range = this.getAnimationRange(name);
  9551. if (!range) {
  9552. return null;
  9553. }
  9554. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9555. };
  9556. Node.prototype.serializeAnimationRanges = function () {
  9557. var serializationRanges = [];
  9558. for (var name in this._ranges) {
  9559. var range = {};
  9560. range.name = name;
  9561. range.from = this._ranges[name].from;
  9562. range.to = this._ranges[name].to;
  9563. serializationRanges.push(range);
  9564. }
  9565. return serializationRanges;
  9566. };
  9567. Node.prototype.dispose = function () {
  9568. this.parent = null;
  9569. // Callback
  9570. this.onDisposeObservable.notifyObservers(this);
  9571. this.onDisposeObservable.clear();
  9572. };
  9573. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9574. if (parsedNode.ranges) {
  9575. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9576. var data = parsedNode.ranges[index];
  9577. node.createAnimationRange(data.name, data.from, data.to);
  9578. }
  9579. }
  9580. };
  9581. return Node;
  9582. }());
  9583. __decorate([
  9584. BABYLON.serialize()
  9585. ], Node.prototype, "name", void 0);
  9586. __decorate([
  9587. BABYLON.serialize()
  9588. ], Node.prototype, "id", void 0);
  9589. __decorate([
  9590. BABYLON.serialize()
  9591. ], Node.prototype, "uniqueId", void 0);
  9592. __decorate([
  9593. BABYLON.serialize()
  9594. ], Node.prototype, "state", void 0);
  9595. __decorate([
  9596. BABYLON.serialize()
  9597. ], Node.prototype, "metadata", void 0);
  9598. BABYLON.Node = Node;
  9599. })(BABYLON || (BABYLON = {}));
  9600. //# sourceMappingURL=babylon.node.js.map
  9601. var BABYLON;
  9602. (function (BABYLON) {
  9603. var FilesInput = (function () {
  9604. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9605. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9606. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9607. this._engine = p_engine;
  9608. this._canvas = p_canvas;
  9609. this._currentScene = p_scene;
  9610. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9611. this._progressCallback = p_progressCallback;
  9612. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9613. this._textureLoadingCallback = p_textureLoadingCallback;
  9614. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9615. }
  9616. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9617. var _this = this;
  9618. if (p_elementToMonitor) {
  9619. this._elementToMonitor = p_elementToMonitor;
  9620. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9621. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9622. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9623. }
  9624. };
  9625. FilesInput.prototype.renderFunction = function () {
  9626. if (this._additionnalRenderLoopLogicCallback) {
  9627. this._additionnalRenderLoopLogicCallback();
  9628. }
  9629. if (this._currentScene) {
  9630. if (this._textureLoadingCallback) {
  9631. var remaining = this._currentScene.getWaitingItemsCount();
  9632. if (remaining > 0) {
  9633. this._textureLoadingCallback(remaining);
  9634. }
  9635. }
  9636. this._currentScene.render();
  9637. }
  9638. };
  9639. FilesInput.prototype.drag = function (e) {
  9640. e.stopPropagation();
  9641. e.preventDefault();
  9642. };
  9643. FilesInput.prototype.drop = function (eventDrop) {
  9644. eventDrop.stopPropagation();
  9645. eventDrop.preventDefault();
  9646. this.loadFiles(eventDrop);
  9647. };
  9648. FilesInput.prototype.loadFiles = function (event) {
  9649. if (this._startingProcessingFilesCallback)
  9650. this._startingProcessingFilesCallback();
  9651. // Handling data transfer via drag'n'drop
  9652. if (event && event.dataTransfer && event.dataTransfer.files) {
  9653. this._filesToLoad = event.dataTransfer.files;
  9654. }
  9655. // Handling files from input files
  9656. if (event && event.target && event.target.files) {
  9657. this._filesToLoad = event.target.files;
  9658. }
  9659. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9660. for (var i = 0; i < this._filesToLoad.length; i++) {
  9661. var name_1 = this._filesToLoad[i].name.toLowerCase();
  9662. var extension = name_1.split('.').pop();
  9663. var type = this._filesToLoad[i].type;
  9664. if (extension === "jpg" || extension === "png" || extension === "bmp" || extension === "jpeg" ||
  9665. type === "image/jpeg" || type === "image/png" || type === "image/bmp") {
  9666. FilesInput.FilesTextures[name_1] = this._filesToLoad[i];
  9667. }
  9668. else {
  9669. if ((extension === "babylon" || extension === "stl" || extension === "obj")
  9670. && name_1.indexOf(".binary.babylon") === -1 && name_1.indexOf(".incremental.babylon") === -1) {
  9671. this._sceneFileToLoad = this._filesToLoad[i];
  9672. }
  9673. else {
  9674. FilesInput.FilesToLoad[name_1] = this._filesToLoad[i];
  9675. }
  9676. }
  9677. }
  9678. this.reload();
  9679. }
  9680. };
  9681. FilesInput.prototype.reload = function () {
  9682. var _this = this;
  9683. var that = this;
  9684. // If a ".babylon" file has been provided
  9685. if (this._sceneFileToLoad) {
  9686. if (this._currentScene) {
  9687. if (BABYLON.Tools.errorsCount > 0) {
  9688. BABYLON.Tools.ClearLogCache();
  9689. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9690. }
  9691. this._engine.stopRenderLoop();
  9692. this._currentScene.dispose();
  9693. }
  9694. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9695. that._currentScene = newScene;
  9696. // Wait for textures and shaders to be ready
  9697. that._currentScene.executeWhenReady(function () {
  9698. // Attach camera to canvas inputs
  9699. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9700. that._currentScene.createDefaultCameraOrLight();
  9701. }
  9702. that._currentScene.activeCamera.attachControl(that._canvas);
  9703. if (that._sceneLoadedCallback) {
  9704. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9705. }
  9706. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9707. });
  9708. }, function (progress) {
  9709. if (_this._progressCallback) {
  9710. _this._progressCallback(progress);
  9711. }
  9712. });
  9713. }
  9714. else {
  9715. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9716. }
  9717. };
  9718. return FilesInput;
  9719. }());
  9720. FilesInput.FilesTextures = new Array();
  9721. FilesInput.FilesToLoad = new Array();
  9722. BABYLON.FilesInput = FilesInput;
  9723. })(BABYLON || (BABYLON = {}));
  9724. //# sourceMappingURL=babylon.filesInput.js.map
  9725. var BABYLON;
  9726. (function (BABYLON) {
  9727. var IntersectionInfo = (function () {
  9728. function IntersectionInfo(bu, bv, distance) {
  9729. this.bu = bu;
  9730. this.bv = bv;
  9731. this.distance = distance;
  9732. this.faceId = 0;
  9733. this.subMeshId = 0;
  9734. }
  9735. return IntersectionInfo;
  9736. }());
  9737. BABYLON.IntersectionInfo = IntersectionInfo;
  9738. var PickingInfo = (function () {
  9739. function PickingInfo() {
  9740. this.hit = false;
  9741. this.distance = 0;
  9742. this.pickedPoint = null;
  9743. this.pickedMesh = null;
  9744. this.bu = 0;
  9745. this.bv = 0;
  9746. this.faceId = -1;
  9747. this.subMeshId = 0;
  9748. this.pickedSprite = null;
  9749. }
  9750. // Methods
  9751. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9752. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9753. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9754. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9755. return null;
  9756. }
  9757. var indices = this.pickedMesh.getIndices();
  9758. var result;
  9759. if (useVerticesNormals) {
  9760. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9761. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9762. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9763. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9764. normal0 = normal0.scale(this.bu);
  9765. normal1 = normal1.scale(this.bv);
  9766. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9767. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9768. }
  9769. else {
  9770. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9771. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9772. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9773. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9774. var p1p2 = vertex1.subtract(vertex2);
  9775. var p3p2 = vertex3.subtract(vertex2);
  9776. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9777. }
  9778. if (useWorldCoordinates) {
  9779. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9780. }
  9781. return BABYLON.Vector3.Normalize(result);
  9782. };
  9783. PickingInfo.prototype.getTextureCoordinates = function () {
  9784. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9785. return null;
  9786. }
  9787. var indices = this.pickedMesh.getIndices();
  9788. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9789. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9790. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9791. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9792. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9793. uv1 = uv1.scale(this.bu);
  9794. uv2 = uv2.scale(this.bv);
  9795. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9796. };
  9797. return PickingInfo;
  9798. }());
  9799. BABYLON.PickingInfo = PickingInfo;
  9800. })(BABYLON || (BABYLON = {}));
  9801. //# sourceMappingURL=babylon.pickingInfo.js.map
  9802. var BABYLON;
  9803. (function (BABYLON) {
  9804. var BoundingSphere = (function () {
  9805. function BoundingSphere(minimum, maximum) {
  9806. this.minimum = minimum;
  9807. this.maximum = maximum;
  9808. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9809. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9810. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9811. this.radius = distance * 0.5;
  9812. this.centerWorld = BABYLON.Vector3.Zero();
  9813. this._update(BABYLON.Matrix.Identity());
  9814. }
  9815. // Methods
  9816. BoundingSphere.prototype._update = function (world) {
  9817. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9818. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9819. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9820. };
  9821. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9822. for (var i = 0; i < 6; i++) {
  9823. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9824. return false;
  9825. }
  9826. return true;
  9827. };
  9828. BoundingSphere.prototype.intersectsPoint = function (point) {
  9829. var x = this.centerWorld.x - point.x;
  9830. var y = this.centerWorld.y - point.y;
  9831. var z = this.centerWorld.z - point.z;
  9832. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9833. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9834. return false;
  9835. return true;
  9836. };
  9837. // Statics
  9838. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9839. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9840. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9841. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9842. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9843. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9844. return false;
  9845. return true;
  9846. };
  9847. return BoundingSphere;
  9848. }());
  9849. BABYLON.BoundingSphere = BoundingSphere;
  9850. })(BABYLON || (BABYLON = {}));
  9851. //# sourceMappingURL=babylon.boundingSphere.js.map
  9852. var BABYLON;
  9853. (function (BABYLON) {
  9854. var BoundingBox = (function () {
  9855. function BoundingBox(minimum, maximum) {
  9856. this.minimum = minimum;
  9857. this.maximum = maximum;
  9858. this.vectors = new Array();
  9859. this.vectorsWorld = new Array();
  9860. // Bounding vectors
  9861. this.vectors.push(this.minimum.clone());
  9862. this.vectors.push(this.maximum.clone());
  9863. this.vectors.push(this.minimum.clone());
  9864. this.vectors[2].x = this.maximum.x;
  9865. this.vectors.push(this.minimum.clone());
  9866. this.vectors[3].y = this.maximum.y;
  9867. this.vectors.push(this.minimum.clone());
  9868. this.vectors[4].z = this.maximum.z;
  9869. this.vectors.push(this.maximum.clone());
  9870. this.vectors[5].z = this.minimum.z;
  9871. this.vectors.push(this.maximum.clone());
  9872. this.vectors[6].x = this.minimum.x;
  9873. this.vectors.push(this.maximum.clone());
  9874. this.vectors[7].y = this.minimum.y;
  9875. // OBB
  9876. this.center = this.maximum.add(this.minimum).scale(0.5);
  9877. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9878. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9879. // World
  9880. for (var index = 0; index < this.vectors.length; index++) {
  9881. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9882. }
  9883. this.minimumWorld = BABYLON.Vector3.Zero();
  9884. this.maximumWorld = BABYLON.Vector3.Zero();
  9885. this._update(BABYLON.Matrix.Identity());
  9886. }
  9887. // Methods
  9888. BoundingBox.prototype.getWorldMatrix = function () {
  9889. return this._worldMatrix;
  9890. };
  9891. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9892. this._worldMatrix.copyFrom(matrix);
  9893. return this;
  9894. };
  9895. BoundingBox.prototype._update = function (world) {
  9896. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9897. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9898. for (var index = 0; index < this.vectors.length; index++) {
  9899. var v = this.vectorsWorld[index];
  9900. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9901. if (v.x < this.minimumWorld.x)
  9902. this.minimumWorld.x = v.x;
  9903. if (v.y < this.minimumWorld.y)
  9904. this.minimumWorld.y = v.y;
  9905. if (v.z < this.minimumWorld.z)
  9906. this.minimumWorld.z = v.z;
  9907. if (v.x > this.maximumWorld.x)
  9908. this.maximumWorld.x = v.x;
  9909. if (v.y > this.maximumWorld.y)
  9910. this.maximumWorld.y = v.y;
  9911. if (v.z > this.maximumWorld.z)
  9912. this.maximumWorld.z = v.z;
  9913. }
  9914. // OBB
  9915. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9916. this.center.scaleInPlace(0.5);
  9917. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9918. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9919. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9920. this._worldMatrix = world;
  9921. };
  9922. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9923. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9924. };
  9925. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9926. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9927. };
  9928. BoundingBox.prototype.intersectsPoint = function (point) {
  9929. var delta = -BABYLON.Epsilon;
  9930. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9931. return false;
  9932. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9933. return false;
  9934. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9935. return false;
  9936. return true;
  9937. };
  9938. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9939. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9940. };
  9941. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9942. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9943. return false;
  9944. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9945. return false;
  9946. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9947. return false;
  9948. return true;
  9949. };
  9950. // Statics
  9951. BoundingBox.Intersects = function (box0, box1) {
  9952. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9953. return false;
  9954. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9955. return false;
  9956. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9957. return false;
  9958. return true;
  9959. };
  9960. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9961. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9962. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9963. return (num <= (sphereRadius * sphereRadius));
  9964. };
  9965. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9966. for (var p = 0; p < 6; p++) {
  9967. for (var i = 0; i < 8; i++) {
  9968. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9969. return false;
  9970. }
  9971. }
  9972. }
  9973. return true;
  9974. };
  9975. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9976. for (var p = 0; p < 6; p++) {
  9977. var inCount = 8;
  9978. for (var i = 0; i < 8; i++) {
  9979. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9980. --inCount;
  9981. }
  9982. else {
  9983. break;
  9984. }
  9985. }
  9986. if (inCount === 0)
  9987. return false;
  9988. }
  9989. return true;
  9990. };
  9991. return BoundingBox;
  9992. }());
  9993. BABYLON.BoundingBox = BoundingBox;
  9994. })(BABYLON || (BABYLON = {}));
  9995. //# sourceMappingURL=babylon.boundingBox.js.map
  9996. var BABYLON;
  9997. (function (BABYLON) {
  9998. var computeBoxExtents = function (axis, box) {
  9999. var p = BABYLON.Vector3.Dot(box.center, axis);
  10000. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  10001. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  10002. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  10003. var r = r0 + r1 + r2;
  10004. return {
  10005. min: p - r,
  10006. max: p + r
  10007. };
  10008. };
  10009. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  10010. var axisOverlap = function (axis, box0, box1) {
  10011. var result0 = computeBoxExtents(axis, box0);
  10012. var result1 = computeBoxExtents(axis, box1);
  10013. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  10014. };
  10015. var BoundingInfo = (function () {
  10016. function BoundingInfo(minimum, maximum) {
  10017. this.minimum = minimum;
  10018. this.maximum = maximum;
  10019. this._isLocked = false;
  10020. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  10021. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  10022. }
  10023. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  10024. get: function () {
  10025. return this._isLocked;
  10026. },
  10027. set: function (value) {
  10028. this._isLocked = value;
  10029. },
  10030. enumerable: true,
  10031. configurable: true
  10032. });
  10033. // Methods
  10034. BoundingInfo.prototype.update = function (world) {
  10035. if (this._isLocked) {
  10036. return;
  10037. }
  10038. this.boundingBox._update(world);
  10039. this.boundingSphere._update(world);
  10040. };
  10041. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  10042. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  10043. return false;
  10044. return this.boundingBox.isInFrustum(frustumPlanes);
  10045. };
  10046. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  10047. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  10048. };
  10049. BoundingInfo.prototype._checkCollision = function (collider) {
  10050. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  10051. };
  10052. BoundingInfo.prototype.intersectsPoint = function (point) {
  10053. if (!this.boundingSphere.centerWorld) {
  10054. return false;
  10055. }
  10056. if (!this.boundingSphere.intersectsPoint(point)) {
  10057. return false;
  10058. }
  10059. if (!this.boundingBox.intersectsPoint(point)) {
  10060. return false;
  10061. }
  10062. return true;
  10063. };
  10064. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  10065. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  10066. return false;
  10067. }
  10068. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  10069. return false;
  10070. }
  10071. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  10072. return false;
  10073. }
  10074. if (!precise) {
  10075. return true;
  10076. }
  10077. var box0 = this.boundingBox;
  10078. var box1 = boundingInfo.boundingBox;
  10079. if (!axisOverlap(box0.directions[0], box0, box1))
  10080. return false;
  10081. if (!axisOverlap(box0.directions[1], box0, box1))
  10082. return false;
  10083. if (!axisOverlap(box0.directions[2], box0, box1))
  10084. return false;
  10085. if (!axisOverlap(box1.directions[0], box0, box1))
  10086. return false;
  10087. if (!axisOverlap(box1.directions[1], box0, box1))
  10088. return false;
  10089. if (!axisOverlap(box1.directions[2], box0, box1))
  10090. return false;
  10091. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  10092. return false;
  10093. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  10094. return false;
  10095. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  10096. return false;
  10097. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  10098. return false;
  10099. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  10100. return false;
  10101. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  10102. return false;
  10103. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  10104. return false;
  10105. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  10106. return false;
  10107. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  10108. return false;
  10109. return true;
  10110. };
  10111. return BoundingInfo;
  10112. }());
  10113. BABYLON.BoundingInfo = BoundingInfo;
  10114. })(BABYLON || (BABYLON = {}));
  10115. //# sourceMappingURL=babylon.boundingInfo.js.map
  10116. var BABYLON;
  10117. (function (BABYLON) {
  10118. var Ray = (function () {
  10119. function Ray(origin, direction, length) {
  10120. if (length === void 0) { length = Number.MAX_VALUE; }
  10121. this.origin = origin;
  10122. this.direction = direction;
  10123. this.length = length;
  10124. }
  10125. // Methods
  10126. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  10127. var d = 0.0;
  10128. var maxValue = Number.MAX_VALUE;
  10129. var inv;
  10130. var min;
  10131. var max;
  10132. var temp;
  10133. if (Math.abs(this.direction.x) < 0.0000001) {
  10134. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  10135. return false;
  10136. }
  10137. }
  10138. else {
  10139. inv = 1.0 / this.direction.x;
  10140. min = (minimum.x - this.origin.x) * inv;
  10141. max = (maximum.x - this.origin.x) * inv;
  10142. if (max === -Infinity) {
  10143. max = Infinity;
  10144. }
  10145. if (min > max) {
  10146. temp = min;
  10147. min = max;
  10148. max = temp;
  10149. }
  10150. d = Math.max(min, d);
  10151. maxValue = Math.min(max, maxValue);
  10152. if (d > maxValue) {
  10153. return false;
  10154. }
  10155. }
  10156. if (Math.abs(this.direction.y) < 0.0000001) {
  10157. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  10158. return false;
  10159. }
  10160. }
  10161. else {
  10162. inv = 1.0 / this.direction.y;
  10163. min = (minimum.y - this.origin.y) * inv;
  10164. max = (maximum.y - this.origin.y) * inv;
  10165. if (max === -Infinity) {
  10166. max = Infinity;
  10167. }
  10168. if (min > max) {
  10169. temp = min;
  10170. min = max;
  10171. max = temp;
  10172. }
  10173. d = Math.max(min, d);
  10174. maxValue = Math.min(max, maxValue);
  10175. if (d > maxValue) {
  10176. return false;
  10177. }
  10178. }
  10179. if (Math.abs(this.direction.z) < 0.0000001) {
  10180. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  10181. return false;
  10182. }
  10183. }
  10184. else {
  10185. inv = 1.0 / this.direction.z;
  10186. min = (minimum.z - this.origin.z) * inv;
  10187. max = (maximum.z - this.origin.z) * inv;
  10188. if (max === -Infinity) {
  10189. max = Infinity;
  10190. }
  10191. if (min > max) {
  10192. temp = min;
  10193. min = max;
  10194. max = temp;
  10195. }
  10196. d = Math.max(min, d);
  10197. maxValue = Math.min(max, maxValue);
  10198. if (d > maxValue) {
  10199. return false;
  10200. }
  10201. }
  10202. return true;
  10203. };
  10204. Ray.prototype.intersectsBox = function (box) {
  10205. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  10206. };
  10207. Ray.prototype.intersectsSphere = function (sphere) {
  10208. var x = sphere.center.x - this.origin.x;
  10209. var y = sphere.center.y - this.origin.y;
  10210. var z = sphere.center.z - this.origin.z;
  10211. var pyth = (x * x) + (y * y) + (z * z);
  10212. var rr = sphere.radius * sphere.radius;
  10213. if (pyth <= rr) {
  10214. return true;
  10215. }
  10216. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  10217. if (dot < 0.0) {
  10218. return false;
  10219. }
  10220. var temp = pyth - (dot * dot);
  10221. return temp <= rr;
  10222. };
  10223. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  10224. if (!this._edge1) {
  10225. this._edge1 = BABYLON.Vector3.Zero();
  10226. this._edge2 = BABYLON.Vector3.Zero();
  10227. this._pvec = BABYLON.Vector3.Zero();
  10228. this._tvec = BABYLON.Vector3.Zero();
  10229. this._qvec = BABYLON.Vector3.Zero();
  10230. }
  10231. vertex1.subtractToRef(vertex0, this._edge1);
  10232. vertex2.subtractToRef(vertex0, this._edge2);
  10233. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  10234. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  10235. if (det === 0) {
  10236. return null;
  10237. }
  10238. var invdet = 1 / det;
  10239. this.origin.subtractToRef(vertex0, this._tvec);
  10240. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  10241. if (bu < 0 || bu > 1.0) {
  10242. return null;
  10243. }
  10244. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  10245. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  10246. if (bv < 0 || bu + bv > 1.0) {
  10247. return null;
  10248. }
  10249. //check if the distance is longer than the predefined length.
  10250. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  10251. if (distance > this.length) {
  10252. return null;
  10253. }
  10254. return new BABYLON.IntersectionInfo(bu, bv, distance);
  10255. };
  10256. Ray.prototype.intersectsPlane = function (plane) {
  10257. var distance;
  10258. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  10259. if (Math.abs(result1) < 9.99999997475243E-07) {
  10260. return null;
  10261. }
  10262. else {
  10263. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  10264. distance = (-plane.d - result2) / result1;
  10265. if (distance < 0.0) {
  10266. if (distance < -9.99999997475243E-07) {
  10267. return null;
  10268. }
  10269. else {
  10270. return 0;
  10271. }
  10272. }
  10273. return distance;
  10274. }
  10275. };
  10276. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  10277. var tm = BABYLON.Tmp.Matrix[0];
  10278. mesh.getWorldMatrix().invertToRef(tm);
  10279. if (this._tmpRay) {
  10280. Ray.TransformToRef(this, tm, this._tmpRay);
  10281. }
  10282. else {
  10283. this._tmpRay = Ray.Transform(this, tm);
  10284. }
  10285. return mesh.intersects(this._tmpRay, fastCheck);
  10286. };
  10287. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  10288. if (results) {
  10289. results.length = 0;
  10290. }
  10291. else {
  10292. results = [];
  10293. }
  10294. for (var i = 0; i < meshes.length; i++) {
  10295. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  10296. if (pickInfo.hit) {
  10297. results.push(pickInfo);
  10298. }
  10299. }
  10300. results.sort(this._comparePickingInfo);
  10301. return results;
  10302. };
  10303. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  10304. if (pickingInfoA.distance < pickingInfoB.distance) {
  10305. return -1;
  10306. }
  10307. else if (pickingInfoA.distance > pickingInfoB.distance) {
  10308. return 1;
  10309. }
  10310. else {
  10311. return 0;
  10312. }
  10313. };
  10314. /**
  10315. * @Deprecated. Use new RayHelper.show() instead.
  10316. * */
  10317. Ray.prototype.show = function (scene, color) {
  10318. console.warn('Ray.show() has been deprecated. Use new RayHelper.show() instead.');
  10319. if (!this._rayHelper) {
  10320. this._rayHelper = new BABYLON.RayHelper(this);
  10321. }
  10322. this._rayHelper.show(scene, color);
  10323. };
  10324. /**
  10325. * @Deprecated. Use new RayHelper.hide() instead.
  10326. * */
  10327. Ray.prototype.hide = function () {
  10328. console.warn('Ray.hide() has been deprecated. Use new RayHelper.hide() instead.');
  10329. if (this._rayHelper) {
  10330. this._rayHelper.hide();
  10331. this._rayHelper = null;
  10332. }
  10333. };
  10334. /**
  10335. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  10336. * @param sega the first point of the segment to test the intersection against
  10337. * @param segb the second point of the segment to test the intersection against
  10338. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  10339. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  10340. */
  10341. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  10342. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  10343. var u = segb.subtract(sega);
  10344. var v = rsegb.subtract(this.origin);
  10345. var w = sega.subtract(this.origin);
  10346. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  10347. var b = BABYLON.Vector3.Dot(u, v);
  10348. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  10349. var d = BABYLON.Vector3.Dot(u, w);
  10350. var e = BABYLON.Vector3.Dot(v, w);
  10351. var D = a * c - b * b; // always >= 0
  10352. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  10353. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  10354. // compute the line parameters of the two closest points
  10355. if (D < Ray.smallnum) {
  10356. sN = 0.0; // force using point P0 on segment S1
  10357. sD = 1.0; // to prevent possible division by 0.0 later
  10358. tN = e;
  10359. tD = c;
  10360. }
  10361. else {
  10362. sN = (b * e - c * d);
  10363. tN = (a * e - b * d);
  10364. if (sN < 0.0) {
  10365. sN = 0.0;
  10366. tN = e;
  10367. tD = c;
  10368. }
  10369. else if (sN > sD) {
  10370. sN = sD;
  10371. tN = e + b;
  10372. tD = c;
  10373. }
  10374. }
  10375. if (tN < 0.0) {
  10376. tN = 0.0;
  10377. // recompute sc for this edge
  10378. if (-d < 0.0) {
  10379. sN = 0.0;
  10380. }
  10381. else if (-d > a)
  10382. sN = sD;
  10383. else {
  10384. sN = -d;
  10385. sD = a;
  10386. }
  10387. }
  10388. else if (tN > tD) {
  10389. tN = tD;
  10390. // recompute sc for this edge
  10391. if ((-d + b) < 0.0) {
  10392. sN = 0;
  10393. }
  10394. else if ((-d + b) > a) {
  10395. sN = sD;
  10396. }
  10397. else {
  10398. sN = (-d + b);
  10399. sD = a;
  10400. }
  10401. }
  10402. // finally do the division to get sc and tc
  10403. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10404. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10405. // get the difference of the two closest points
  10406. var qtc = v.multiplyByFloats(tc, tc, tc);
  10407. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10408. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10409. if (isIntersected) {
  10410. return qtc.length();
  10411. }
  10412. return -1;
  10413. };
  10414. // Statics
  10415. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10416. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10417. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10418. var direction = end.subtract(start);
  10419. direction.normalize();
  10420. return new Ray(start, direction);
  10421. };
  10422. /**
  10423. * 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
  10424. * transformed to the given world matrix.
  10425. * @param origin The origin point
  10426. * @param end The end point
  10427. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10428. */
  10429. Ray.CreateNewFromTo = function (origin, end, world) {
  10430. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10431. var direction = end.subtract(origin);
  10432. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10433. direction.normalize();
  10434. return Ray.Transform(new Ray(origin, direction, length), world);
  10435. };
  10436. Ray.Transform = function (ray, matrix) {
  10437. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10438. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10439. newDirection.normalize();
  10440. return new Ray(newOrigin, newDirection, ray.length);
  10441. };
  10442. Ray.TransformToRef = function (ray, matrix, result) {
  10443. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  10444. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  10445. ray.direction.normalize();
  10446. };
  10447. return Ray;
  10448. }());
  10449. Ray.smallnum = 0.00000001;
  10450. Ray.rayl = 10e8;
  10451. BABYLON.Ray = Ray;
  10452. })(BABYLON || (BABYLON = {}));
  10453. //# sourceMappingURL=babylon.ray.js.map
  10454. var BABYLON;
  10455. (function (BABYLON) {
  10456. var RayHelper = (function () {
  10457. function RayHelper(ray) {
  10458. this.ray = ray;
  10459. }
  10460. RayHelper.prototype.show = function (scene, color) {
  10461. if (!this._renderFunction) {
  10462. var ray = this.ray;
  10463. this._renderFunction = this._render.bind(this);
  10464. this._scene = scene;
  10465. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  10466. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  10467. this._scene.registerBeforeRender(this._renderFunction);
  10468. }
  10469. if (color) {
  10470. this._renderLine.color.copyFrom(color);
  10471. }
  10472. };
  10473. RayHelper.prototype.hide = function () {
  10474. if (this._renderFunction) {
  10475. this._scene.unregisterBeforeRender(this._renderFunction);
  10476. this._scene = null;
  10477. this._renderFunction = null;
  10478. this._renderLine.dispose();
  10479. this._renderLine = null;
  10480. this._renderPoints = null;
  10481. }
  10482. };
  10483. RayHelper.prototype._render = function () {
  10484. var ray = this.ray;
  10485. var point = this._renderPoints[1];
  10486. var len = Math.min(ray.length, 1000000);
  10487. point.copyFrom(ray.direction);
  10488. point.scaleInPlace(len);
  10489. point.addInPlace(ray.origin);
  10490. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  10491. };
  10492. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  10493. this._attachedToMesh = mesh;
  10494. var ray = this.ray;
  10495. if (!ray.direction) {
  10496. ray.direction = BABYLON.Vector3.Zero();
  10497. }
  10498. if (!ray.origin) {
  10499. ray.origin = BABYLON.Vector3.Zero();
  10500. }
  10501. if (length) {
  10502. ray.length = length;
  10503. }
  10504. if (!meshSpaceOrigin) {
  10505. meshSpaceOrigin = BABYLON.Vector3.Zero();
  10506. }
  10507. if (!meshSpaceDirection) {
  10508. // -1 so that this will work with Mesh.lookAt
  10509. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  10510. }
  10511. if (!this._meshSpaceDirection) {
  10512. this._meshSpaceDirection = meshSpaceDirection.clone();
  10513. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  10514. }
  10515. else {
  10516. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  10517. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  10518. }
  10519. if (!this._updateToMeshFunction) {
  10520. this._updateToMeshFunction = this._updateToMesh.bind(this);
  10521. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  10522. }
  10523. this._updateToMesh();
  10524. };
  10525. RayHelper.prototype.detachFromMesh = function () {
  10526. if (this._attachedToMesh) {
  10527. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  10528. this._attachedToMesh = null;
  10529. this._updateToMeshFunction = null;
  10530. }
  10531. };
  10532. RayHelper.prototype._updateToMesh = function () {
  10533. var ray = this.ray;
  10534. if (this._attachedToMesh._isDisposed) {
  10535. this.detachFromMesh();
  10536. return;
  10537. }
  10538. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  10539. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  10540. };
  10541. RayHelper.prototype.dispose = function () {
  10542. this.hide();
  10543. this.detachFromMesh();
  10544. this.ray = null;
  10545. };
  10546. return RayHelper;
  10547. }());
  10548. BABYLON.RayHelper = RayHelper;
  10549. })(BABYLON || (BABYLON = {}));
  10550. //# sourceMappingURL=babylon.rayHelper.js.map
  10551. var BABYLON;
  10552. (function (BABYLON) {
  10553. var AbstractMesh = (function (_super) {
  10554. __extends(AbstractMesh, _super);
  10555. // Constructor
  10556. function AbstractMesh(name, scene) {
  10557. var _this = _super.call(this, name, scene) || this;
  10558. _this._facetNb = 0; // facet number
  10559. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  10560. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  10561. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  10562. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  10563. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  10564. _this._subDiv = {
  10565. max: 1,
  10566. X: 1,
  10567. Y: 1,
  10568. Z: 1
  10569. };
  10570. // Events
  10571. /**
  10572. * An event triggered when this mesh collides with another one
  10573. * @type {BABYLON.Observable}
  10574. */
  10575. _this.onCollideObservable = new BABYLON.Observable();
  10576. /**
  10577. * An event triggered when the collision's position changes
  10578. * @type {BABYLON.Observable}
  10579. */
  10580. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10581. /**
  10582. * An event triggered after the world matrix is updated
  10583. * @type {BABYLON.Observable}
  10584. */
  10585. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10586. // Properties
  10587. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10588. _this.position = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10589. _this._rotation = new BABYLON.Vector3(0.0, 0.0, 0.0);
  10590. _this._scaling = new BABYLON.Vector3(1.0, 1.0, 1.0);
  10591. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10592. _this.visibility = 1.0;
  10593. _this.alphaIndex = Number.MAX_VALUE;
  10594. _this.infiniteDistance = false;
  10595. _this.isVisible = true;
  10596. _this.isPickable = true;
  10597. _this.showBoundingBox = false;
  10598. _this.showSubMeshesBoundingBox = false;
  10599. _this.isBlocker = false;
  10600. _this.renderingGroupId = 0;
  10601. _this.receiveShadows = false;
  10602. _this.renderOutline = false;
  10603. _this.outlineColor = BABYLON.Color3.Red();
  10604. _this.outlineWidth = 0.02;
  10605. _this.renderOverlay = false;
  10606. _this.overlayColor = BABYLON.Color3.Red();
  10607. _this.overlayAlpha = 0.5;
  10608. _this.hasVertexAlpha = false;
  10609. _this.useVertexColors = true;
  10610. _this.applyFog = true;
  10611. _this.computeBonesUsingShaders = true;
  10612. _this.scalingDeterminant = 1;
  10613. _this.numBoneInfluencers = 4;
  10614. _this.useOctreeForRenderingSelection = true;
  10615. _this.useOctreeForPicking = true;
  10616. _this.useOctreeForCollisions = true;
  10617. _this.layerMask = 0x0FFFFFFF;
  10618. /**
  10619. * True if the mesh must be rendered in any case.
  10620. */
  10621. _this.alwaysSelectAsActiveMesh = false;
  10622. // Collisions
  10623. _this._checkCollisions = false;
  10624. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10625. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10626. _this._collider = new BABYLON.Collider();
  10627. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10628. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10629. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10630. // Edges
  10631. _this.edgesWidth = 1;
  10632. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10633. // Cache
  10634. _this._localWorld = BABYLON.Matrix.Zero();
  10635. _this._worldMatrix = BABYLON.Matrix.Zero();
  10636. _this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10637. _this._absolutePosition = BABYLON.Vector3.Zero();
  10638. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10639. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10640. _this._isDirty = false;
  10641. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10642. _this._isDisposed = false;
  10643. _this._renderId = 0;
  10644. _this._intersectionsInProgress = new Array();
  10645. _this._isWorldMatrixFrozen = false;
  10646. _this._unIndexed = false;
  10647. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10648. if (collidedMesh === void 0) { collidedMesh = null; }
  10649. //TODO move this to the collision coordinator!
  10650. if (_this.getScene().workerCollisions)
  10651. newPosition.multiplyInPlace(_this._collider.radius);
  10652. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10653. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10654. _this.position.addInPlace(_this._diffPositionForCollisions);
  10655. }
  10656. if (collidedMesh) {
  10657. _this.onCollideObservable.notifyObservers(collidedMesh);
  10658. }
  10659. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10660. };
  10661. scene.addMesh(_this);
  10662. return _this;
  10663. }
  10664. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10665. get: function () {
  10666. return AbstractMesh._BILLBOARDMODE_NONE;
  10667. },
  10668. enumerable: true,
  10669. configurable: true
  10670. });
  10671. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10672. get: function () {
  10673. return AbstractMesh._BILLBOARDMODE_X;
  10674. },
  10675. enumerable: true,
  10676. configurable: true
  10677. });
  10678. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10679. get: function () {
  10680. return AbstractMesh._BILLBOARDMODE_Y;
  10681. },
  10682. enumerable: true,
  10683. configurable: true
  10684. });
  10685. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10686. get: function () {
  10687. return AbstractMesh._BILLBOARDMODE_Z;
  10688. },
  10689. enumerable: true,
  10690. configurable: true
  10691. });
  10692. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10693. get: function () {
  10694. return AbstractMesh._BILLBOARDMODE_ALL;
  10695. },
  10696. enumerable: true,
  10697. configurable: true
  10698. });
  10699. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  10700. /**
  10701. * Read-only : the number of facets in the mesh
  10702. */
  10703. get: function () {
  10704. return this._facetNb;
  10705. },
  10706. enumerable: true,
  10707. configurable: true
  10708. });
  10709. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  10710. /**
  10711. * The number of subdivisions per axis in the partioning space
  10712. */
  10713. get: function () {
  10714. return this._partitioningSubdivisions;
  10715. },
  10716. set: function (nb) {
  10717. this._partitioningSubdivisions = nb;
  10718. },
  10719. enumerable: true,
  10720. configurable: true
  10721. });
  10722. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  10723. /**
  10724. * The ratio to apply to the bouding box size to set to the partioning space.
  10725. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  10726. */
  10727. get: function () {
  10728. return this._partitioningBBoxRatio;
  10729. },
  10730. set: function (ratio) {
  10731. this._partitioningBBoxRatio = ratio;
  10732. },
  10733. enumerable: true,
  10734. configurable: true
  10735. });
  10736. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  10737. /**
  10738. * Read-only : is the feature facetData enabled ?
  10739. */
  10740. get: function () {
  10741. return this._facetDataEnabled;
  10742. },
  10743. enumerable: true,
  10744. configurable: true
  10745. });
  10746. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10747. set: function (callback) {
  10748. if (this._onCollideObserver) {
  10749. this.onCollideObservable.remove(this._onCollideObserver);
  10750. }
  10751. this._onCollideObserver = this.onCollideObservable.add(callback);
  10752. },
  10753. enumerable: true,
  10754. configurable: true
  10755. });
  10756. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10757. set: function (callback) {
  10758. if (this._onCollisionPositionChangeObserver) {
  10759. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10760. }
  10761. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10762. },
  10763. enumerable: true,
  10764. configurable: true
  10765. });
  10766. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10767. get: function () {
  10768. return this._skeleton;
  10769. },
  10770. set: function (value) {
  10771. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10772. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10773. }
  10774. if (value && value.needInitialSkinMatrix) {
  10775. value._registerMeshWithPoseMatrix(this);
  10776. }
  10777. this._skeleton = value;
  10778. if (!this._skeleton) {
  10779. this._bonesTransformMatrices = null;
  10780. }
  10781. },
  10782. enumerable: true,
  10783. configurable: true
  10784. });
  10785. /**
  10786. * Returns the string "AbstractMesh"
  10787. */
  10788. AbstractMesh.prototype.getClassName = function () {
  10789. return "AbstractMesh";
  10790. };
  10791. /**
  10792. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10793. */
  10794. AbstractMesh.prototype.toString = function (fullDetails) {
  10795. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10796. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10797. if (this._skeleton) {
  10798. ret += ", skeleton: " + this._skeleton.name;
  10799. }
  10800. if (fullDetails) {
  10801. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10802. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10803. }
  10804. return ret;
  10805. };
  10806. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10807. /**
  10808. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  10809. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  10810. * Default : (0.0, 0.0, 0.0)
  10811. */
  10812. get: function () {
  10813. return this._rotation;
  10814. },
  10815. set: function (newRotation) {
  10816. this._rotation = newRotation;
  10817. },
  10818. enumerable: true,
  10819. configurable: true
  10820. });
  10821. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10822. /**
  10823. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  10824. * Default : (1.0, 1.0, 1.0)
  10825. */
  10826. get: function () {
  10827. return this._scaling;
  10828. },
  10829. set: function (newScaling) {
  10830. this._scaling = newScaling;
  10831. if (this.physicsImpostor) {
  10832. this.physicsImpostor.forceUpdate();
  10833. }
  10834. },
  10835. enumerable: true,
  10836. configurable: true
  10837. });
  10838. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10839. /**
  10840. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  10841. * It's null by default.
  10842. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  10843. */
  10844. get: function () {
  10845. return this._rotationQuaternion;
  10846. },
  10847. set: function (quaternion) {
  10848. this._rotationQuaternion = quaternion;
  10849. //reset the rotation vector.
  10850. if (quaternion && this.rotation.length()) {
  10851. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  10852. }
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. // Methods
  10858. /**
  10859. * Copies the paramater passed Matrix into the mesh Pose matrix.
  10860. * Returns nothing.
  10861. */
  10862. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10863. this._poseMatrix.copyFrom(matrix);
  10864. };
  10865. /**
  10866. * Returns the mesh Pose matrix.
  10867. * Returned object : Matrix
  10868. */
  10869. AbstractMesh.prototype.getPoseMatrix = function () {
  10870. return this._poseMatrix;
  10871. };
  10872. /**
  10873. * Disables the mesh edger rendering mode.
  10874. * Returns nothing.
  10875. */
  10876. AbstractMesh.prototype.disableEdgesRendering = function () {
  10877. if (this._edgesRenderer !== undefined) {
  10878. this._edgesRenderer.dispose();
  10879. this._edgesRenderer = undefined;
  10880. }
  10881. };
  10882. /**
  10883. * Enables the edge rendering mode on the mesh.
  10884. * This mode makes the mesh edges visible.
  10885. * Returns nothing.
  10886. */
  10887. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10888. if (epsilon === void 0) { epsilon = 0.95; }
  10889. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10890. this.disableEdgesRendering();
  10891. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10892. };
  10893. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10894. /**
  10895. * Returns true if the mesh is blocked. Used by the class Mesh.
  10896. * Returns the boolean `false` by default.
  10897. */
  10898. get: function () {
  10899. return false;
  10900. },
  10901. enumerable: true,
  10902. configurable: true
  10903. });
  10904. /**
  10905. * Returns the mesh itself by default, used by the class Mesh.
  10906. * Returned type : AbstractMesh
  10907. */
  10908. AbstractMesh.prototype.getLOD = function (camera) {
  10909. return this;
  10910. };
  10911. /**
  10912. * Returns 0 by default, used by the class Mesh.
  10913. * Returns an integer.
  10914. */
  10915. AbstractMesh.prototype.getTotalVertices = function () {
  10916. return 0;
  10917. };
  10918. /**
  10919. * Returns null by default, used by the class Mesh.
  10920. * Returned type : integer array
  10921. */
  10922. AbstractMesh.prototype.getIndices = function () {
  10923. return null;
  10924. };
  10925. /**
  10926. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  10927. * Returned type : float array or Float32Array
  10928. */
  10929. AbstractMesh.prototype.getVerticesData = function (kind) {
  10930. return null;
  10931. };
  10932. /** Returns false by default, used by the class Mesh.
  10933. * Returns a boolean
  10934. */
  10935. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10936. return false;
  10937. };
  10938. /**
  10939. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  10940. * Returns a BoundingInfo
  10941. */
  10942. AbstractMesh.prototype.getBoundingInfo = function () {
  10943. if (this._masterMesh) {
  10944. return this._masterMesh.getBoundingInfo();
  10945. }
  10946. if (!this._boundingInfo) {
  10947. this._updateBoundingInfo();
  10948. }
  10949. return this._boundingInfo;
  10950. };
  10951. /**
  10952. * Sets a mesh new object BoundingInfo.
  10953. * Returns nothing.
  10954. */
  10955. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10956. this._boundingInfo = boundingInfo;
  10957. };
  10958. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10959. get: function () {
  10960. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10961. },
  10962. enumerable: true,
  10963. configurable: true
  10964. });
  10965. AbstractMesh.prototype._preActivate = function () {
  10966. };
  10967. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10968. };
  10969. AbstractMesh.prototype._activate = function (renderId) {
  10970. this._renderId = renderId;
  10971. };
  10972. /**
  10973. * Returns the last update of the World matrix
  10974. * Returns a Matrix.
  10975. */
  10976. AbstractMesh.prototype.getWorldMatrix = function () {
  10977. if (this._masterMesh) {
  10978. return this._masterMesh.getWorldMatrix();
  10979. }
  10980. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10981. this.computeWorldMatrix();
  10982. }
  10983. return this._worldMatrix;
  10984. };
  10985. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10986. /**
  10987. * Returns directly the last state of the mesh World matrix.
  10988. * A Matrix is returned.
  10989. */
  10990. get: function () {
  10991. return this._worldMatrix;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10997. /**
  10998. * Returns the current mesh absolute position.
  10999. * Retuns a Vector3
  11000. */
  11001. get: function () {
  11002. return this._absolutePosition;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. /**
  11008. * Prevents the World matrix to be computed any longer.
  11009. * Returns nothing.
  11010. */
  11011. AbstractMesh.prototype.freezeWorldMatrix = function () {
  11012. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  11013. this.computeWorldMatrix(true);
  11014. this._isWorldMatrixFrozen = true;
  11015. };
  11016. /**
  11017. * Allows back the World matrix computation.
  11018. * Returns nothing.
  11019. */
  11020. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  11021. this._isWorldMatrixFrozen = false;
  11022. this.computeWorldMatrix(true);
  11023. };
  11024. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  11025. /**
  11026. * True if the World matrix has been frozen.
  11027. * Returns a boolean.
  11028. */
  11029. get: function () {
  11030. return this._isWorldMatrixFrozen;
  11031. },
  11032. enumerable: true,
  11033. configurable: true
  11034. });
  11035. /**
  11036. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  11037. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD
  11038. */
  11039. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  11040. axis.normalize();
  11041. if (!this.rotationQuaternion) {
  11042. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11043. this.rotation = BABYLON.Vector3.Zero();
  11044. }
  11045. var rotationQuaternion;
  11046. if (!space || space === BABYLON.Space.LOCAL) {
  11047. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11048. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  11049. }
  11050. else {
  11051. if (this.parent) {
  11052. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11053. invertParentWorldMatrix.invert();
  11054. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  11055. }
  11056. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  11057. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  11058. }
  11059. };
  11060. /**
  11061. * Translates the mesh along the axis vector for the passed distance in the given space.
  11062. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD
  11063. */
  11064. AbstractMesh.prototype.translate = function (axis, distance, space) {
  11065. var displacementVector = axis.scale(distance);
  11066. if (!space || space === BABYLON.Space.LOCAL) {
  11067. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  11068. this.setPositionWithLocalVector(tempV3);
  11069. }
  11070. else {
  11071. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  11072. }
  11073. };
  11074. /**
  11075. * Adds a rotation step to the mesh current rotation.
  11076. * x, y, z are Euler angles expressed in radians.
  11077. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  11078. * This means this rotation is made in the mesh local space only.
  11079. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  11080. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  11081. * ```javascript
  11082. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  11083. * ```
  11084. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  11085. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  11086. */
  11087. AbstractMesh.prototype.addRotation = function (x, y, z) {
  11088. var rotationQuaternion;
  11089. if (this.rotationQuaternion) {
  11090. rotationQuaternion = this.rotationQuaternion;
  11091. }
  11092. else {
  11093. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  11094. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  11095. }
  11096. var accumulation = BABYLON.Tmp.Quaternion[0];
  11097. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  11098. rotationQuaternion.multiplyInPlace(accumulation);
  11099. if (!this.rotationQuaternion) {
  11100. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  11101. }
  11102. return this;
  11103. };
  11104. /**
  11105. * Retuns the mesh absolute position in the World.
  11106. * Returns a Vector3
  11107. */
  11108. AbstractMesh.prototype.getAbsolutePosition = function () {
  11109. this.computeWorldMatrix();
  11110. return this._absolutePosition;
  11111. };
  11112. /**
  11113. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  11114. * Returns nothing.
  11115. */
  11116. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  11117. if (!absolutePosition) {
  11118. return;
  11119. }
  11120. var absolutePositionX;
  11121. var absolutePositionY;
  11122. var absolutePositionZ;
  11123. if (absolutePosition.x === undefined) {
  11124. if (arguments.length < 3) {
  11125. return;
  11126. }
  11127. absolutePositionX = arguments[0];
  11128. absolutePositionY = arguments[1];
  11129. absolutePositionZ = arguments[2];
  11130. }
  11131. else {
  11132. absolutePositionX = absolutePosition.x;
  11133. absolutePositionY = absolutePosition.y;
  11134. absolutePositionZ = absolutePosition.z;
  11135. }
  11136. if (this.parent) {
  11137. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  11138. invertParentWorldMatrix.invert();
  11139. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  11140. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  11141. }
  11142. else {
  11143. this.position.x = absolutePositionX;
  11144. this.position.y = absolutePositionY;
  11145. this.position.z = absolutePositionZ;
  11146. }
  11147. };
  11148. // ================================== Point of View Movement =================================
  11149. /**
  11150. * Perform relative position change from the point of view of behind the front of the mesh.
  11151. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11152. * Supports definition of mesh facing forward or backward.
  11153. * @param {number} amountRight
  11154. * @param {number} amountUp
  11155. * @param {number} amountForward
  11156. */
  11157. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  11158. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  11159. };
  11160. /**
  11161. * Calculate relative position change from the point of view of behind the front of the mesh.
  11162. * This is performed taking into account the meshes current rotation, so you do not have to care.
  11163. * Supports definition of mesh facing forward or backward.
  11164. * @param {number} amountRight
  11165. * @param {number} amountUp
  11166. * @param {number} amountForward
  11167. */
  11168. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  11169. var rotMatrix = new BABYLON.Matrix();
  11170. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  11171. rotQuaternion.toRotationMatrix(rotMatrix);
  11172. var translationDelta = BABYLON.Vector3.Zero();
  11173. var defForwardMult = this.definedFacingForward ? -1 : 1;
  11174. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  11175. return translationDelta;
  11176. };
  11177. // ================================== Point of View Rotation =================================
  11178. /**
  11179. * Perform relative rotation change from the point of view of behind the front of the mesh.
  11180. * Supports definition of mesh facing forward or backward.
  11181. * @param {number} flipBack
  11182. * @param {number} twirlClockwise
  11183. * @param {number} tiltRight
  11184. */
  11185. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11186. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  11187. };
  11188. /**
  11189. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  11190. * Supports definition of mesh facing forward or backward.
  11191. * @param {number} flipBack
  11192. * @param {number} twirlClockwise
  11193. * @param {number} tiltRight
  11194. */
  11195. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  11196. var defForwardMult = this.definedFacingForward ? 1 : -1;
  11197. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  11198. };
  11199. /**
  11200. * Sets a new pivot matrix to the mesh.
  11201. * Returns nothing.
  11202. */
  11203. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  11204. this._pivotMatrix = matrix;
  11205. this._cache.pivotMatrixUpdated = true;
  11206. };
  11207. /**
  11208. * Returns the mesh pivot matrix.
  11209. * Default : Identity.
  11210. * A Matrix is returned.
  11211. */
  11212. AbstractMesh.prototype.getPivotMatrix = function () {
  11213. return this._pivotMatrix;
  11214. };
  11215. AbstractMesh.prototype._isSynchronized = function () {
  11216. if (this._isDirty) {
  11217. return false;
  11218. }
  11219. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  11220. return false;
  11221. if (this._cache.pivotMatrixUpdated) {
  11222. return false;
  11223. }
  11224. if (this.infiniteDistance) {
  11225. return false;
  11226. }
  11227. if (!this._cache.position.equals(this.position))
  11228. return false;
  11229. if (this.rotationQuaternion) {
  11230. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  11231. return false;
  11232. }
  11233. if (!this._cache.rotation.equals(this.rotation))
  11234. return false;
  11235. if (!this._cache.scaling.equals(this.scaling))
  11236. return false;
  11237. return true;
  11238. };
  11239. AbstractMesh.prototype._initCache = function () {
  11240. _super.prototype._initCache.call(this);
  11241. this._cache.localMatrixUpdated = false;
  11242. this._cache.position = BABYLON.Vector3.Zero();
  11243. this._cache.scaling = BABYLON.Vector3.Zero();
  11244. this._cache.rotation = BABYLON.Vector3.Zero();
  11245. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  11246. this._cache.billboardMode = -1;
  11247. };
  11248. AbstractMesh.prototype.markAsDirty = function (property) {
  11249. if (property === "rotation") {
  11250. this.rotationQuaternion = null;
  11251. }
  11252. this._currentRenderId = Number.MAX_VALUE;
  11253. this._isDirty = true;
  11254. };
  11255. /**
  11256. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  11257. * Returns nothing.
  11258. */
  11259. AbstractMesh.prototype._updateBoundingInfo = function () {
  11260. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  11261. this._boundingInfo.update(this.worldMatrixFromCache);
  11262. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  11263. };
  11264. /**
  11265. * Update a mesh's children BoundingInfo objects only.
  11266. * Returns nothing.
  11267. */
  11268. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  11269. if (!this.subMeshes) {
  11270. return;
  11271. }
  11272. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  11273. var subMesh = this.subMeshes[subIndex];
  11274. if (!subMesh.IsGlobal) {
  11275. subMesh.updateBoundingInfo(matrix);
  11276. }
  11277. }
  11278. };
  11279. /**
  11280. * Computes the mesh World matrix and returns it.
  11281. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  11282. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  11283. * If the parameter `force`is set to `true`, the actual computation is done.
  11284. * Returns the mesh World Matrix.
  11285. */
  11286. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  11287. if (this._isWorldMatrixFrozen) {
  11288. return this._worldMatrix;
  11289. }
  11290. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  11291. this._currentRenderId = this.getScene().getRenderId();
  11292. return this._worldMatrix;
  11293. }
  11294. this._cache.position.copyFrom(this.position);
  11295. this._cache.scaling.copyFrom(this.scaling);
  11296. this._cache.pivotMatrixUpdated = false;
  11297. this._cache.billboardMode = this.billboardMode;
  11298. this._currentRenderId = this.getScene().getRenderId();
  11299. this._isDirty = false;
  11300. // Scaling
  11301. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  11302. // Rotation
  11303. //rotate, if quaternion is set and rotation was used
  11304. if (this.rotationQuaternion) {
  11305. var len = this.rotation.length();
  11306. if (len) {
  11307. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  11308. this.rotation.copyFromFloats(0, 0, 0);
  11309. }
  11310. }
  11311. if (this.rotationQuaternion) {
  11312. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  11313. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  11314. }
  11315. else {
  11316. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  11317. this._cache.rotation.copyFrom(this.rotation);
  11318. }
  11319. // Translation
  11320. if (this.infiniteDistance && !this.parent) {
  11321. var camera = this.getScene().activeCamera;
  11322. if (camera) {
  11323. var cameraWorldMatrix = camera.getWorldMatrix();
  11324. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  11325. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  11326. }
  11327. }
  11328. else {
  11329. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  11330. }
  11331. // Composing transformations
  11332. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  11333. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  11334. // Billboarding
  11335. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  11336. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  11337. var localPosition = BABYLON.Tmp.Vector3[0];
  11338. if (this.parent && this.parent.getWorldMatrix) {
  11339. this._markSyncedWithParent();
  11340. var parentMatrix;
  11341. if (this._meshToBoneReferal) {
  11342. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11343. parentMatrix = BABYLON.Tmp.Matrix[6];
  11344. }
  11345. else {
  11346. parentMatrix = this.parent.getWorldMatrix();
  11347. }
  11348. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  11349. localPosition = BABYLON.Tmp.Vector3[1];
  11350. }
  11351. var zero = this.getScene().activeCamera.globalPosition.clone();
  11352. if (this.parent && this.parent.position) {
  11353. localPosition.addInPlace(this.parent.position);
  11354. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  11355. }
  11356. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  11357. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  11358. zero.x = localPosition.x + BABYLON.Epsilon;
  11359. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  11360. zero.y = localPosition.y + BABYLON.Epsilon;
  11361. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  11362. zero.z = localPosition.z + BABYLON.Epsilon;
  11363. }
  11364. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  11365. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  11366. BABYLON.Tmp.Matrix[3].invert();
  11367. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  11368. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  11369. }
  11370. // Local world
  11371. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  11372. // Parent
  11373. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  11374. this._markSyncedWithParent();
  11375. if (this._meshToBoneReferal) {
  11376. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  11377. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  11378. }
  11379. else {
  11380. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  11381. }
  11382. }
  11383. else {
  11384. this._worldMatrix.copyFrom(this._localWorld);
  11385. }
  11386. // Bounding info
  11387. this._updateBoundingInfo();
  11388. // Absolute position
  11389. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  11390. // Callbacks
  11391. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  11392. if (!this._poseMatrix) {
  11393. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  11394. }
  11395. return this._worldMatrix;
  11396. };
  11397. /**
  11398. * If you'd like to be called back after the mesh position, rotation or scaling has been updated
  11399. * @param func: callback function to add
  11400. */
  11401. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  11402. this.onAfterWorldMatrixUpdateObservable.add(func);
  11403. };
  11404. /**
  11405. * Removes a registered callback function
  11406. */
  11407. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  11408. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  11409. };
  11410. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  11411. this.computeWorldMatrix();
  11412. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  11413. };
  11414. /**
  11415. * Returns the mesh position in the local space from the current World matrix values.
  11416. * Returns a new Vector3.
  11417. */
  11418. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  11419. this.computeWorldMatrix();
  11420. var invLocalWorldMatrix = this._localWorld.clone();
  11421. invLocalWorldMatrix.invert();
  11422. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  11423. };
  11424. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  11425. this.computeWorldMatrix(true);
  11426. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  11427. };
  11428. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  11429. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  11430. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  11431. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  11432. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  11433. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  11434. /// <returns>Mesh oriented towards targetMesh</returns>
  11435. if (yawCor === void 0) { yawCor = 0; }
  11436. if (pitchCor === void 0) { pitchCor = 0; }
  11437. if (rollCor === void 0) { rollCor = 0; }
  11438. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11439. var dv = AbstractMesh._lookAtVectorCache;
  11440. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  11441. targetPoint.subtractToRef(pos, dv);
  11442. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  11443. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  11444. var pitch = Math.atan2(dv.y, len);
  11445. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  11446. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  11447. };
  11448. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  11449. this._meshToBoneReferal = affectedMesh;
  11450. this.parent = bone;
  11451. if (bone.getWorldMatrix().determinant() < 0) {
  11452. this.scalingDeterminant *= -1;
  11453. }
  11454. };
  11455. AbstractMesh.prototype.detachFromBone = function () {
  11456. if (this.parent.getWorldMatrix().determinant() < 0) {
  11457. this.scalingDeterminant *= -1;
  11458. }
  11459. this._meshToBoneReferal = null;
  11460. this.parent = null;
  11461. };
  11462. /**
  11463. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  11464. * A mesh is in the frustum if its bounding box intersects the frustum.
  11465. * Boolean returned.
  11466. */
  11467. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11468. return this._boundingInfo.isInFrustum(frustumPlanes);
  11469. };
  11470. /**
  11471. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  11472. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  11473. * Boolean returned.
  11474. */
  11475. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11476. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11477. ;
  11478. };
  11479. /**
  11480. * True if the mesh intersects another mesh or a SolidParticle object.
  11481. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  11482. * Returns a boolean.
  11483. */
  11484. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11485. if (!this._boundingInfo || !mesh._boundingInfo) {
  11486. return false;
  11487. }
  11488. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11489. };
  11490. /**
  11491. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  11492. * Returns a boolean.
  11493. */
  11494. AbstractMesh.prototype.intersectsPoint = function (point) {
  11495. if (!this._boundingInfo) {
  11496. return false;
  11497. }
  11498. return this._boundingInfo.intersectsPoint(point);
  11499. };
  11500. // Physics
  11501. /**
  11502. * @Deprecated. Use new PhysicsImpostor instead.
  11503. * */
  11504. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  11505. //legacy support
  11506. if (impostor.impostor) {
  11507. options = impostor;
  11508. impostor = impostor.impostor;
  11509. }
  11510. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  11511. return this.physicsImpostor.physicsBody;
  11512. };
  11513. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11514. return this.physicsImpostor;
  11515. };
  11516. /**
  11517. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  11518. */
  11519. AbstractMesh.prototype.getPhysicsMass = function () {
  11520. return this.physicsImpostor.getParam("mass");
  11521. };
  11522. /**
  11523. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  11524. */
  11525. AbstractMesh.prototype.getPhysicsFriction = function () {
  11526. return this.physicsImpostor.getParam("friction");
  11527. };
  11528. /**
  11529. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  11530. */
  11531. AbstractMesh.prototype.getPhysicsRestitution = function () {
  11532. return this.physicsImpostor.getParam("restitution");
  11533. };
  11534. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11535. if (!camera) {
  11536. camera = this.getScene().activeCamera;
  11537. }
  11538. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11539. };
  11540. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11541. if (!camera) {
  11542. camera = this.getScene().activeCamera;
  11543. }
  11544. return this.absolutePosition.subtract(camera.position).length();
  11545. };
  11546. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11547. if (!this.physicsImpostor) {
  11548. return;
  11549. }
  11550. this.physicsImpostor.applyImpulse(force, contactPoint);
  11551. };
  11552. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11553. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11554. return;
  11555. }
  11556. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11557. mainPivot: pivot1,
  11558. connectedPivot: pivot2,
  11559. nativeParams: options
  11560. });
  11561. };
  11562. /**
  11563. * @Deprecated
  11564. */
  11565. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  11566. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  11567. this.updatePhysicsBody();
  11568. };
  11569. /**
  11570. * @Deprecated
  11571. * Calling this function is not needed anymore.
  11572. * The physics engine takes care of transofmration automatically.
  11573. */
  11574. AbstractMesh.prototype.updatePhysicsBody = function () {
  11575. //Unneeded
  11576. };
  11577. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11578. // Collisions
  11579. /**
  11580. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  11581. * Default `false`.
  11582. */
  11583. get: function () {
  11584. return this._checkCollisions;
  11585. },
  11586. set: function (collisionEnabled) {
  11587. this._checkCollisions = collisionEnabled;
  11588. if (this.getScene().workerCollisions) {
  11589. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11590. }
  11591. },
  11592. enumerable: true,
  11593. configurable: true
  11594. });
  11595. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11596. var globalPosition = this.getAbsolutePosition();
  11597. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11598. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11599. this._collider.radius = this.ellipsoid;
  11600. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11601. };
  11602. // Submeshes octree
  11603. /**
  11604. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  11605. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  11606. */
  11607. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11608. if (maxCapacity === void 0) { maxCapacity = 64; }
  11609. if (maxDepth === void 0) { maxDepth = 2; }
  11610. if (!this._submeshesOctree) {
  11611. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11612. }
  11613. this.computeWorldMatrix(true);
  11614. // Update octree
  11615. var bbox = this.getBoundingInfo().boundingBox;
  11616. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11617. return this._submeshesOctree;
  11618. };
  11619. // Collisions
  11620. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11621. this._generatePointsArray();
  11622. // Transformation
  11623. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11624. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11625. subMesh._lastColliderWorldVertices = [];
  11626. subMesh._trianglePlanes = [];
  11627. var start = subMesh.verticesStart;
  11628. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11629. for (var i = start; i < end; i++) {
  11630. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11631. }
  11632. }
  11633. // Collide
  11634. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11635. if (collider.collisionFound) {
  11636. collider.collidedMesh = this;
  11637. }
  11638. };
  11639. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11640. var subMeshes;
  11641. var len;
  11642. // Octrees
  11643. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11644. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11645. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11646. len = intersections.length;
  11647. subMeshes = intersections.data;
  11648. }
  11649. else {
  11650. subMeshes = this.subMeshes;
  11651. len = subMeshes.length;
  11652. }
  11653. for (var index = 0; index < len; index++) {
  11654. var subMesh = subMeshes[index];
  11655. // Bounding test
  11656. if (len > 1 && !subMesh._checkCollision(collider))
  11657. continue;
  11658. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11659. }
  11660. };
  11661. AbstractMesh.prototype._checkCollision = function (collider) {
  11662. // Bounding box test
  11663. if (!this._boundingInfo._checkCollision(collider))
  11664. return;
  11665. // Transformation matrix
  11666. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11667. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11668. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11669. };
  11670. // Picking
  11671. AbstractMesh.prototype._generatePointsArray = function () {
  11672. return false;
  11673. };
  11674. /**
  11675. * Checks if the passed Ray intersects with the mesh.
  11676. * Returns an object PickingInfo.
  11677. */
  11678. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11679. var pickingInfo = new BABYLON.PickingInfo();
  11680. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11681. return pickingInfo;
  11682. }
  11683. if (!this._generatePointsArray()) {
  11684. return pickingInfo;
  11685. }
  11686. var intersectInfo = null;
  11687. // Octrees
  11688. var subMeshes;
  11689. var len;
  11690. if (this._submeshesOctree && this.useOctreeForPicking) {
  11691. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11692. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11693. len = intersections.length;
  11694. subMeshes = intersections.data;
  11695. }
  11696. else {
  11697. subMeshes = this.subMeshes;
  11698. len = subMeshes.length;
  11699. }
  11700. for (var index = 0; index < len; index++) {
  11701. var subMesh = subMeshes[index];
  11702. // Bounding test
  11703. if (len > 1 && !subMesh.canIntersects(ray))
  11704. continue;
  11705. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11706. if (currentIntersectInfo) {
  11707. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11708. intersectInfo = currentIntersectInfo;
  11709. intersectInfo.subMeshId = index;
  11710. if (fastCheck) {
  11711. break;
  11712. }
  11713. }
  11714. }
  11715. }
  11716. if (intersectInfo) {
  11717. // Get picked point
  11718. var world = this.getWorldMatrix();
  11719. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11720. var direction = ray.direction.clone();
  11721. direction = direction.scale(intersectInfo.distance);
  11722. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11723. var pickedPoint = worldOrigin.add(worldDirection);
  11724. // Return result
  11725. pickingInfo.hit = true;
  11726. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11727. pickingInfo.pickedPoint = pickedPoint;
  11728. pickingInfo.pickedMesh = this;
  11729. pickingInfo.bu = intersectInfo.bu;
  11730. pickingInfo.bv = intersectInfo.bv;
  11731. pickingInfo.faceId = intersectInfo.faceId;
  11732. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11733. return pickingInfo;
  11734. }
  11735. return pickingInfo;
  11736. };
  11737. /**
  11738. * Clones the mesh, used by the class Mesh.
  11739. * Just returns `null` for an AbstractMesh.
  11740. */
  11741. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11742. return null;
  11743. };
  11744. /**
  11745. * Disposes all the mesh submeshes.
  11746. * Returns nothing.
  11747. */
  11748. AbstractMesh.prototype.releaseSubMeshes = function () {
  11749. if (this.subMeshes) {
  11750. while (this.subMeshes.length) {
  11751. this.subMeshes[0].dispose();
  11752. }
  11753. }
  11754. else {
  11755. this.subMeshes = new Array();
  11756. }
  11757. };
  11758. /**
  11759. * Disposes the AbstractMesh.
  11760. * Some internal references are kept for further use.
  11761. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  11762. * Returns nothing.
  11763. */
  11764. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11765. var _this = this;
  11766. var index;
  11767. // Action manager
  11768. if (this.actionManager) {
  11769. this.actionManager.dispose();
  11770. this.actionManager = null;
  11771. }
  11772. // Skeleton
  11773. this.skeleton = null;
  11774. // Animations
  11775. this.getScene().stopAnimation(this);
  11776. // Physics
  11777. if (this.physicsImpostor) {
  11778. this.physicsImpostor.dispose();
  11779. }
  11780. // Intersections in progress
  11781. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11782. var other = this._intersectionsInProgress[index];
  11783. var pos = other._intersectionsInProgress.indexOf(this);
  11784. other._intersectionsInProgress.splice(pos, 1);
  11785. }
  11786. this._intersectionsInProgress = [];
  11787. // Lights
  11788. var lights = this.getScene().lights;
  11789. lights.forEach(function (light) {
  11790. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11791. if (meshIndex !== -1) {
  11792. light.includedOnlyMeshes.splice(meshIndex, 1);
  11793. }
  11794. meshIndex = light.excludedMeshes.indexOf(_this);
  11795. if (meshIndex !== -1) {
  11796. light.excludedMeshes.splice(meshIndex, 1);
  11797. }
  11798. // Shadow generators
  11799. var generator = light.getShadowGenerator();
  11800. if (generator) {
  11801. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11802. if (meshIndex !== -1) {
  11803. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11804. }
  11805. }
  11806. });
  11807. // Edges
  11808. if (this._edgesRenderer) {
  11809. this._edgesRenderer.dispose();
  11810. this._edgesRenderer = null;
  11811. }
  11812. // SubMeshes
  11813. if (this.getClassName() !== "InstancedMesh") {
  11814. this.releaseSubMeshes();
  11815. }
  11816. // Engine
  11817. this.getScene().getEngine().wipeCaches();
  11818. // Remove from scene
  11819. this.getScene().removeMesh(this);
  11820. if (!doNotRecurse) {
  11821. // Particles
  11822. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11823. if (this.getScene().particleSystems[index].emitter === this) {
  11824. this.getScene().particleSystems[index].dispose();
  11825. index--;
  11826. }
  11827. }
  11828. // Children
  11829. var objects = this.getDescendants(true);
  11830. for (index = 0; index < objects.length; index++) {
  11831. objects[index].dispose();
  11832. }
  11833. }
  11834. else {
  11835. var childMeshes = this.getChildMeshes(true);
  11836. for (index = 0; index < childMeshes.length; index++) {
  11837. var child = childMeshes[index];
  11838. child.parent = null;
  11839. child.computeWorldMatrix(true);
  11840. }
  11841. }
  11842. // facet data
  11843. if (this._facetDataEnabled) {
  11844. this.disableFacetData();
  11845. }
  11846. this.onAfterWorldMatrixUpdateObservable.clear();
  11847. this.onCollideObservable.clear();
  11848. this.onCollisionPositionChangeObservable.clear();
  11849. this._isDisposed = true;
  11850. _super.prototype.dispose.call(this);
  11851. };
  11852. /**
  11853. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  11854. * This Vector3 is expressed in the World space.
  11855. */
  11856. AbstractMesh.prototype.getDirection = function (localAxis) {
  11857. var result = BABYLON.Vector3.Zero();
  11858. this.getDirectionToRef(localAxis, result);
  11859. return result;
  11860. };
  11861. /**
  11862. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  11863. * localAxis is expressed in the mesh local space.
  11864. * result is computed in the Wordl space from the mesh World matrix.
  11865. * Returns nothing.
  11866. */
  11867. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  11868. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  11869. };
  11870. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  11871. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11872. if (this.getScene().getRenderId() == 0) {
  11873. this.computeWorldMatrix(true);
  11874. }
  11875. var wm = this.getWorldMatrix();
  11876. if (space == BABYLON.Space.WORLD) {
  11877. var tmat = BABYLON.Tmp.Matrix[0];
  11878. wm.invertToRef(tmat);
  11879. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  11880. }
  11881. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  11882. this._pivotMatrix.m[12] = -point.x;
  11883. this._pivotMatrix.m[13] = -point.y;
  11884. this._pivotMatrix.m[14] = -point.z;
  11885. this._cache.pivotMatrixUpdated = true;
  11886. };
  11887. /**
  11888. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  11889. */
  11890. AbstractMesh.prototype.getPivotPoint = function () {
  11891. var point = BABYLON.Vector3.Zero();
  11892. this.getPivotPointToRef(point);
  11893. return point;
  11894. };
  11895. /**
  11896. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  11897. */
  11898. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  11899. result.x = -this._pivotMatrix.m[12];
  11900. result.y = -this._pivotMatrix.m[13];
  11901. result.z = -this._pivotMatrix.m[14];
  11902. };
  11903. /**
  11904. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  11905. */
  11906. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  11907. var point = BABYLON.Vector3.Zero();
  11908. this.getAbsolutePivotPointToRef(point);
  11909. return point;
  11910. };
  11911. /**
  11912. * Defines the passed mesh as the parent of the current mesh.
  11913. * If keepWorldPositionRotation is set to `true` (default `false`), the current mesh position and rotation are kept.
  11914. * Returns nothing.
  11915. */
  11916. AbstractMesh.prototype.setParent = function (mesh, keepWorldPositionRotation) {
  11917. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11918. var child = this;
  11919. var parent = mesh;
  11920. if (mesh == null) {
  11921. if (child.parent && keepWorldPositionRotation) {
  11922. var rotation = BABYLON.Tmp.Quaternion[0];
  11923. var position = BABYLON.Tmp.Vector3[0];
  11924. var scale = BABYLON.Tmp.Vector3[1];
  11925. child.getWorldMatrix().decompose(scale, rotation, position);
  11926. if (child.rotationQuaternion) {
  11927. child.rotationQuaternion.copyFrom(rotation);
  11928. }
  11929. else {
  11930. rotation.toEulerAnglesToRef(child.rotation);
  11931. }
  11932. child.position.x = position.x;
  11933. child.position.y = position.y;
  11934. child.position.z = position.z;
  11935. }
  11936. }
  11937. else {
  11938. if (keepWorldPositionRotation) {
  11939. var rotation = BABYLON.Tmp.Quaternion[0];
  11940. var position = BABYLON.Tmp.Vector3[0];
  11941. var scale = BABYLON.Tmp.Vector3[1];
  11942. var m1 = BABYLON.Tmp.Matrix[0];
  11943. var m2 = BABYLON.Tmp.Matrix[1];
  11944. parent.getWorldMatrix().decompose(scale, rotation, position);
  11945. rotation.toRotationMatrix(m1);
  11946. m2.setTranslation(position);
  11947. m2.multiplyToRef(m1, m1);
  11948. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  11949. var m = child.getWorldMatrix().multiply(invParentMatrix);
  11950. m.decompose(scale, rotation, position);
  11951. if (child.rotationQuaternion) {
  11952. child.rotationQuaternion.copyFrom(rotation);
  11953. }
  11954. else {
  11955. rotation.toEulerAnglesToRef(child.rotation);
  11956. }
  11957. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  11958. var m = child.getWorldMatrix().multiply(invParentMatrix);
  11959. m.decompose(scale, rotation, position);
  11960. child.position.x = position.x;
  11961. child.position.y = position.y;
  11962. child.position.z = position.z;
  11963. }
  11964. }
  11965. child.parent = parent;
  11966. };
  11967. /**
  11968. * Adds the passed mesh as a child to the current mesh.
  11969. * If keepWorldPositionRotation is set to `true` (default `false`), the child world position and rotation are kept.
  11970. * Returns nothing.
  11971. */
  11972. AbstractMesh.prototype.addChild = function (mesh, keepWorldPositionRotation) {
  11973. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11974. mesh.setParent(this, keepWorldPositionRotation);
  11975. };
  11976. /**
  11977. * Removes the passed mesh from the current mesh children list.
  11978. */
  11979. AbstractMesh.prototype.removeChild = function (mesh, keepWorldPositionRotation) {
  11980. if (keepWorldPositionRotation === void 0) { keepWorldPositionRotation = false; }
  11981. mesh.setParent(null, keepWorldPositionRotation);
  11982. };
  11983. /**
  11984. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  11985. */
  11986. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  11987. result.x = this._pivotMatrix.m[12];
  11988. result.y = this._pivotMatrix.m[13];
  11989. result.z = this._pivotMatrix.m[14];
  11990. this.getPivotPointToRef(result);
  11991. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  11992. };
  11993. // Facet data
  11994. /**
  11995. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning
  11996. */
  11997. AbstractMesh.prototype._initFacetData = function () {
  11998. if (!this._facetNormals) {
  11999. this._facetNormals = new Array();
  12000. }
  12001. if (!this._facetPositions) {
  12002. this._facetPositions = new Array();
  12003. }
  12004. if (!this._facetPartitioning) {
  12005. this._facetPartitioning = new Array();
  12006. }
  12007. this._facetNb = this.getIndices().length / 3;
  12008. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  12009. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  12010. for (var f = 0; f < this._facetNb; f++) {
  12011. this._facetNormals[f] = BABYLON.Vector3.Zero();
  12012. this._facetPositions[f] = BABYLON.Vector3.Zero();
  12013. }
  12014. this._facetDataEnabled = true;
  12015. return this;
  12016. };
  12017. /**
  12018. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  12019. * This method can be called within the render loop.
  12020. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  12021. */
  12022. AbstractMesh.prototype.updateFacetData = function () {
  12023. if (!this._facetDataEnabled) {
  12024. this._initFacetData();
  12025. }
  12026. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  12027. var indices = this.getIndices();
  12028. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  12029. var bInfo = this.getBoundingInfo();
  12030. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  12031. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  12032. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  12033. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  12034. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  12035. this._subDiv.max = this._partitioningSubdivisions;
  12036. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  12037. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  12038. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  12039. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  12040. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  12041. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  12042. // set the parameters for ComputeNormals()
  12043. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  12044. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  12045. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  12046. this._facetParameters.bInfo = bInfo;
  12047. this._facetParameters.bbSize = this._bbSize;
  12048. this._facetParameters.subDiv = this._subDiv;
  12049. this._facetParameters.ratio = this.partitioningBBoxRatio;
  12050. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  12051. return this;
  12052. };
  12053. /**
  12054. * Returns the facetLocalNormals array.
  12055. * The normals are expressed in the mesh local space.
  12056. */
  12057. AbstractMesh.prototype.getFacetLocalNormals = function () {
  12058. if (!this._facetNormals) {
  12059. this.updateFacetData();
  12060. }
  12061. return this._facetNormals;
  12062. };
  12063. /**
  12064. * Returns the facetLocalPositions array.
  12065. * The facet positions are expressed in the mesh local space.
  12066. */
  12067. AbstractMesh.prototype.getFacetLocalPositions = function () {
  12068. if (!this._facetPositions) {
  12069. this.updateFacetData();
  12070. }
  12071. return this._facetPositions;
  12072. };
  12073. /**
  12074. * Returns the facetLocalPartioning array
  12075. */
  12076. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  12077. if (!this._facetPartitioning) {
  12078. this.updateFacetData();
  12079. }
  12080. return this._facetPartitioning;
  12081. };
  12082. /**
  12083. * Returns the i-th facet position in the world system.
  12084. * This method allocates a new Vector3 per call.
  12085. */
  12086. AbstractMesh.prototype.getFacetPosition = function (i) {
  12087. var pos = BABYLON.Vector3.Zero();
  12088. this.getFacetPositionToRef(i, pos);
  12089. return pos;
  12090. };
  12091. /**
  12092. * Sets the reference Vector3 with the i-th facet position in the world system.
  12093. * Returns the mesh.
  12094. */
  12095. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  12096. var localPos = (this.getFacetLocalPositions())[i];
  12097. var world = this.getWorldMatrix();
  12098. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  12099. return this;
  12100. };
  12101. /**
  12102. * Returns the i-th facet normal in the world system.
  12103. * This method allocates a new Vector3 per call.
  12104. */
  12105. AbstractMesh.prototype.getFacetNormal = function (i) {
  12106. var norm = BABYLON.Vector3.Zero();
  12107. this.getFacetNormalToRef(i, norm);
  12108. return norm;
  12109. };
  12110. /**
  12111. * Sets the reference Vector3 with the i-th facet normal in the world system.
  12112. * Returns the mesh.
  12113. */
  12114. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  12115. var localNorm = (this.getFacetLocalNormals())[i];
  12116. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  12117. return this;
  12118. };
  12119. /**
  12120. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  12121. */
  12122. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  12123. var bInfo = this.getBoundingInfo();
  12124. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  12125. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  12126. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  12127. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  12128. return null;
  12129. }
  12130. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  12131. };
  12132. /**
  12133. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  12134. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  12135. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  12136. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12137. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  12138. */
  12139. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  12140. if (checkFace === void 0) { checkFace = false; }
  12141. if (facing === void 0) { facing = true; }
  12142. var world = this.getWorldMatrix();
  12143. var invMat = BABYLON.Tmp.Matrix[5];
  12144. world.invertToRef(invMat);
  12145. var invVect = BABYLON.Tmp.Vector3[8];
  12146. var closest = null;
  12147. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  12148. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  12149. if (projected) {
  12150. // tranform the local computed projected vector to world coordinates
  12151. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  12152. }
  12153. return closest;
  12154. };
  12155. /**
  12156. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  12157. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  12158. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  12159. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  12160. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  12161. */
  12162. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  12163. if (checkFace === void 0) { checkFace = false; }
  12164. if (facing === void 0) { facing = true; }
  12165. var closest = null;
  12166. var tmpx = 0.0;
  12167. var tmpy = 0.0;
  12168. var tmpz = 0.0;
  12169. var d = 0.0; // tmp dot facet normal * facet position
  12170. var t0 = 0.0;
  12171. var projx = 0.0;
  12172. var projy = 0.0;
  12173. var projz = 0.0;
  12174. // Get all the facets in the same partitioning block than (x, y, z)
  12175. var facetPositions = this.getFacetLocalPositions();
  12176. var facetNormals = this.getFacetLocalNormals();
  12177. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  12178. if (!facetsInBlock) {
  12179. return null;
  12180. }
  12181. // Get the closest facet to (x, y, z)
  12182. var shortest = Number.MAX_VALUE; // init distance vars
  12183. var tmpDistance = shortest;
  12184. var fib; // current facet in the block
  12185. var norm; // current facet normal
  12186. var p0; // current facet barycenter position
  12187. // loop on all the facets in the current partitioning block
  12188. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  12189. fib = facetsInBlock[idx];
  12190. norm = facetNormals[fib];
  12191. p0 = facetPositions[fib];
  12192. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  12193. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  12194. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  12195. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  12196. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  12197. projx = x + norm.x * t0;
  12198. projy = y + norm.y * t0;
  12199. projz = z + norm.z * t0;
  12200. tmpx = projx - x;
  12201. tmpy = projy - y;
  12202. tmpz = projz - z;
  12203. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  12204. if (tmpDistance < shortest) {
  12205. shortest = tmpDistance;
  12206. closest = fib;
  12207. if (projected) {
  12208. projected.x = projx;
  12209. projected.y = projy;
  12210. projected.z = projz;
  12211. }
  12212. }
  12213. }
  12214. }
  12215. return closest;
  12216. };
  12217. /**
  12218. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  12219. */
  12220. AbstractMesh.prototype.getFacetDataParameters = function () {
  12221. return this._facetParameters;
  12222. };
  12223. /**
  12224. * Disables the feature FacetData and frees the related memory.
  12225. * Returns the mesh.
  12226. */
  12227. AbstractMesh.prototype.disableFacetData = function () {
  12228. if (this._facetDataEnabled) {
  12229. this._facetDataEnabled = false;
  12230. this._facetPositions = null;
  12231. this._facetNormals = null;
  12232. this._facetPartitioning = null;
  12233. this._facetParameters = null;
  12234. }
  12235. return this;
  12236. };
  12237. return AbstractMesh;
  12238. }(BABYLON.Node));
  12239. // Statics
  12240. AbstractMesh._BILLBOARDMODE_NONE = 0;
  12241. AbstractMesh._BILLBOARDMODE_X = 1;
  12242. AbstractMesh._BILLBOARDMODE_Y = 2;
  12243. AbstractMesh._BILLBOARDMODE_Z = 4;
  12244. AbstractMesh._BILLBOARDMODE_ALL = 7;
  12245. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  12246. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  12247. BABYLON.AbstractMesh = AbstractMesh;
  12248. })(BABYLON || (BABYLON = {}));
  12249. //# sourceMappingURL=babylon.abstractMesh.js.map
  12250. var BABYLON;
  12251. (function (BABYLON) {
  12252. var Light = (function (_super) {
  12253. __extends(Light, _super);
  12254. function Light(name, scene) {
  12255. var _this = _super.call(this, name, scene) || this;
  12256. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  12257. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  12258. _this.intensity = 1.0;
  12259. _this.range = Number.MAX_VALUE;
  12260. _this.includeOnlyWithLayerMask = 0;
  12261. _this.includedOnlyMeshes = new Array();
  12262. _this.excludedMeshes = new Array();
  12263. _this.excludeWithLayerMask = 0;
  12264. _this.lightmapMode = 0;
  12265. // PBR Properties.
  12266. _this.radius = 0.00001;
  12267. _this._excludedMeshesIds = new Array();
  12268. _this._includedOnlyMeshesIds = new Array();
  12269. scene.addLight(_this);
  12270. return _this;
  12271. }
  12272. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  12273. /**
  12274. * If every light affecting the material is in this lightmapMode,
  12275. * material.lightmapTexture adds or multiplies
  12276. * (depends on material.useLightmapAsShadowmap)
  12277. * after every other light calculations.
  12278. */
  12279. get: function () {
  12280. return Light._LIGHTMAP_DEFAULT;
  12281. },
  12282. enumerable: true,
  12283. configurable: true
  12284. });
  12285. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  12286. /**
  12287. * material.lightmapTexture as only diffuse lighting from this light
  12288. * adds pnly specular lighting from this light
  12289. * adds dynamic shadows
  12290. */
  12291. get: function () {
  12292. return Light._LIGHTMAP_SPECULAR;
  12293. },
  12294. enumerable: true,
  12295. configurable: true
  12296. });
  12297. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  12298. /**
  12299. * material.lightmapTexture as only lighting
  12300. * no light calculation from this light
  12301. * only adds dynamic shadows from this light
  12302. */
  12303. get: function () {
  12304. return Light._LIGHTMAP_SHADOWSONLY;
  12305. },
  12306. enumerable: true,
  12307. configurable: true
  12308. });
  12309. Light.prototype.getClassName = function () {
  12310. return "Light";
  12311. };
  12312. /**
  12313. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12314. */
  12315. Light.prototype.toString = function (fullDetails) {
  12316. var ret = "Name: " + this.name;
  12317. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  12318. if (this.animations) {
  12319. for (var i = 0; i < this.animations.length; i++) {
  12320. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  12321. }
  12322. }
  12323. if (fullDetails) {
  12324. }
  12325. return ret;
  12326. };
  12327. Light.prototype.getShadowGenerator = function () {
  12328. return this._shadowGenerator;
  12329. };
  12330. Light.prototype.getAbsolutePosition = function () {
  12331. return BABYLON.Vector3.Zero();
  12332. };
  12333. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  12334. };
  12335. Light.prototype._getWorldMatrix = function () {
  12336. return BABYLON.Matrix.Identity();
  12337. };
  12338. Light.prototype.canAffectMesh = function (mesh) {
  12339. if (!mesh) {
  12340. return true;
  12341. }
  12342. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  12343. return false;
  12344. }
  12345. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  12346. return false;
  12347. }
  12348. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  12349. return false;
  12350. }
  12351. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  12352. return false;
  12353. }
  12354. return true;
  12355. };
  12356. Light.prototype.getWorldMatrix = function () {
  12357. this._currentRenderId = this.getScene().getRenderId();
  12358. var worldMatrix = this._getWorldMatrix();
  12359. if (this.parent && this.parent.getWorldMatrix) {
  12360. if (!this._parentedWorldMatrix) {
  12361. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  12362. }
  12363. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  12364. this._markSyncedWithParent();
  12365. return this._parentedWorldMatrix;
  12366. }
  12367. return worldMatrix;
  12368. };
  12369. Light.prototype.dispose = function () {
  12370. if (this._shadowGenerator) {
  12371. this._shadowGenerator.dispose();
  12372. this._shadowGenerator = null;
  12373. }
  12374. // Animations
  12375. this.getScene().stopAnimation(this);
  12376. // Remove from scene
  12377. this.getScene().removeLight(this);
  12378. _super.prototype.dispose.call(this);
  12379. };
  12380. Light.prototype.getTypeID = function () {
  12381. return 0;
  12382. };
  12383. Light.prototype.clone = function (name) {
  12384. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  12385. };
  12386. Light.prototype.serialize = function () {
  12387. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  12388. // Type
  12389. serializationObject.type = this.getTypeID();
  12390. // Parent
  12391. if (this.parent) {
  12392. serializationObject.parentId = this.parent.id;
  12393. }
  12394. // Inclusion / exclusions
  12395. if (this.excludedMeshes.length > 0) {
  12396. serializationObject.excludedMeshesIds = [];
  12397. this.excludedMeshes.forEach(function (mesh) {
  12398. serializationObject.excludedMeshesIds.push(mesh.id);
  12399. });
  12400. }
  12401. if (this.includedOnlyMeshes.length > 0) {
  12402. serializationObject.includedOnlyMeshesIds = [];
  12403. this.includedOnlyMeshes.forEach(function (mesh) {
  12404. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  12405. });
  12406. }
  12407. // Animations
  12408. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  12409. serializationObject.ranges = this.serializeAnimationRanges();
  12410. return serializationObject;
  12411. };
  12412. Light.GetConstructorFromName = function (type, name, scene) {
  12413. switch (type) {
  12414. case 0:
  12415. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  12416. case 1:
  12417. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  12418. case 2:
  12419. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  12420. case 3:
  12421. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  12422. }
  12423. };
  12424. Light.Parse = function (parsedLight, scene) {
  12425. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  12426. // Inclusion / exclusions
  12427. if (parsedLight.excludedMeshesIds) {
  12428. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  12429. }
  12430. if (parsedLight.includedOnlyMeshesIds) {
  12431. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  12432. }
  12433. // Parent
  12434. if (parsedLight.parentId) {
  12435. light._waitingParentId = parsedLight.parentId;
  12436. }
  12437. // Animations
  12438. if (parsedLight.animations) {
  12439. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  12440. var parsedAnimation = parsedLight.animations[animationIndex];
  12441. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  12442. }
  12443. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  12444. }
  12445. if (parsedLight.autoAnimate) {
  12446. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  12447. }
  12448. return light;
  12449. };
  12450. return Light;
  12451. }(BABYLON.Node));
  12452. //lightmapMode Consts
  12453. Light._LIGHTMAP_DEFAULT = 0;
  12454. Light._LIGHTMAP_SPECULAR = 1;
  12455. Light._LIGHTMAP_SHADOWSONLY = 2;
  12456. __decorate([
  12457. BABYLON.serializeAsColor3()
  12458. ], Light.prototype, "diffuse", void 0);
  12459. __decorate([
  12460. BABYLON.serializeAsColor3()
  12461. ], Light.prototype, "specular", void 0);
  12462. __decorate([
  12463. BABYLON.serialize()
  12464. ], Light.prototype, "intensity", void 0);
  12465. __decorate([
  12466. BABYLON.serialize()
  12467. ], Light.prototype, "range", void 0);
  12468. __decorate([
  12469. BABYLON.serialize()
  12470. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  12471. __decorate([
  12472. BABYLON.serialize()
  12473. ], Light.prototype, "excludeWithLayerMask", void 0);
  12474. __decorate([
  12475. BABYLON.serialize()
  12476. ], Light.prototype, "lightmapMode", void 0);
  12477. __decorate([
  12478. BABYLON.serialize()
  12479. ], Light.prototype, "radius", void 0);
  12480. BABYLON.Light = Light;
  12481. })(BABYLON || (BABYLON = {}));
  12482. //# sourceMappingURL=babylon.light.js.map
  12483. var BABYLON;
  12484. (function (BABYLON) {
  12485. var PointLight = (function (_super) {
  12486. __extends(PointLight, _super);
  12487. function PointLight(name, position, scene) {
  12488. var _this = _super.call(this, name, scene) || this;
  12489. _this.position = position;
  12490. return _this;
  12491. }
  12492. PointLight.prototype.getClassName = function () {
  12493. return "PointLight";
  12494. };
  12495. PointLight.prototype.getAbsolutePosition = function () {
  12496. return this.transformedPosition ? this.transformedPosition : this.position;
  12497. };
  12498. PointLight.prototype.computeTransformedPosition = function () {
  12499. if (this.parent && this.parent.getWorldMatrix) {
  12500. if (!this.transformedPosition) {
  12501. this.transformedPosition = BABYLON.Vector3.Zero();
  12502. }
  12503. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12504. return true;
  12505. }
  12506. return false;
  12507. };
  12508. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  12509. if (this.parent && this.parent.getWorldMatrix) {
  12510. this.computeTransformedPosition();
  12511. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  12512. return;
  12513. }
  12514. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  12515. };
  12516. PointLight.prototype.needCube = function () {
  12517. return true;
  12518. };
  12519. PointLight.prototype.supportsVSM = function () {
  12520. return false;
  12521. };
  12522. PointLight.prototype.needRefreshPerFrame = function () {
  12523. return false;
  12524. };
  12525. PointLight.prototype.getShadowDirection = function (faceIndex) {
  12526. switch (faceIndex) {
  12527. case 0:
  12528. return new BABYLON.Vector3(1, 0, 0);
  12529. case 1:
  12530. return new BABYLON.Vector3(-1, 0, 0);
  12531. case 2:
  12532. return new BABYLON.Vector3(0, -1, 0);
  12533. case 3:
  12534. return new BABYLON.Vector3(0, 1, 0);
  12535. case 4:
  12536. return new BABYLON.Vector3(0, 0, 1);
  12537. case 5:
  12538. return new BABYLON.Vector3(0, 0, -1);
  12539. }
  12540. return BABYLON.Vector3.Zero();
  12541. };
  12542. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12543. var activeCamera = this.getScene().activeCamera;
  12544. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  12545. };
  12546. PointLight.prototype._getWorldMatrix = function () {
  12547. if (!this._worldMatrix) {
  12548. this._worldMatrix = BABYLON.Matrix.Identity();
  12549. }
  12550. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12551. return this._worldMatrix;
  12552. };
  12553. PointLight.prototype.getTypeID = function () {
  12554. return 0;
  12555. };
  12556. return PointLight;
  12557. }(BABYLON.Light));
  12558. __decorate([
  12559. BABYLON.serializeAsVector3()
  12560. ], PointLight.prototype, "position", void 0);
  12561. BABYLON.PointLight = PointLight;
  12562. })(BABYLON || (BABYLON = {}));
  12563. //# sourceMappingURL=babylon.pointLight.js.map
  12564. var BABYLON;
  12565. (function (BABYLON) {
  12566. var SpotLight = (function (_super) {
  12567. __extends(SpotLight, _super);
  12568. function SpotLight(name, position, direction, angle, exponent, scene) {
  12569. var _this = _super.call(this, name, scene) || this;
  12570. _this.position = position;
  12571. _this.direction = direction;
  12572. _this.angle = angle;
  12573. _this.exponent = exponent;
  12574. return _this;
  12575. }
  12576. SpotLight.prototype.getClassName = function () {
  12577. return "SpotLight";
  12578. };
  12579. SpotLight.prototype.getAbsolutePosition = function () {
  12580. return this.transformedPosition ? this.transformedPosition : this.position;
  12581. };
  12582. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12583. var activeCamera = this.getScene().activeCamera;
  12584. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  12585. };
  12586. SpotLight.prototype.needCube = function () {
  12587. return false;
  12588. };
  12589. SpotLight.prototype.supportsVSM = function () {
  12590. return true;
  12591. };
  12592. SpotLight.prototype.needRefreshPerFrame = function () {
  12593. return false;
  12594. };
  12595. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  12596. return this.direction;
  12597. };
  12598. SpotLight.prototype.setDirectionToTarget = function (target) {
  12599. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  12600. return this.direction;
  12601. };
  12602. SpotLight.prototype.computeTransformedPosition = function () {
  12603. if (this.parent && this.parent.getWorldMatrix) {
  12604. if (!this.transformedPosition) {
  12605. this.transformedPosition = BABYLON.Vector3.Zero();
  12606. }
  12607. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12608. return true;
  12609. }
  12610. return false;
  12611. };
  12612. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  12613. var normalizeDirection;
  12614. if (this.parent && this.parent.getWorldMatrix) {
  12615. if (!this._transformedDirection) {
  12616. this._transformedDirection = BABYLON.Vector3.Zero();
  12617. }
  12618. this.computeTransformedPosition();
  12619. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  12620. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  12621. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  12622. }
  12623. else {
  12624. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  12625. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  12626. }
  12627. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  12628. };
  12629. SpotLight.prototype._getWorldMatrix = function () {
  12630. if (!this._worldMatrix) {
  12631. this._worldMatrix = BABYLON.Matrix.Identity();
  12632. }
  12633. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12634. return this._worldMatrix;
  12635. };
  12636. SpotLight.prototype.getTypeID = function () {
  12637. return 2;
  12638. };
  12639. SpotLight.prototype.getRotation = function () {
  12640. this.direction.normalize();
  12641. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  12642. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  12643. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  12644. };
  12645. return SpotLight;
  12646. }(BABYLON.Light));
  12647. __decorate([
  12648. BABYLON.serializeAsVector3()
  12649. ], SpotLight.prototype, "position", void 0);
  12650. __decorate([
  12651. BABYLON.serializeAsVector3()
  12652. ], SpotLight.prototype, "direction", void 0);
  12653. __decorate([
  12654. BABYLON.serialize()
  12655. ], SpotLight.prototype, "angle", void 0);
  12656. __decorate([
  12657. BABYLON.serialize()
  12658. ], SpotLight.prototype, "exponent", void 0);
  12659. BABYLON.SpotLight = SpotLight;
  12660. })(BABYLON || (BABYLON = {}));
  12661. //# sourceMappingURL=babylon.spotLight.js.map
  12662. var BABYLON;
  12663. (function (BABYLON) {
  12664. var HemisphericLight = (function (_super) {
  12665. __extends(HemisphericLight, _super);
  12666. function HemisphericLight(name, direction, scene) {
  12667. var _this = _super.call(this, name, scene) || this;
  12668. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  12669. _this.direction = direction;
  12670. return _this;
  12671. }
  12672. HemisphericLight.prototype.getClassName = function () {
  12673. return "HemisphericLight";
  12674. };
  12675. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  12676. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  12677. return this.direction;
  12678. };
  12679. HemisphericLight.prototype.getShadowGenerator = function () {
  12680. return null;
  12681. };
  12682. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  12683. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  12684. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  12685. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  12686. };
  12687. HemisphericLight.prototype._getWorldMatrix = function () {
  12688. if (!this._worldMatrix) {
  12689. this._worldMatrix = BABYLON.Matrix.Identity();
  12690. }
  12691. return this._worldMatrix;
  12692. };
  12693. HemisphericLight.prototype.getTypeID = function () {
  12694. return 3;
  12695. };
  12696. return HemisphericLight;
  12697. }(BABYLON.Light));
  12698. __decorate([
  12699. BABYLON.serializeAsColor3()
  12700. ], HemisphericLight.prototype, "groundColor", void 0);
  12701. __decorate([
  12702. BABYLON.serializeAsVector3()
  12703. ], HemisphericLight.prototype, "direction", void 0);
  12704. BABYLON.HemisphericLight = HemisphericLight;
  12705. })(BABYLON || (BABYLON = {}));
  12706. //# sourceMappingURL=babylon.hemisphericLight.js.map
  12707. var BABYLON;
  12708. (function (BABYLON) {
  12709. var DirectionalLight = (function (_super) {
  12710. __extends(DirectionalLight, _super);
  12711. function DirectionalLight(name, direction, scene) {
  12712. var _this = _super.call(this, name, scene) || this;
  12713. _this.shadowOrthoScale = 0.5;
  12714. _this.autoUpdateExtends = true;
  12715. // Cache
  12716. _this._orthoLeft = Number.MAX_VALUE;
  12717. _this._orthoRight = Number.MIN_VALUE;
  12718. _this._orthoTop = Number.MIN_VALUE;
  12719. _this._orthoBottom = Number.MAX_VALUE;
  12720. _this.position = direction.scale(-1);
  12721. _this.direction = direction;
  12722. return _this;
  12723. }
  12724. DirectionalLight.prototype.getClassName = function () {
  12725. return "DirectionalLight";
  12726. };
  12727. DirectionalLight.prototype.getAbsolutePosition = function () {
  12728. return this.transformedPosition ? this.transformedPosition : this.position;
  12729. };
  12730. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  12731. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  12732. return this.direction;
  12733. };
  12734. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  12735. var activeCamera = this.getScene().activeCamera;
  12736. // Check extends
  12737. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  12738. var tempVector3 = BABYLON.Vector3.Zero();
  12739. this._orthoLeft = Number.MAX_VALUE;
  12740. this._orthoRight = Number.MIN_VALUE;
  12741. this._orthoTop = Number.MIN_VALUE;
  12742. this._orthoBottom = Number.MAX_VALUE;
  12743. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  12744. var mesh = renderList[meshIndex];
  12745. if (!mesh) {
  12746. continue;
  12747. }
  12748. var boundingInfo = mesh.getBoundingInfo();
  12749. if (!boundingInfo) {
  12750. continue;
  12751. }
  12752. var boundingBox = boundingInfo.boundingBox;
  12753. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  12754. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  12755. if (tempVector3.x < this._orthoLeft)
  12756. this._orthoLeft = tempVector3.x;
  12757. if (tempVector3.y < this._orthoBottom)
  12758. this._orthoBottom = tempVector3.y;
  12759. if (tempVector3.x > this._orthoRight)
  12760. this._orthoRight = tempVector3.x;
  12761. if (tempVector3.y > this._orthoTop)
  12762. this._orthoTop = tempVector3.y;
  12763. }
  12764. }
  12765. }
  12766. var xOffset = this._orthoRight - this._orthoLeft;
  12767. var yOffset = this._orthoTop - this._orthoBottom;
  12768. 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);
  12769. };
  12770. DirectionalLight.prototype.supportsVSM = function () {
  12771. return true;
  12772. };
  12773. DirectionalLight.prototype.needRefreshPerFrame = function () {
  12774. return true;
  12775. };
  12776. DirectionalLight.prototype.needCube = function () {
  12777. return false;
  12778. };
  12779. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  12780. return this.direction;
  12781. };
  12782. DirectionalLight.prototype.computeTransformedPosition = function () {
  12783. if (this.parent && this.parent.getWorldMatrix) {
  12784. if (!this.transformedPosition) {
  12785. this.transformedPosition = BABYLON.Vector3.Zero();
  12786. }
  12787. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  12788. return true;
  12789. }
  12790. return false;
  12791. };
  12792. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  12793. if (this.parent && this.parent.getWorldMatrix) {
  12794. if (!this._transformedDirection) {
  12795. this._transformedDirection = BABYLON.Vector3.Zero();
  12796. }
  12797. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  12798. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  12799. return;
  12800. }
  12801. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  12802. };
  12803. DirectionalLight.prototype._getWorldMatrix = function () {
  12804. if (!this._worldMatrix) {
  12805. this._worldMatrix = BABYLON.Matrix.Identity();
  12806. }
  12807. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  12808. return this._worldMatrix;
  12809. };
  12810. DirectionalLight.prototype.getTypeID = function () {
  12811. return 1;
  12812. };
  12813. return DirectionalLight;
  12814. }(BABYLON.Light));
  12815. __decorate([
  12816. BABYLON.serializeAsVector3()
  12817. ], DirectionalLight.prototype, "position", void 0);
  12818. __decorate([
  12819. BABYLON.serializeAsVector3()
  12820. ], DirectionalLight.prototype, "direction", void 0);
  12821. __decorate([
  12822. BABYLON.serialize()
  12823. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  12824. __decorate([
  12825. BABYLON.serialize()
  12826. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  12827. BABYLON.DirectionalLight = DirectionalLight;
  12828. })(BABYLON || (BABYLON = {}));
  12829. //# sourceMappingURL=babylon.directionalLight.js.map
  12830. var BABYLON;
  12831. (function (BABYLON) {
  12832. var ShadowGenerator = (function () {
  12833. function ShadowGenerator(mapSize, light) {
  12834. var _this = this;
  12835. // Members
  12836. this._filter = ShadowGenerator.FILTER_NONE;
  12837. this.blurScale = 2;
  12838. this._blurBoxOffset = 0;
  12839. this._bias = 0.00005;
  12840. this._lightDirection = BABYLON.Vector3.Zero();
  12841. this.forceBackFacesOnly = false;
  12842. this._darkness = 0;
  12843. this._transparencyShadow = false;
  12844. this._viewMatrix = BABYLON.Matrix.Zero();
  12845. this._projectionMatrix = BABYLON.Matrix.Zero();
  12846. this._transformMatrix = BABYLON.Matrix.Zero();
  12847. this._worldViewProjection = BABYLON.Matrix.Zero();
  12848. this._currentFaceIndex = 0;
  12849. this._currentFaceIndexCache = 0;
  12850. this._useFullFloat = true;
  12851. this._light = light;
  12852. this._scene = light.getScene();
  12853. this._mapSize = mapSize;
  12854. light._shadowGenerator = this;
  12855. // Texture type fallback from float to int if not supported.
  12856. var textureType;
  12857. var caps = this._scene.getEngine().getCaps();
  12858. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  12859. this._useFullFloat = true;
  12860. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  12861. }
  12862. else {
  12863. this._useFullFloat = false;
  12864. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  12865. }
  12866. // Render target
  12867. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  12868. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12869. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12870. this._shadowMap.anisotropicFilteringLevel = 1;
  12871. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12872. this._shadowMap.renderParticles = false;
  12873. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  12874. _this._currentFaceIndex = faceIndex;
  12875. });
  12876. this._shadowMap.onAfterUnbindObservable.add(function () {
  12877. if (!_this.useBlurVarianceShadowMap) {
  12878. return;
  12879. }
  12880. if (!_this._shadowMap2) {
  12881. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  12882. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12883. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12884. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  12885. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  12886. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  12887. effect.setTexture("textureSampler", _this._shadowMap);
  12888. });
  12889. _this.blurBoxOffset = 1;
  12890. }
  12891. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  12892. });
  12893. // Custom render function
  12894. var renderSubMesh = function (subMesh) {
  12895. var mesh = subMesh.getRenderingMesh();
  12896. var scene = _this._scene;
  12897. var engine = scene.getEngine();
  12898. // Culling
  12899. engine.setState(subMesh.getMaterial().backFaceCulling);
  12900. // Managing instances
  12901. var batch = mesh._getInstancesRenderList(subMesh._id);
  12902. if (batch.mustReturn) {
  12903. return;
  12904. }
  12905. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  12906. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  12907. engine.enableEffect(_this._effect);
  12908. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  12909. var material = subMesh.getMaterial();
  12910. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  12911. _this._effect.setVector3("lightPosition", _this.getLight().position);
  12912. if (_this.getLight().needCube()) {
  12913. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  12914. }
  12915. // Alpha test
  12916. if (material && material.needAlphaTesting()) {
  12917. var alphaTexture = material.getAlphaTestTexture();
  12918. _this._effect.setTexture("diffuseSampler", alphaTexture);
  12919. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  12920. }
  12921. // Bones
  12922. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12923. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  12924. }
  12925. if (_this.forceBackFacesOnly) {
  12926. engine.setState(true, 0, false, true);
  12927. }
  12928. // Draw
  12929. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  12930. if (_this.forceBackFacesOnly) {
  12931. engine.setState(true, 0, false, false);
  12932. }
  12933. }
  12934. else {
  12935. // Need to reset refresh rate of the shadowMap
  12936. _this._shadowMap.resetRefreshCounter();
  12937. }
  12938. };
  12939. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  12940. var index;
  12941. for (index = 0; index < opaqueSubMeshes.length; index++) {
  12942. renderSubMesh(opaqueSubMeshes.data[index]);
  12943. }
  12944. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  12945. renderSubMesh(alphaTestSubMeshes.data[index]);
  12946. }
  12947. if (_this._transparencyShadow) {
  12948. for (index = 0; index < transparentSubMeshes.length; index++) {
  12949. renderSubMesh(transparentSubMeshes.data[index]);
  12950. }
  12951. }
  12952. };
  12953. this._shadowMap.onClearObservable.add(function (engine) {
  12954. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  12955. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  12956. }
  12957. else {
  12958. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  12959. }
  12960. });
  12961. }
  12962. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  12963. // Static
  12964. get: function () {
  12965. return ShadowGenerator._FILTER_NONE;
  12966. },
  12967. enumerable: true,
  12968. configurable: true
  12969. });
  12970. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  12971. get: function () {
  12972. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  12973. },
  12974. enumerable: true,
  12975. configurable: true
  12976. });
  12977. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  12978. get: function () {
  12979. return ShadowGenerator._FILTER_POISSONSAMPLING;
  12980. },
  12981. enumerable: true,
  12982. configurable: true
  12983. });
  12984. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  12985. get: function () {
  12986. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  12987. },
  12988. enumerable: true,
  12989. configurable: true
  12990. });
  12991. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  12992. get: function () {
  12993. return this._bias;
  12994. },
  12995. set: function (bias) {
  12996. this._bias = bias;
  12997. },
  12998. enumerable: true,
  12999. configurable: true
  13000. });
  13001. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  13002. get: function () {
  13003. return this._blurBoxOffset;
  13004. },
  13005. set: function (value) {
  13006. var _this = this;
  13007. if (this._blurBoxOffset === value) {
  13008. return;
  13009. }
  13010. this._blurBoxOffset = value;
  13011. if (this._boxBlurPostprocess) {
  13012. this._boxBlurPostprocess.dispose();
  13013. }
  13014. 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);
  13015. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  13016. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  13017. });
  13018. },
  13019. enumerable: true,
  13020. configurable: true
  13021. });
  13022. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  13023. get: function () {
  13024. return this._filter;
  13025. },
  13026. set: function (value) {
  13027. if (this._filter === value) {
  13028. return;
  13029. }
  13030. this._filter = value;
  13031. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  13032. this._shadowMap.anisotropicFilteringLevel = 16;
  13033. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  13034. }
  13035. else {
  13036. this._shadowMap.anisotropicFilteringLevel = 1;
  13037. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  13038. }
  13039. },
  13040. enumerable: true,
  13041. configurable: true
  13042. });
  13043. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  13044. get: function () {
  13045. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  13046. },
  13047. set: function (value) {
  13048. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  13049. },
  13050. enumerable: true,
  13051. configurable: true
  13052. });
  13053. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  13054. get: function () {
  13055. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  13056. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  13057. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  13058. },
  13059. set: function (value) {
  13060. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  13061. },
  13062. enumerable: true,
  13063. configurable: true
  13064. });
  13065. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  13066. get: function () {
  13067. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  13068. },
  13069. set: function (value) {
  13070. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  13071. },
  13072. enumerable: true,
  13073. configurable: true
  13074. });
  13075. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  13076. var defines = [];
  13077. if (this._useFullFloat) {
  13078. defines.push("#define FULLFLOAT");
  13079. }
  13080. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  13081. defines.push("#define VSM");
  13082. }
  13083. if (this.getLight().needCube()) {
  13084. defines.push("#define CUBEMAP");
  13085. }
  13086. var attribs = [BABYLON.VertexBuffer.PositionKind];
  13087. var mesh = subMesh.getMesh();
  13088. var material = subMesh.getMaterial();
  13089. // Alpha test
  13090. if (material && material.needAlphaTesting()) {
  13091. defines.push("#define ALPHATEST");
  13092. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  13093. attribs.push(BABYLON.VertexBuffer.UVKind);
  13094. defines.push("#define UV1");
  13095. }
  13096. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  13097. var alphaTexture = material.getAlphaTestTexture();
  13098. if (alphaTexture.coordinatesIndex === 1) {
  13099. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  13100. defines.push("#define UV2");
  13101. }
  13102. }
  13103. }
  13104. // Bones
  13105. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  13106. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  13107. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  13108. if (mesh.numBoneInfluencers > 4) {
  13109. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  13110. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  13111. }
  13112. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  13113. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  13114. }
  13115. else {
  13116. defines.push("#define NUM_BONE_INFLUENCERS 0");
  13117. }
  13118. // Instances
  13119. if (useInstances) {
  13120. defines.push("#define INSTANCES");
  13121. attribs.push("world0");
  13122. attribs.push("world1");
  13123. attribs.push("world2");
  13124. attribs.push("world3");
  13125. }
  13126. // Get correct effect
  13127. var join = defines.join("\n");
  13128. if (this._cachedDefines !== join) {
  13129. this._cachedDefines = join;
  13130. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  13131. }
  13132. return this._effect.isReady();
  13133. };
  13134. ShadowGenerator.prototype.getShadowMap = function () {
  13135. return this._shadowMap;
  13136. };
  13137. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  13138. if (this._shadowMap2) {
  13139. return this._shadowMap2;
  13140. }
  13141. return this._shadowMap;
  13142. };
  13143. ShadowGenerator.prototype.getLight = function () {
  13144. return this._light;
  13145. };
  13146. // Methods
  13147. ShadowGenerator.prototype.getTransformMatrix = function () {
  13148. var scene = this._scene;
  13149. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  13150. return this._transformMatrix;
  13151. }
  13152. this._currentRenderID = scene.getRenderId();
  13153. this._currentFaceIndexCache = this._currentFaceIndex;
  13154. var lightPosition = this._light.position;
  13155. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  13156. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  13157. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  13158. }
  13159. if (this._light.computeTransformedPosition()) {
  13160. lightPosition = this._light.transformedPosition;
  13161. }
  13162. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  13163. this._cachedPosition = lightPosition.clone();
  13164. this._cachedDirection = this._lightDirection.clone();
  13165. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  13166. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  13167. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13168. }
  13169. return this._transformMatrix;
  13170. };
  13171. ShadowGenerator.prototype.getDarkness = function () {
  13172. return this._darkness;
  13173. };
  13174. ShadowGenerator.prototype.setDarkness = function (darkness) {
  13175. if (darkness >= 1.0)
  13176. this._darkness = 1.0;
  13177. else if (darkness <= 0.0)
  13178. this._darkness = 0.0;
  13179. else
  13180. this._darkness = darkness;
  13181. };
  13182. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  13183. this._transparencyShadow = hasShadow;
  13184. };
  13185. ShadowGenerator.prototype._packHalf = function (depth) {
  13186. var scale = depth * 255.0;
  13187. var fract = scale - Math.floor(scale);
  13188. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  13189. };
  13190. ShadowGenerator.prototype.dispose = function () {
  13191. this._shadowMap.dispose();
  13192. if (this._shadowMap2) {
  13193. this._shadowMap2.dispose();
  13194. }
  13195. if (this._downSamplePostprocess) {
  13196. this._downSamplePostprocess.dispose();
  13197. }
  13198. if (this._boxBlurPostprocess) {
  13199. this._boxBlurPostprocess.dispose();
  13200. }
  13201. this._light._shadowGenerator = null;
  13202. };
  13203. ShadowGenerator.prototype.serialize = function () {
  13204. var serializationObject = {};
  13205. serializationObject.lightId = this._light.id;
  13206. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  13207. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  13208. serializationObject.usePoissonSampling = this.usePoissonSampling;
  13209. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  13210. serializationObject.renderList = [];
  13211. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  13212. var mesh = this.getShadowMap().renderList[meshIndex];
  13213. serializationObject.renderList.push(mesh.id);
  13214. }
  13215. return serializationObject;
  13216. };
  13217. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  13218. //casting to point light, as light is missing the position attr and typescript complains.
  13219. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  13220. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  13221. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  13222. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  13223. meshes.forEach(function (mesh) {
  13224. shadowGenerator.getShadowMap().renderList.push(mesh);
  13225. });
  13226. }
  13227. if (parsedShadowGenerator.usePoissonSampling) {
  13228. shadowGenerator.usePoissonSampling = true;
  13229. }
  13230. else if (parsedShadowGenerator.useVarianceShadowMap) {
  13231. shadowGenerator.useVarianceShadowMap = true;
  13232. }
  13233. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  13234. shadowGenerator.useBlurVarianceShadowMap = true;
  13235. if (parsedShadowGenerator.blurScale) {
  13236. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  13237. }
  13238. if (parsedShadowGenerator.blurBoxOffset) {
  13239. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  13240. }
  13241. }
  13242. if (parsedShadowGenerator.bias !== undefined) {
  13243. shadowGenerator.bias = parsedShadowGenerator.bias;
  13244. }
  13245. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  13246. return shadowGenerator;
  13247. };
  13248. return ShadowGenerator;
  13249. }());
  13250. ShadowGenerator._FILTER_NONE = 0;
  13251. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  13252. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  13253. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  13254. BABYLON.ShadowGenerator = ShadowGenerator;
  13255. })(BABYLON || (BABYLON = {}));
  13256. //# sourceMappingURL=babylon.shadowGenerator.js.map
  13257. var BABYLON;
  13258. (function (BABYLON) {
  13259. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  13260. if (boxMin.x > sphereCenter.x + sphereRadius)
  13261. return false;
  13262. if (sphereCenter.x - sphereRadius > boxMax.x)
  13263. return false;
  13264. if (boxMin.y > sphereCenter.y + sphereRadius)
  13265. return false;
  13266. if (sphereCenter.y - sphereRadius > boxMax.y)
  13267. return false;
  13268. if (boxMin.z > sphereCenter.z + sphereRadius)
  13269. return false;
  13270. if (sphereCenter.z - sphereRadius > boxMax.z)
  13271. return false;
  13272. return true;
  13273. };
  13274. var getLowestRoot = (function () {
  13275. var result = { root: 0, found: false };
  13276. return function (a, b, c, maxR) {
  13277. result.root = 0;
  13278. result.found = false;
  13279. var determinant = b * b - 4.0 * a * c;
  13280. if (determinant < 0)
  13281. return result;
  13282. var sqrtD = Math.sqrt(determinant);
  13283. var r1 = (-b - sqrtD) / (2.0 * a);
  13284. var r2 = (-b + sqrtD) / (2.0 * a);
  13285. if (r1 > r2) {
  13286. var temp = r2;
  13287. r2 = r1;
  13288. r1 = temp;
  13289. }
  13290. if (r1 > 0 && r1 < maxR) {
  13291. result.root = r1;
  13292. result.found = true;
  13293. return result;
  13294. }
  13295. if (r2 > 0 && r2 < maxR) {
  13296. result.root = r2;
  13297. result.found = true;
  13298. return result;
  13299. }
  13300. return result;
  13301. };
  13302. })();
  13303. var Collider = (function () {
  13304. function Collider() {
  13305. this.radius = new BABYLON.Vector3(1, 1, 1);
  13306. this.retry = 0;
  13307. this.basePointWorld = BABYLON.Vector3.Zero();
  13308. this.velocityWorld = BABYLON.Vector3.Zero();
  13309. this.normalizedVelocity = BABYLON.Vector3.Zero();
  13310. this._collisionPoint = BABYLON.Vector3.Zero();
  13311. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  13312. this._tempVector = BABYLON.Vector3.Zero();
  13313. this._tempVector2 = BABYLON.Vector3.Zero();
  13314. this._tempVector3 = BABYLON.Vector3.Zero();
  13315. this._tempVector4 = BABYLON.Vector3.Zero();
  13316. this._edge = BABYLON.Vector3.Zero();
  13317. this._baseToVertex = BABYLON.Vector3.Zero();
  13318. this._destinationPoint = BABYLON.Vector3.Zero();
  13319. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  13320. this._displacementVector = BABYLON.Vector3.Zero();
  13321. }
  13322. // Methods
  13323. Collider.prototype._initialize = function (source, dir, e) {
  13324. this.velocity = dir;
  13325. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  13326. this.basePoint = source;
  13327. source.multiplyToRef(this.radius, this.basePointWorld);
  13328. dir.multiplyToRef(this.radius, this.velocityWorld);
  13329. this.velocityWorldLength = this.velocityWorld.length();
  13330. this.epsilon = e;
  13331. this.collisionFound = false;
  13332. };
  13333. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  13334. pa.subtractToRef(point, this._tempVector);
  13335. pb.subtractToRef(point, this._tempVector2);
  13336. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  13337. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  13338. if (d < 0)
  13339. return false;
  13340. pc.subtractToRef(point, this._tempVector3);
  13341. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  13342. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  13343. if (d < 0)
  13344. return false;
  13345. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  13346. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  13347. return d >= 0;
  13348. };
  13349. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  13350. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  13351. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  13352. if (distance > this.velocityWorldLength + max + sphereRadius) {
  13353. return false;
  13354. }
  13355. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  13356. return false;
  13357. return true;
  13358. };
  13359. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  13360. var t0;
  13361. var embeddedInPlane = false;
  13362. //defensive programming, actually not needed.
  13363. if (!trianglePlaneArray) {
  13364. trianglePlaneArray = [];
  13365. }
  13366. if (!trianglePlaneArray[faceIndex]) {
  13367. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  13368. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  13369. }
  13370. var trianglePlane = trianglePlaneArray[faceIndex];
  13371. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  13372. return;
  13373. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  13374. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  13375. if (normalDotVelocity == 0) {
  13376. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  13377. return;
  13378. embeddedInPlane = true;
  13379. t0 = 0;
  13380. }
  13381. else {
  13382. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  13383. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  13384. if (t0 > t1) {
  13385. var temp = t1;
  13386. t1 = t0;
  13387. t0 = temp;
  13388. }
  13389. if (t0 > 1.0 || t1 < 0.0)
  13390. return;
  13391. if (t0 < 0)
  13392. t0 = 0;
  13393. if (t0 > 1.0)
  13394. t0 = 1.0;
  13395. }
  13396. this._collisionPoint.copyFromFloats(0, 0, 0);
  13397. var found = false;
  13398. var t = 1.0;
  13399. if (!embeddedInPlane) {
  13400. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  13401. this.velocity.scaleToRef(t0, this._tempVector);
  13402. this._planeIntersectionPoint.addInPlace(this._tempVector);
  13403. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  13404. found = true;
  13405. t = t0;
  13406. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  13407. }
  13408. }
  13409. if (!found) {
  13410. var velocitySquaredLength = this.velocity.lengthSquared();
  13411. var a = velocitySquaredLength;
  13412. this.basePoint.subtractToRef(p1, this._tempVector);
  13413. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  13414. var c = this._tempVector.lengthSquared() - 1.0;
  13415. var lowestRoot = getLowestRoot(a, b, c, t);
  13416. if (lowestRoot.found) {
  13417. t = lowestRoot.root;
  13418. found = true;
  13419. this._collisionPoint.copyFrom(p1);
  13420. }
  13421. this.basePoint.subtractToRef(p2, this._tempVector);
  13422. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  13423. c = this._tempVector.lengthSquared() - 1.0;
  13424. lowestRoot = getLowestRoot(a, b, c, t);
  13425. if (lowestRoot.found) {
  13426. t = lowestRoot.root;
  13427. found = true;
  13428. this._collisionPoint.copyFrom(p2);
  13429. }
  13430. this.basePoint.subtractToRef(p3, this._tempVector);
  13431. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  13432. c = this._tempVector.lengthSquared() - 1.0;
  13433. lowestRoot = getLowestRoot(a, b, c, t);
  13434. if (lowestRoot.found) {
  13435. t = lowestRoot.root;
  13436. found = true;
  13437. this._collisionPoint.copyFrom(p3);
  13438. }
  13439. p2.subtractToRef(p1, this._edge);
  13440. p1.subtractToRef(this.basePoint, this._baseToVertex);
  13441. var edgeSquaredLength = this._edge.lengthSquared();
  13442. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  13443. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  13444. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  13445. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  13446. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  13447. lowestRoot = getLowestRoot(a, b, c, t);
  13448. if (lowestRoot.found) {
  13449. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  13450. if (f >= 0.0 && f <= 1.0) {
  13451. t = lowestRoot.root;
  13452. found = true;
  13453. this._edge.scaleInPlace(f);
  13454. p1.addToRef(this._edge, this._collisionPoint);
  13455. }
  13456. }
  13457. p3.subtractToRef(p2, this._edge);
  13458. p2.subtractToRef(this.basePoint, this._baseToVertex);
  13459. edgeSquaredLength = this._edge.lengthSquared();
  13460. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  13461. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  13462. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  13463. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  13464. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  13465. lowestRoot = getLowestRoot(a, b, c, t);
  13466. if (lowestRoot.found) {
  13467. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  13468. if (f >= 0.0 && f <= 1.0) {
  13469. t = lowestRoot.root;
  13470. found = true;
  13471. this._edge.scaleInPlace(f);
  13472. p2.addToRef(this._edge, this._collisionPoint);
  13473. }
  13474. }
  13475. p1.subtractToRef(p3, this._edge);
  13476. p3.subtractToRef(this.basePoint, this._baseToVertex);
  13477. edgeSquaredLength = this._edge.lengthSquared();
  13478. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  13479. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  13480. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  13481. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  13482. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  13483. lowestRoot = getLowestRoot(a, b, c, t);
  13484. if (lowestRoot.found) {
  13485. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  13486. if (f >= 0.0 && f <= 1.0) {
  13487. t = lowestRoot.root;
  13488. found = true;
  13489. this._edge.scaleInPlace(f);
  13490. p3.addToRef(this._edge, this._collisionPoint);
  13491. }
  13492. }
  13493. }
  13494. if (found) {
  13495. var distToCollision = t * this.velocity.length();
  13496. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  13497. if (!this.intersectionPoint) {
  13498. this.intersectionPoint = this._collisionPoint.clone();
  13499. }
  13500. else {
  13501. this.intersectionPoint.copyFrom(this._collisionPoint);
  13502. }
  13503. this.nearestDistance = distToCollision;
  13504. this.collisionFound = true;
  13505. }
  13506. }
  13507. };
  13508. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  13509. for (var i = indexStart; i < indexEnd; i += 3) {
  13510. var p1 = pts[indices[i] - decal];
  13511. var p2 = pts[indices[i + 1] - decal];
  13512. var p3 = pts[indices[i + 2] - decal];
  13513. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  13514. }
  13515. };
  13516. Collider.prototype._getResponse = function (pos, vel) {
  13517. pos.addToRef(vel, this._destinationPoint);
  13518. vel.scaleInPlace((this.nearestDistance / vel.length()));
  13519. this.basePoint.addToRef(vel, pos);
  13520. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  13521. this._slidePlaneNormal.normalize();
  13522. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  13523. pos.addInPlace(this._displacementVector);
  13524. this.intersectionPoint.addInPlace(this._displacementVector);
  13525. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  13526. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  13527. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  13528. };
  13529. return Collider;
  13530. }());
  13531. BABYLON.Collider = Collider;
  13532. })(BABYLON || (BABYLON = {}));
  13533. //# sourceMappingURL=babylon.collider.js.map
  13534. var BABYLON;
  13535. (function (BABYLON) {
  13536. //WebWorker code will be inserted to this variable.
  13537. BABYLON.CollisionWorker = "";
  13538. var WorkerTaskType;
  13539. (function (WorkerTaskType) {
  13540. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  13541. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  13542. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  13543. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  13544. var WorkerReplyType;
  13545. (function (WorkerReplyType) {
  13546. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  13547. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  13548. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  13549. var CollisionCoordinatorWorker = (function () {
  13550. function CollisionCoordinatorWorker() {
  13551. var _this = this;
  13552. this._scaledPosition = BABYLON.Vector3.Zero();
  13553. this._scaledVelocity = BABYLON.Vector3.Zero();
  13554. this.onMeshUpdated = function (mesh) {
  13555. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  13556. };
  13557. this.onGeometryUpdated = function (geometry) {
  13558. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  13559. };
  13560. this._afterRender = function () {
  13561. if (!_this._init)
  13562. return;
  13563. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  13564. return;
  13565. }
  13566. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  13567. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  13568. if (_this._runningUpdated > 4) {
  13569. return;
  13570. }
  13571. ++_this._runningUpdated;
  13572. var payload = {
  13573. updatedMeshes: _this._addUpdateMeshesList,
  13574. updatedGeometries: _this._addUpdateGeometriesList,
  13575. removedGeometries: _this._toRemoveGeometryArray,
  13576. removedMeshes: _this._toRemoveMeshesArray
  13577. };
  13578. var message = {
  13579. payload: payload,
  13580. taskType: WorkerTaskType.UPDATE
  13581. };
  13582. var serializable = [];
  13583. for (var id in payload.updatedGeometries) {
  13584. if (payload.updatedGeometries.hasOwnProperty(id)) {
  13585. //prepare transferables
  13586. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  13587. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  13588. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  13589. }
  13590. }
  13591. _this._worker.postMessage(message, serializable);
  13592. _this._addUpdateMeshesList = {};
  13593. _this._addUpdateGeometriesList = {};
  13594. _this._toRemoveGeometryArray = [];
  13595. _this._toRemoveMeshesArray = [];
  13596. };
  13597. this._onMessageFromWorker = function (e) {
  13598. var returnData = e.data;
  13599. if (returnData.error != WorkerReplyType.SUCCESS) {
  13600. //TODO what errors can be returned from the worker?
  13601. BABYLON.Tools.Warn("error returned from worker!");
  13602. return;
  13603. }
  13604. switch (returnData.taskType) {
  13605. case WorkerTaskType.INIT:
  13606. _this._init = true;
  13607. //Update the worked with ALL of the scene's current state
  13608. _this._scene.meshes.forEach(function (mesh) {
  13609. _this.onMeshAdded(mesh);
  13610. });
  13611. _this._scene.getGeometries().forEach(function (geometry) {
  13612. _this.onGeometryAdded(geometry);
  13613. });
  13614. break;
  13615. case WorkerTaskType.UPDATE:
  13616. _this._runningUpdated--;
  13617. break;
  13618. case WorkerTaskType.COLLIDE:
  13619. _this._runningCollisionTask = false;
  13620. var returnPayload = returnData.payload;
  13621. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  13622. return;
  13623. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  13624. //cleanup
  13625. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  13626. break;
  13627. }
  13628. };
  13629. this._collisionsCallbackArray = [];
  13630. this._init = false;
  13631. this._runningUpdated = 0;
  13632. this._runningCollisionTask = false;
  13633. this._addUpdateMeshesList = {};
  13634. this._addUpdateGeometriesList = {};
  13635. this._toRemoveGeometryArray = [];
  13636. this._toRemoveMeshesArray = [];
  13637. }
  13638. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  13639. if (!this._init)
  13640. return;
  13641. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  13642. return;
  13643. position.divideToRef(collider.radius, this._scaledPosition);
  13644. velocity.divideToRef(collider.radius, this._scaledVelocity);
  13645. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  13646. var payload = {
  13647. collider: {
  13648. position: this._scaledPosition.asArray(),
  13649. velocity: this._scaledVelocity.asArray(),
  13650. radius: collider.radius.asArray()
  13651. },
  13652. collisionId: collisionIndex,
  13653. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  13654. maximumRetry: maximumRetry
  13655. };
  13656. var message = {
  13657. payload: payload,
  13658. taskType: WorkerTaskType.COLLIDE
  13659. };
  13660. this._worker.postMessage(message);
  13661. };
  13662. CollisionCoordinatorWorker.prototype.init = function (scene) {
  13663. this._scene = scene;
  13664. this._scene.registerAfterRender(this._afterRender);
  13665. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  13666. this._worker = new Worker(workerUrl);
  13667. this._worker.onmessage = this._onMessageFromWorker;
  13668. var message = {
  13669. payload: {},
  13670. taskType: WorkerTaskType.INIT
  13671. };
  13672. this._worker.postMessage(message);
  13673. };
  13674. CollisionCoordinatorWorker.prototype.destroy = function () {
  13675. this._scene.unregisterAfterRender(this._afterRender);
  13676. this._worker.terminate();
  13677. };
  13678. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  13679. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  13680. this.onMeshUpdated(mesh);
  13681. };
  13682. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  13683. this._toRemoveMeshesArray.push(mesh.uniqueId);
  13684. };
  13685. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  13686. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  13687. geometry.onGeometryUpdated = this.onGeometryUpdated;
  13688. this.onGeometryUpdated(geometry);
  13689. };
  13690. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  13691. this._toRemoveGeometryArray.push(geometry.id);
  13692. };
  13693. return CollisionCoordinatorWorker;
  13694. }());
  13695. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  13696. var submeshes = [];
  13697. if (mesh.subMeshes) {
  13698. submeshes = mesh.subMeshes.map(function (sm, idx) {
  13699. return {
  13700. position: idx,
  13701. verticesStart: sm.verticesStart,
  13702. verticesCount: sm.verticesCount,
  13703. indexStart: sm.indexStart,
  13704. indexCount: sm.indexCount,
  13705. hasMaterial: !!sm.getMaterial(),
  13706. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  13707. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  13708. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  13709. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  13710. };
  13711. });
  13712. }
  13713. var geometryId = null;
  13714. if (mesh instanceof BABYLON.Mesh) {
  13715. geometryId = mesh.geometry ? mesh.geometry.id : null;
  13716. }
  13717. else if (mesh instanceof BABYLON.InstancedMesh) {
  13718. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  13719. }
  13720. return {
  13721. uniqueId: mesh.uniqueId,
  13722. id: mesh.id,
  13723. name: mesh.name,
  13724. geometryId: geometryId,
  13725. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  13726. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  13727. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  13728. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  13729. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  13730. subMeshes: submeshes,
  13731. checkCollisions: mesh.checkCollisions
  13732. };
  13733. };
  13734. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  13735. return {
  13736. id: geometry.id,
  13737. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  13738. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  13739. indices: new Uint32Array(geometry.getIndices() || []),
  13740. };
  13741. };
  13742. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  13743. var CollisionCoordinatorLegacy = (function () {
  13744. function CollisionCoordinatorLegacy() {
  13745. this._scaledPosition = BABYLON.Vector3.Zero();
  13746. this._scaledVelocity = BABYLON.Vector3.Zero();
  13747. this._finalPosition = BABYLON.Vector3.Zero();
  13748. }
  13749. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  13750. position.divideToRef(collider.radius, this._scaledPosition);
  13751. velocity.divideToRef(collider.radius, this._scaledVelocity);
  13752. collider.collidedMesh = null;
  13753. collider.retry = 0;
  13754. collider.initialVelocity = this._scaledVelocity;
  13755. collider.initialPosition = this._scaledPosition;
  13756. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  13757. this._finalPosition.multiplyInPlace(collider.radius);
  13758. //run the callback
  13759. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  13760. };
  13761. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  13762. this._scene = scene;
  13763. };
  13764. CollisionCoordinatorLegacy.prototype.destroy = function () {
  13765. //Legacy need no destruction method.
  13766. };
  13767. //No update in legacy mode
  13768. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  13769. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  13770. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  13771. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  13772. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  13773. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  13774. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  13775. if (excludedMesh === void 0) { excludedMesh = null; }
  13776. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  13777. if (collider.retry >= maximumRetry) {
  13778. finalPosition.copyFrom(position);
  13779. return;
  13780. }
  13781. collider._initialize(position, velocity, closeDistance);
  13782. // Check all meshes
  13783. for (var index = 0; index < this._scene.meshes.length; index++) {
  13784. var mesh = this._scene.meshes[index];
  13785. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  13786. mesh._checkCollision(collider);
  13787. }
  13788. }
  13789. if (!collider.collisionFound) {
  13790. position.addToRef(velocity, finalPosition);
  13791. return;
  13792. }
  13793. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  13794. collider._getResponse(position, velocity);
  13795. }
  13796. if (velocity.length() <= closeDistance) {
  13797. finalPosition.copyFrom(position);
  13798. return;
  13799. }
  13800. collider.retry++;
  13801. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  13802. };
  13803. return CollisionCoordinatorLegacy;
  13804. }());
  13805. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  13806. })(BABYLON || (BABYLON = {}));
  13807. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  13808. var BABYLON;
  13809. (function (BABYLON) {
  13810. var Camera = (function (_super) {
  13811. __extends(Camera, _super);
  13812. function Camera(name, position, scene) {
  13813. var _this = _super.call(this, name, scene) || this;
  13814. _this.upVector = BABYLON.Vector3.Up();
  13815. _this.orthoLeft = null;
  13816. _this.orthoRight = null;
  13817. _this.orthoBottom = null;
  13818. _this.orthoTop = null;
  13819. _this.fov = 0.8;
  13820. _this.minZ = 1.0;
  13821. _this.maxZ = 10000.0;
  13822. _this.inertia = 0.9;
  13823. _this.mode = Camera.PERSPECTIVE_CAMERA;
  13824. _this.isIntermediate = false;
  13825. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  13826. _this.layerMask = 0x0FFFFFFF;
  13827. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  13828. // Camera rig members
  13829. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  13830. _this._rigCameras = new Array();
  13831. // Cache
  13832. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  13833. _this._projectionMatrix = new BABYLON.Matrix();
  13834. _this._doNotComputeProjectionMatrix = false;
  13835. _this._postProcesses = new Array();
  13836. _this._transformMatrix = BABYLON.Matrix.Zero();
  13837. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13838. _this._activeMeshes = new BABYLON.SmartArray(256);
  13839. _this._globalPosition = BABYLON.Vector3.Zero();
  13840. _this._refreshFrustumPlanes = true;
  13841. scene.addCamera(_this);
  13842. if (!scene.activeCamera) {
  13843. scene.activeCamera = _this;
  13844. }
  13845. _this.position = position;
  13846. return _this;
  13847. }
  13848. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13849. get: function () {
  13850. return Camera._PERSPECTIVE_CAMERA;
  13851. },
  13852. enumerable: true,
  13853. configurable: true
  13854. });
  13855. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13856. get: function () {
  13857. return Camera._ORTHOGRAPHIC_CAMERA;
  13858. },
  13859. enumerable: true,
  13860. configurable: true
  13861. });
  13862. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13863. get: function () {
  13864. return Camera._FOVMODE_VERTICAL_FIXED;
  13865. },
  13866. enumerable: true,
  13867. configurable: true
  13868. });
  13869. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13870. get: function () {
  13871. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13872. },
  13873. enumerable: true,
  13874. configurable: true
  13875. });
  13876. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13877. get: function () {
  13878. return Camera._RIG_MODE_NONE;
  13879. },
  13880. enumerable: true,
  13881. configurable: true
  13882. });
  13883. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13884. get: function () {
  13885. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13886. },
  13887. enumerable: true,
  13888. configurable: true
  13889. });
  13890. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13891. get: function () {
  13892. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13893. },
  13894. enumerable: true,
  13895. configurable: true
  13896. });
  13897. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13898. get: function () {
  13899. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13900. },
  13901. enumerable: true,
  13902. configurable: true
  13903. });
  13904. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13905. get: function () {
  13906. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13907. },
  13908. enumerable: true,
  13909. configurable: true
  13910. });
  13911. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13912. get: function () {
  13913. return Camera._RIG_MODE_VR;
  13914. },
  13915. enumerable: true,
  13916. configurable: true
  13917. });
  13918. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13919. get: function () {
  13920. return Camera._RIG_MODE_WEBVR;
  13921. },
  13922. enumerable: true,
  13923. configurable: true
  13924. });
  13925. Camera.prototype.getClassName = function () {
  13926. return "Camera";
  13927. };
  13928. /**
  13929. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13930. */
  13931. Camera.prototype.toString = function (fullDetails) {
  13932. var ret = "Name: " + this.name;
  13933. ret += ", type: " + this.getClassName();
  13934. if (this.animations) {
  13935. for (var i = 0; i < this.animations.length; i++) {
  13936. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13937. }
  13938. }
  13939. if (fullDetails) {
  13940. }
  13941. return ret;
  13942. };
  13943. Object.defineProperty(Camera.prototype, "globalPosition", {
  13944. get: function () {
  13945. return this._globalPosition;
  13946. },
  13947. enumerable: true,
  13948. configurable: true
  13949. });
  13950. Camera.prototype.getActiveMeshes = function () {
  13951. return this._activeMeshes;
  13952. };
  13953. Camera.prototype.isActiveMesh = function (mesh) {
  13954. return (this._activeMeshes.indexOf(mesh) !== -1);
  13955. };
  13956. //Cache
  13957. Camera.prototype._initCache = function () {
  13958. _super.prototype._initCache.call(this);
  13959. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13960. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13961. this._cache.mode = undefined;
  13962. this._cache.minZ = undefined;
  13963. this._cache.maxZ = undefined;
  13964. this._cache.fov = undefined;
  13965. this._cache.fovMode = undefined;
  13966. this._cache.aspectRatio = undefined;
  13967. this._cache.orthoLeft = undefined;
  13968. this._cache.orthoRight = undefined;
  13969. this._cache.orthoBottom = undefined;
  13970. this._cache.orthoTop = undefined;
  13971. this._cache.renderWidth = undefined;
  13972. this._cache.renderHeight = undefined;
  13973. };
  13974. Camera.prototype._updateCache = function (ignoreParentClass) {
  13975. if (!ignoreParentClass) {
  13976. _super.prototype._updateCache.call(this);
  13977. }
  13978. var engine = this.getEngine();
  13979. this._cache.position.copyFrom(this.position);
  13980. this._cache.upVector.copyFrom(this.upVector);
  13981. this._cache.mode = this.mode;
  13982. this._cache.minZ = this.minZ;
  13983. this._cache.maxZ = this.maxZ;
  13984. this._cache.fov = this.fov;
  13985. this._cache.fovMode = this.fovMode;
  13986. this._cache.aspectRatio = engine.getAspectRatio(this);
  13987. this._cache.orthoLeft = this.orthoLeft;
  13988. this._cache.orthoRight = this.orthoRight;
  13989. this._cache.orthoBottom = this.orthoBottom;
  13990. this._cache.orthoTop = this.orthoTop;
  13991. this._cache.renderWidth = engine.getRenderWidth();
  13992. this._cache.renderHeight = engine.getRenderHeight();
  13993. };
  13994. Camera.prototype._updateFromScene = function () {
  13995. this.updateCache();
  13996. this.update();
  13997. };
  13998. // Synchronized
  13999. Camera.prototype._isSynchronized = function () {
  14000. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14001. };
  14002. Camera.prototype._isSynchronizedViewMatrix = function () {
  14003. if (!_super.prototype._isSynchronized.call(this))
  14004. return false;
  14005. return this._cache.position.equals(this.position)
  14006. && this._cache.upVector.equals(this.upVector)
  14007. && this.isSynchronizedWithParent();
  14008. };
  14009. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14010. var check = this._cache.mode === this.mode
  14011. && this._cache.minZ === this.minZ
  14012. && this._cache.maxZ === this.maxZ;
  14013. if (!check) {
  14014. return false;
  14015. }
  14016. var engine = this.getEngine();
  14017. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14018. check = this._cache.fov === this.fov
  14019. && this._cache.fovMode === this.fovMode
  14020. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14021. }
  14022. else {
  14023. check = this._cache.orthoLeft === this.orthoLeft
  14024. && this._cache.orthoRight === this.orthoRight
  14025. && this._cache.orthoBottom === this.orthoBottom
  14026. && this._cache.orthoTop === this.orthoTop
  14027. && this._cache.renderWidth === engine.getRenderWidth()
  14028. && this._cache.renderHeight === engine.getRenderHeight();
  14029. }
  14030. return check;
  14031. };
  14032. // Controls
  14033. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14034. };
  14035. Camera.prototype.detachControl = function (element) {
  14036. };
  14037. Camera.prototype.update = function () {
  14038. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14039. this._updateRigCameras();
  14040. }
  14041. this._checkInputs();
  14042. };
  14043. Camera.prototype._checkInputs = function () {
  14044. };
  14045. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14046. // invalidate framebuffer
  14047. if (this._postProcesses.length > 0) {
  14048. this._postProcesses[0].markTextureDirty();
  14049. }
  14050. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14051. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14052. var cam = this._rigCameras[i];
  14053. var rigPostProcess = cam._rigPostProcess;
  14054. // for VR rig, there does not have to be a post process
  14055. if (rigPostProcess) {
  14056. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14057. if (isPass) {
  14058. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14059. cam.isIntermediate = this._postProcesses.length === 0;
  14060. }
  14061. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14062. rigPostProcess.markTextureDirty();
  14063. }
  14064. else {
  14065. cam._postProcesses = this._postProcesses.slice(0);
  14066. }
  14067. }
  14068. };
  14069. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  14070. if (insertAt === void 0) { insertAt = null; }
  14071. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  14072. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  14073. return 0;
  14074. }
  14075. if (insertAt == null || insertAt < 0) {
  14076. this._postProcesses.push(postProcess);
  14077. }
  14078. else {
  14079. this._postProcesses.splice(insertAt, 0, postProcess);
  14080. }
  14081. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14082. return this._postProcesses.indexOf(postProcess);
  14083. };
  14084. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  14085. if (atIndices === void 0) { atIndices = null; }
  14086. var result = [];
  14087. var i;
  14088. var index;
  14089. if (!atIndices) {
  14090. var idx = this._postProcesses.indexOf(postProcess);
  14091. if (idx !== -1) {
  14092. this._postProcesses.splice(idx, 1);
  14093. }
  14094. }
  14095. else {
  14096. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  14097. // iterate descending, so can just splice as we go
  14098. for (i = atIndices.length - 1; i >= 0; i--) {
  14099. if (this._postProcesses[atIndices[i]] !== postProcess) {
  14100. result.push(i);
  14101. continue;
  14102. }
  14103. index = atIndices[i];
  14104. this._postProcesses.splice(index, 1);
  14105. }
  14106. }
  14107. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  14108. return result;
  14109. };
  14110. Camera.prototype.getWorldMatrix = function () {
  14111. if (!this._worldMatrix) {
  14112. this._worldMatrix = BABYLON.Matrix.Identity();
  14113. }
  14114. var viewMatrix = this.getViewMatrix();
  14115. viewMatrix.invertToRef(this._worldMatrix);
  14116. return this._worldMatrix;
  14117. };
  14118. Camera.prototype._getViewMatrix = function () {
  14119. return BABYLON.Matrix.Identity();
  14120. };
  14121. Camera.prototype.getViewMatrix = function (force) {
  14122. this._computedViewMatrix = this._computeViewMatrix(force);
  14123. if (!force && this._isSynchronizedViewMatrix()) {
  14124. return this._computedViewMatrix;
  14125. }
  14126. this._refreshFrustumPlanes = true;
  14127. if (!this.parent || !this.parent.getWorldMatrix) {
  14128. this._globalPosition.copyFrom(this.position);
  14129. }
  14130. else {
  14131. if (!this._worldMatrix) {
  14132. this._worldMatrix = BABYLON.Matrix.Identity();
  14133. }
  14134. this._computedViewMatrix.invertToRef(this._worldMatrix);
  14135. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  14136. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  14137. this._computedViewMatrix.invert();
  14138. this._markSyncedWithParent();
  14139. }
  14140. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  14141. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  14142. }
  14143. this._currentRenderId = this.getScene().getRenderId();
  14144. return this._computedViewMatrix;
  14145. };
  14146. Camera.prototype._computeViewMatrix = function (force) {
  14147. if (!force && this._isSynchronizedViewMatrix()) {
  14148. return this._computedViewMatrix;
  14149. }
  14150. this._computedViewMatrix = this._getViewMatrix();
  14151. this._currentRenderId = this.getScene().getRenderId();
  14152. return this._computedViewMatrix;
  14153. };
  14154. Camera.prototype.freezeProjectionMatrix = function (projection) {
  14155. this._doNotComputeProjectionMatrix = true;
  14156. if (projection !== undefined) {
  14157. this._projectionMatrix = projection;
  14158. }
  14159. };
  14160. ;
  14161. Camera.prototype.unfreezeProjectionMatrix = function () {
  14162. this._doNotComputeProjectionMatrix = false;
  14163. };
  14164. ;
  14165. Camera.prototype.getProjectionMatrix = function (force) {
  14166. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  14167. return this._projectionMatrix;
  14168. }
  14169. this._refreshFrustumPlanes = true;
  14170. var engine = this.getEngine();
  14171. var scene = this.getScene();
  14172. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14173. if (this.minZ <= 0) {
  14174. this.minZ = 0.1;
  14175. }
  14176. if (scene.useRightHandedSystem) {
  14177. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14178. }
  14179. else {
  14180. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  14181. }
  14182. return this._projectionMatrix;
  14183. }
  14184. var halfWidth = engine.getRenderWidth() / 2.0;
  14185. var halfHeight = engine.getRenderHeight() / 2.0;
  14186. if (scene.useRightHandedSystem) {
  14187. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14188. }
  14189. else {
  14190. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  14191. }
  14192. return this._projectionMatrix;
  14193. };
  14194. Camera.prototype.getTranformationMatrix = function () {
  14195. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  14196. return this._transformMatrix;
  14197. };
  14198. Camera.prototype.updateFrustumPlanes = function () {
  14199. if (!this._refreshFrustumPlanes) {
  14200. return;
  14201. }
  14202. this.getTranformationMatrix();
  14203. if (!this._frustumPlanes) {
  14204. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  14205. }
  14206. else {
  14207. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  14208. }
  14209. this._refreshFrustumPlanes = false;
  14210. };
  14211. Camera.prototype.isInFrustum = function (target) {
  14212. this.updateFrustumPlanes();
  14213. return target.isInFrustum(this._frustumPlanes);
  14214. };
  14215. Camera.prototype.isCompletelyInFrustum = function (target) {
  14216. this.updateFrustumPlanes();
  14217. return target.isCompletelyInFrustum(this._frustumPlanes);
  14218. };
  14219. Camera.prototype.dispose = function () {
  14220. // Animations
  14221. this.getScene().stopAnimation(this);
  14222. // Remove from scene
  14223. this.getScene().removeCamera(this);
  14224. while (this._rigCameras.length > 0) {
  14225. this._rigCameras.pop().dispose();
  14226. }
  14227. // Postprocesses
  14228. var i = this._postProcesses.length;
  14229. while (--i >= 0) {
  14230. this._postProcesses[i].dispose(this);
  14231. }
  14232. _super.prototype.dispose.call(this);
  14233. };
  14234. // ---- Camera rigs section ----
  14235. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  14236. while (this._rigCameras.length > 0) {
  14237. this._rigCameras.pop().dispose();
  14238. }
  14239. this.cameraRigMode = mode;
  14240. this._cameraRigParams = {};
  14241. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  14242. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  14243. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  14244. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  14245. // create the rig cameras, unless none
  14246. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14247. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  14248. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  14249. }
  14250. switch (this.cameraRigMode) {
  14251. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  14252. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14253. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  14254. break;
  14255. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  14256. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  14257. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  14258. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14259. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  14260. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  14261. break;
  14262. case Camera.RIG_MODE_VR:
  14263. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  14264. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  14265. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14266. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14267. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  14268. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  14269. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  14270. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  14271. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14272. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14273. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  14274. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  14275. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  14276. if (metrics.compensateDistortion) {
  14277. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  14278. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  14279. }
  14280. break;
  14281. case Camera.RIG_MODE_WEBVR:
  14282. if (rigParams.vrDisplay) {
  14283. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  14284. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  14285. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  14286. this._rigCameras[0].setCameraRigParameter("left", true);
  14287. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  14288. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  14289. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14290. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14291. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  14292. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  14293. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  14294. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  14295. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  14296. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  14297. }
  14298. break;
  14299. }
  14300. this._cascadePostProcessesToRigCams();
  14301. this.
  14302. update();
  14303. };
  14304. Camera.prototype._getVRProjectionMatrix = function () {
  14305. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  14306. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  14307. return this._projectionMatrix;
  14308. };
  14309. Camera.prototype._getWebVRProjectionMatrix = function () {
  14310. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  14311. //babylon compatible matrix
  14312. [8, 9, 10, 11].forEach(function (num) {
  14313. projectionArray[num] *= -1;
  14314. });
  14315. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  14316. return this._projectionMatrix;
  14317. };
  14318. //Can be used, but we'll use the free camera's view matrix calculation
  14319. Camera.prototype._getWebVRViewMatrix = function () {
  14320. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  14321. //babylon compatible matrix
  14322. [8, 9, 10, 11].forEach(function (num) {
  14323. projectionArray[num] *= -1;
  14324. });
  14325. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  14326. return this._webvrViewMatrix;
  14327. };
  14328. Camera.prototype.setCameraRigParameter = function (name, value) {
  14329. if (!this._cameraRigParams) {
  14330. this._cameraRigParams = {};
  14331. }
  14332. this._cameraRigParams[name] = value;
  14333. //provisionnally:
  14334. if (name === "interaxialDistance") {
  14335. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  14336. }
  14337. };
  14338. /**
  14339. * needs to be overridden by children so sub has required properties to be copied
  14340. */
  14341. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  14342. return null;
  14343. };
  14344. /**
  14345. * May need to be overridden by children
  14346. */
  14347. Camera.prototype._updateRigCameras = function () {
  14348. for (var i = 0; i < this._rigCameras.length; i++) {
  14349. this._rigCameras[i].minZ = this.minZ;
  14350. this._rigCameras[i].maxZ = this.maxZ;
  14351. this._rigCameras[i].fov = this.fov;
  14352. }
  14353. // only update viewport when ANAGLYPH
  14354. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  14355. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  14356. }
  14357. };
  14358. Camera.prototype._setupInputs = function () {
  14359. };
  14360. Camera.prototype.serialize = function () {
  14361. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14362. // Type
  14363. serializationObject.type = this.getClassName();
  14364. // Parent
  14365. if (this.parent) {
  14366. serializationObject.parentId = this.parent.id;
  14367. }
  14368. if (this.inputs) {
  14369. this.inputs.serialize(serializationObject);
  14370. }
  14371. // Animations
  14372. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14373. serializationObject.ranges = this.serializeAnimationRanges();
  14374. return serializationObject;
  14375. };
  14376. Camera.prototype.clone = function (name) {
  14377. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  14378. };
  14379. Camera.prototype.getDirection = function (localAxis) {
  14380. var result = BABYLON.Vector3.Zero();
  14381. this.getDirectionToRef(localAxis, result);
  14382. return result;
  14383. };
  14384. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  14385. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  14386. };
  14387. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  14388. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  14389. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  14390. switch (type) {
  14391. case "ArcRotateCamera":
  14392. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  14393. case "DeviceOrientationCamera":
  14394. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  14395. case "FollowCamera":
  14396. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  14397. case "ArcFollowCamera":
  14398. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  14399. case "GamepadCamera":
  14400. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14401. case "TouchCamera":
  14402. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  14403. case "VirtualJoysticksCamera":
  14404. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  14405. case "HolographicCamera":
  14406. return function () { return new BABYLON.HolographicCamera(name, scene); };
  14407. case "WebVRFreeCamera":
  14408. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14409. case "VRDeviceOrientationFreeCamera":
  14410. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  14411. case "VRDeviceOrientationGamepadCamera":
  14412. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  14413. case "AnaglyphArcRotateCamera":
  14414. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14415. case "AnaglyphFreeCamera":
  14416. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14417. case "AnaglyphGamepadCamera":
  14418. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14419. case "AnaglyphUniversalCamera":
  14420. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  14421. case "StereoscopicArcRotateCamera":
  14422. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14423. case "StereoscopicFreeCamera":
  14424. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14425. case "StereoscopicGamepadCamera":
  14426. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14427. case "StereoscopicUniversalCamera":
  14428. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  14429. case "FreeCamera":
  14430. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14431. default:
  14432. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  14433. }
  14434. };
  14435. Camera.Parse = function (parsedCamera, scene) {
  14436. var type = parsedCamera.type;
  14437. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  14438. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  14439. // Parent
  14440. if (parsedCamera.parentId) {
  14441. camera._waitingParentId = parsedCamera.parentId;
  14442. }
  14443. //If camera has an input manager, let it parse inputs settings
  14444. if (camera.inputs) {
  14445. camera.inputs.parse(parsedCamera);
  14446. camera._setupInputs();
  14447. }
  14448. // Target
  14449. if (parsedCamera.target) {
  14450. if (camera.setTarget) {
  14451. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  14452. }
  14453. }
  14454. // Apply 3d rig, when found
  14455. if (parsedCamera.cameraRigMode) {
  14456. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  14457. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  14458. }
  14459. // Animations
  14460. if (parsedCamera.animations) {
  14461. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  14462. var parsedAnimation = parsedCamera.animations[animationIndex];
  14463. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14464. }
  14465. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  14466. }
  14467. if (parsedCamera.autoAnimate) {
  14468. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  14469. }
  14470. return camera;
  14471. };
  14472. return Camera;
  14473. }(BABYLON.Node));
  14474. // Statics
  14475. Camera._PERSPECTIVE_CAMERA = 0;
  14476. Camera._ORTHOGRAPHIC_CAMERA = 1;
  14477. Camera._FOVMODE_VERTICAL_FIXED = 0;
  14478. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  14479. Camera._RIG_MODE_NONE = 0;
  14480. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  14481. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  14482. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  14483. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  14484. Camera._RIG_MODE_VR = 20;
  14485. Camera._RIG_MODE_WEBVR = 21;
  14486. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  14487. __decorate([
  14488. BABYLON.serializeAsVector3()
  14489. ], Camera.prototype, "position", void 0);
  14490. __decorate([
  14491. BABYLON.serializeAsVector3()
  14492. ], Camera.prototype, "upVector", void 0);
  14493. __decorate([
  14494. BABYLON.serialize()
  14495. ], Camera.prototype, "orthoLeft", void 0);
  14496. __decorate([
  14497. BABYLON.serialize()
  14498. ], Camera.prototype, "orthoRight", void 0);
  14499. __decorate([
  14500. BABYLON.serialize()
  14501. ], Camera.prototype, "orthoBottom", void 0);
  14502. __decorate([
  14503. BABYLON.serialize()
  14504. ], Camera.prototype, "orthoTop", void 0);
  14505. __decorate([
  14506. BABYLON.serialize()
  14507. ], Camera.prototype, "fov", void 0);
  14508. __decorate([
  14509. BABYLON.serialize()
  14510. ], Camera.prototype, "minZ", void 0);
  14511. __decorate([
  14512. BABYLON.serialize()
  14513. ], Camera.prototype, "maxZ", void 0);
  14514. __decorate([
  14515. BABYLON.serialize()
  14516. ], Camera.prototype, "inertia", void 0);
  14517. __decorate([
  14518. BABYLON.serialize()
  14519. ], Camera.prototype, "mode", void 0);
  14520. __decorate([
  14521. BABYLON.serialize()
  14522. ], Camera.prototype, "layerMask", void 0);
  14523. __decorate([
  14524. BABYLON.serialize()
  14525. ], Camera.prototype, "fovMode", void 0);
  14526. __decorate([
  14527. BABYLON.serialize()
  14528. ], Camera.prototype, "cameraRigMode", void 0);
  14529. __decorate([
  14530. BABYLON.serialize()
  14531. ], Camera.prototype, "interaxialDistance", void 0);
  14532. __decorate([
  14533. BABYLON.serialize()
  14534. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  14535. BABYLON.Camera = Camera;
  14536. })(BABYLON || (BABYLON = {}));
  14537. //# sourceMappingURL=babylon.camera.js.map
  14538. var BABYLON;
  14539. (function (BABYLON) {
  14540. BABYLON.CameraInputTypes = {};
  14541. var CameraInputsManager = (function () {
  14542. function CameraInputsManager(camera) {
  14543. this.attached = {};
  14544. this.camera = camera;
  14545. this.checkInputs = function () { };
  14546. }
  14547. CameraInputsManager.prototype.add = function (input) {
  14548. var type = input.getSimpleName();
  14549. if (this.attached[type]) {
  14550. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  14551. return;
  14552. }
  14553. this.attached[type] = input;
  14554. input.camera = this.camera;
  14555. //for checkInputs, we are dynamically creating a function
  14556. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  14557. if (input.checkInputs) {
  14558. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  14559. }
  14560. if (this.attachedElement) {
  14561. input.attachControl(this.attachedElement);
  14562. }
  14563. };
  14564. CameraInputsManager.prototype.remove = function (inputToRemove) {
  14565. for (var cam in this.attached) {
  14566. var input = this.attached[cam];
  14567. if (input === inputToRemove) {
  14568. input.detachControl(this.attachedElement);
  14569. delete this.attached[cam];
  14570. this.rebuildInputCheck();
  14571. }
  14572. }
  14573. };
  14574. CameraInputsManager.prototype.removeByType = function (inputType) {
  14575. for (var cam in this.attached) {
  14576. var input = this.attached[cam];
  14577. if (input.getTypeName() === inputType) {
  14578. input.detachControl(this.attachedElement);
  14579. delete this.attached[cam];
  14580. this.rebuildInputCheck();
  14581. }
  14582. }
  14583. };
  14584. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  14585. var current = this.checkInputs;
  14586. return function () {
  14587. current();
  14588. fn();
  14589. };
  14590. };
  14591. CameraInputsManager.prototype.attachInput = function (input) {
  14592. input.attachControl(this.attachedElement, this.noPreventDefault);
  14593. };
  14594. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  14595. if (this.attachedElement) {
  14596. return;
  14597. }
  14598. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  14599. this.attachedElement = element;
  14600. this.noPreventDefault = noPreventDefault;
  14601. for (var cam in this.attached) {
  14602. var input = this.attached[cam];
  14603. this.attached[cam].attachControl(element, noPreventDefault);
  14604. }
  14605. };
  14606. CameraInputsManager.prototype.detachElement = function (element) {
  14607. if (this.attachedElement !== element) {
  14608. return;
  14609. }
  14610. for (var cam in this.attached) {
  14611. var input = this.attached[cam];
  14612. this.attached[cam].detachControl(element);
  14613. }
  14614. this.attachedElement = null;
  14615. };
  14616. CameraInputsManager.prototype.rebuildInputCheck = function () {
  14617. this.checkInputs = function () { };
  14618. for (var cam in this.attached) {
  14619. var input = this.attached[cam];
  14620. if (input.checkInputs) {
  14621. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  14622. }
  14623. }
  14624. };
  14625. CameraInputsManager.prototype.clear = function () {
  14626. if (this.attachedElement) {
  14627. this.detachElement(this.attachedElement);
  14628. }
  14629. this.attached = {};
  14630. this.attachedElement = null;
  14631. this.checkInputs = function () { };
  14632. };
  14633. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  14634. var inputs = {};
  14635. for (var cam in this.attached) {
  14636. var input = this.attached[cam];
  14637. var res = BABYLON.SerializationHelper.Serialize(input);
  14638. inputs[input.getTypeName()] = res;
  14639. }
  14640. serializedCamera.inputsmgr = inputs;
  14641. };
  14642. CameraInputsManager.prototype.parse = function (parsedCamera) {
  14643. var parsedInputs = parsedCamera.inputsmgr;
  14644. if (parsedInputs) {
  14645. this.clear();
  14646. for (var n in parsedInputs) {
  14647. var construct = BABYLON.CameraInputTypes[n];
  14648. if (construct) {
  14649. var parsedinput = parsedInputs[n];
  14650. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  14651. this.add(input);
  14652. }
  14653. }
  14654. }
  14655. else {
  14656. //2016-03-08 this part is for managing backward compatibility
  14657. for (var n in this.attached) {
  14658. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  14659. if (construct) {
  14660. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  14661. this.remove(this.attached[n]);
  14662. this.add(input);
  14663. }
  14664. }
  14665. }
  14666. };
  14667. return CameraInputsManager;
  14668. }());
  14669. BABYLON.CameraInputsManager = CameraInputsManager;
  14670. })(BABYLON || (BABYLON = {}));
  14671. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  14672. var BABYLON;
  14673. (function (BABYLON) {
  14674. var FreeCameraMouseInput = (function () {
  14675. function FreeCameraMouseInput(touchEnabled) {
  14676. if (touchEnabled === void 0) { touchEnabled = true; }
  14677. this.touchEnabled = touchEnabled;
  14678. this.buttons = [0, 1, 2];
  14679. this.angularSensibility = 2000.0;
  14680. }
  14681. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  14682. var _this = this;
  14683. var engine = this.camera.getEngine();
  14684. if (!this._pointerInput) {
  14685. this._pointerInput = function (p, s) {
  14686. var evt = p.event;
  14687. if (!_this.touchEnabled && evt.pointerType === "touch") {
  14688. return;
  14689. }
  14690. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14691. return;
  14692. }
  14693. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14694. try {
  14695. evt.srcElement.setPointerCapture(evt.pointerId);
  14696. }
  14697. catch (e) {
  14698. }
  14699. _this.previousPosition = {
  14700. x: evt.clientX,
  14701. y: evt.clientY
  14702. };
  14703. if (!noPreventDefault) {
  14704. evt.preventDefault();
  14705. element.focus();
  14706. }
  14707. }
  14708. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14709. try {
  14710. evt.srcElement.releasePointerCapture(evt.pointerId);
  14711. }
  14712. catch (e) {
  14713. }
  14714. _this.previousPosition = null;
  14715. if (!noPreventDefault) {
  14716. evt.preventDefault();
  14717. }
  14718. }
  14719. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14720. if (!_this.previousPosition || engine.isPointerLock) {
  14721. return;
  14722. }
  14723. var offsetX = evt.clientX - _this.previousPosition.x;
  14724. var offsetY = evt.clientY - _this.previousPosition.y;
  14725. if (_this.camera.getScene().useRightHandedSystem) {
  14726. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  14727. }
  14728. else {
  14729. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  14730. }
  14731. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  14732. _this.previousPosition = {
  14733. x: evt.clientX,
  14734. y: evt.clientY
  14735. };
  14736. if (!noPreventDefault) {
  14737. evt.preventDefault();
  14738. }
  14739. }
  14740. };
  14741. }
  14742. this._onMouseMove = function (evt) {
  14743. if (!engine.isPointerLock) {
  14744. return;
  14745. }
  14746. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14747. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14748. if (_this.camera.getScene().useRightHandedSystem) {
  14749. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  14750. }
  14751. else {
  14752. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  14753. }
  14754. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  14755. _this.previousPosition = null;
  14756. if (!noPreventDefault) {
  14757. evt.preventDefault();
  14758. }
  14759. };
  14760. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14761. element.addEventListener("mousemove", this._onMouseMove, false);
  14762. };
  14763. FreeCameraMouseInput.prototype.detachControl = function (element) {
  14764. if (this._observer && element) {
  14765. this.camera.getScene().onPointerObservable.remove(this._observer);
  14766. element.removeEventListener("mousemove", this._onMouseMove);
  14767. this._observer = null;
  14768. this._onMouseMove = null;
  14769. this.previousPosition = null;
  14770. }
  14771. };
  14772. FreeCameraMouseInput.prototype.getTypeName = function () {
  14773. return "FreeCameraMouseInput";
  14774. };
  14775. FreeCameraMouseInput.prototype.getSimpleName = function () {
  14776. return "mouse";
  14777. };
  14778. return FreeCameraMouseInput;
  14779. }());
  14780. __decorate([
  14781. BABYLON.serialize()
  14782. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  14783. __decorate([
  14784. BABYLON.serialize()
  14785. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  14786. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  14787. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  14788. })(BABYLON || (BABYLON = {}));
  14789. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  14790. var BABYLON;
  14791. (function (BABYLON) {
  14792. var FreeCameraKeyboardMoveInput = (function () {
  14793. function FreeCameraKeyboardMoveInput() {
  14794. this._keys = [];
  14795. this.keysUp = [38];
  14796. this.keysDown = [40];
  14797. this.keysLeft = [37];
  14798. this.keysRight = [39];
  14799. }
  14800. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14801. var _this = this;
  14802. if (!this._onKeyDown) {
  14803. element.tabIndex = 1;
  14804. this._onKeyDown = function (evt) {
  14805. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14806. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14807. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14808. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14809. var index = _this._keys.indexOf(evt.keyCode);
  14810. if (index === -1) {
  14811. _this._keys.push(evt.keyCode);
  14812. }
  14813. if (!noPreventDefault) {
  14814. evt.preventDefault();
  14815. }
  14816. }
  14817. };
  14818. this._onKeyUp = function (evt) {
  14819. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14820. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14821. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14822. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14823. var index = _this._keys.indexOf(evt.keyCode);
  14824. if (index >= 0) {
  14825. _this._keys.splice(index, 1);
  14826. }
  14827. if (!noPreventDefault) {
  14828. evt.preventDefault();
  14829. }
  14830. }
  14831. };
  14832. element.addEventListener("keydown", this._onKeyDown, false);
  14833. element.addEventListener("keyup", this._onKeyUp, false);
  14834. BABYLON.Tools.RegisterTopRootEvents([
  14835. { name: "blur", handler: this._onLostFocus }
  14836. ]);
  14837. }
  14838. };
  14839. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14840. if (this._onKeyDown) {
  14841. element.removeEventListener("keydown", this._onKeyDown);
  14842. element.removeEventListener("keyup", this._onKeyUp);
  14843. BABYLON.Tools.UnregisterTopRootEvents([
  14844. { name: "blur", handler: this._onLostFocus }
  14845. ]);
  14846. this._keys = [];
  14847. this._onKeyDown = null;
  14848. this._onKeyUp = null;
  14849. }
  14850. };
  14851. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14852. if (this._onKeyDown) {
  14853. var camera = this.camera;
  14854. // Keyboard
  14855. for (var index = 0; index < this._keys.length; index++) {
  14856. var keyCode = this._keys[index];
  14857. var speed = camera._computeLocalCameraSpeed();
  14858. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14859. camera._localDirection.copyFromFloats(-speed, 0, 0);
  14860. }
  14861. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14862. camera._localDirection.copyFromFloats(0, 0, speed);
  14863. }
  14864. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14865. camera._localDirection.copyFromFloats(speed, 0, 0);
  14866. }
  14867. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14868. camera._localDirection.copyFromFloats(0, 0, -speed);
  14869. }
  14870. if (camera.getScene().useRightHandedSystem) {
  14871. camera._localDirection.z *= -1;
  14872. }
  14873. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  14874. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  14875. camera.cameraDirection.addInPlace(camera._transformedDirection);
  14876. }
  14877. }
  14878. };
  14879. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14880. return "FreeCameraKeyboardMoveInput";
  14881. };
  14882. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  14883. this._keys = [];
  14884. };
  14885. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14886. return "keyboard";
  14887. };
  14888. return FreeCameraKeyboardMoveInput;
  14889. }());
  14890. __decorate([
  14891. BABYLON.serialize()
  14892. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14893. __decorate([
  14894. BABYLON.serialize()
  14895. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14896. __decorate([
  14897. BABYLON.serialize()
  14898. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14899. __decorate([
  14900. BABYLON.serialize()
  14901. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14902. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  14903. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  14904. })(BABYLON || (BABYLON = {}));
  14905. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  14906. var BABYLON;
  14907. (function (BABYLON) {
  14908. var FreeCameraTouchInput = (function () {
  14909. function FreeCameraTouchInput() {
  14910. this._offsetX = null;
  14911. this._offsetY = null;
  14912. this._pointerCount = 0;
  14913. this._pointerPressed = [];
  14914. this.touchAngularSensibility = 200000.0;
  14915. this.touchMoveSensibility = 250.0;
  14916. }
  14917. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  14918. var _this = this;
  14919. var previousPosition;
  14920. if (this._pointerInput === undefined) {
  14921. this._onLostFocus = function (evt) {
  14922. _this._offsetX = null;
  14923. _this._offsetY = null;
  14924. };
  14925. this._pointerInput = function (p, s) {
  14926. var evt = p.event;
  14927. if (evt.pointerType === "mouse") {
  14928. return;
  14929. }
  14930. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14931. if (!noPreventDefault) {
  14932. evt.preventDefault();
  14933. }
  14934. _this._pointerPressed.push(evt.pointerId);
  14935. if (_this._pointerPressed.length !== 1) {
  14936. return;
  14937. }
  14938. previousPosition = {
  14939. x: evt.clientX,
  14940. y: evt.clientY
  14941. };
  14942. }
  14943. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14944. if (!noPreventDefault) {
  14945. evt.preventDefault();
  14946. }
  14947. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14948. if (index === -1) {
  14949. return;
  14950. }
  14951. _this._pointerPressed.splice(index, 1);
  14952. if (index != 0) {
  14953. return;
  14954. }
  14955. previousPosition = null;
  14956. _this._offsetX = null;
  14957. _this._offsetY = null;
  14958. }
  14959. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14960. if (!noPreventDefault) {
  14961. evt.preventDefault();
  14962. }
  14963. if (!previousPosition) {
  14964. return;
  14965. }
  14966. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14967. if (index != 0) {
  14968. return;
  14969. }
  14970. _this._offsetX = evt.clientX - previousPosition.x;
  14971. _this._offsetY = -(evt.clientY - previousPosition.y);
  14972. }
  14973. };
  14974. }
  14975. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14976. element.addEventListener("blur", this._onLostFocus);
  14977. };
  14978. FreeCameraTouchInput.prototype.detachControl = function (element) {
  14979. if (this._pointerInput && element) {
  14980. this.camera.getScene().onPointerObservable.remove(this._observer);
  14981. this._observer = null;
  14982. element.removeEventListener("blur", this._onLostFocus);
  14983. this._onLostFocus = null;
  14984. this._pointerPressed = [];
  14985. this._offsetX = null;
  14986. this._offsetY = null;
  14987. this._pointerCount = 0;
  14988. }
  14989. };
  14990. FreeCameraTouchInput.prototype.checkInputs = function () {
  14991. if (this._offsetX) {
  14992. var camera = this.camera;
  14993. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  14994. if (this._pointerPressed.length > 1) {
  14995. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  14996. }
  14997. else {
  14998. var speed = camera._computeLocalCameraSpeed();
  14999. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  15000. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  15001. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  15002. }
  15003. }
  15004. };
  15005. FreeCameraTouchInput.prototype.getTypeName = function () {
  15006. return "FreeCameraTouchInput";
  15007. };
  15008. FreeCameraTouchInput.prototype.getSimpleName = function () {
  15009. return "touch";
  15010. };
  15011. return FreeCameraTouchInput;
  15012. }());
  15013. __decorate([
  15014. BABYLON.serialize()
  15015. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  15016. __decorate([
  15017. BABYLON.serialize()
  15018. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  15019. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  15020. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  15021. })(BABYLON || (BABYLON = {}));
  15022. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  15023. var BABYLON;
  15024. (function (BABYLON) {
  15025. var FreeCameraDeviceOrientationInput = (function () {
  15026. function FreeCameraDeviceOrientationInput() {
  15027. var _this = this;
  15028. this._screenOrientationAngle = 0;
  15029. this._screenQuaternion = new BABYLON.Quaternion();
  15030. this._alpha = 0;
  15031. this._beta = 0;
  15032. this._gamma = 0;
  15033. this._orientationChanged = function () {
  15034. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  15035. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  15036. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  15037. };
  15038. this._deviceOrientation = function (evt) {
  15039. _this._alpha = evt.alpha;
  15040. _this._beta = evt.beta;
  15041. _this._gamma = evt.gamma;
  15042. };
  15043. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  15044. this._orientationChanged();
  15045. }
  15046. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  15047. get: function () {
  15048. return this._camera;
  15049. },
  15050. set: function (camera) {
  15051. this._camera = camera;
  15052. if (!this._camera.rotationQuaternion)
  15053. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  15054. },
  15055. enumerable: true,
  15056. configurable: true
  15057. });
  15058. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  15059. window.addEventListener("orientationchange", this._orientationChanged);
  15060. window.addEventListener("deviceorientation", this._deviceOrientation);
  15061. //In certain cases, the attach control is called AFTER orientation was changed,
  15062. //So this is needed.
  15063. this._orientationChanged();
  15064. };
  15065. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  15066. window.removeEventListener("orientationchange", this._orientationChanged);
  15067. window.removeEventListener("deviceorientation", this._deviceOrientation);
  15068. };
  15069. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  15070. //if no device orientation provided, don't update the rotation.
  15071. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  15072. if (!this._alpha)
  15073. return;
  15074. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  15075. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  15076. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  15077. //Mirror on XY Plane
  15078. this._camera.rotationQuaternion.z *= -1;
  15079. this._camera.rotationQuaternion.w *= -1;
  15080. };
  15081. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  15082. return "FreeCameraDeviceOrientationInput";
  15083. };
  15084. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  15085. return "deviceOrientation";
  15086. };
  15087. return FreeCameraDeviceOrientationInput;
  15088. }());
  15089. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  15090. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  15091. })(BABYLON || (BABYLON = {}));
  15092. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  15093. var BABYLON;
  15094. (function (BABYLON) {
  15095. var FreeCameraGamepadInput = (function () {
  15096. function FreeCameraGamepadInput() {
  15097. this.gamepadAngularSensibility = 200;
  15098. this.gamepadMoveSensibility = 40;
  15099. }
  15100. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  15101. var _this = this;
  15102. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  15103. };
  15104. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  15105. if (this._gamepads) {
  15106. this._gamepads.dispose();
  15107. }
  15108. this.gamepad = null;
  15109. };
  15110. FreeCameraGamepadInput.prototype.checkInputs = function () {
  15111. if (this.gamepad) {
  15112. var camera = this.camera;
  15113. var LSValues = this.gamepad.leftStick;
  15114. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  15115. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  15116. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  15117. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  15118. var RSValues = this.gamepad.rightStick;
  15119. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  15120. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  15121. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  15122. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  15123. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  15124. var speed = camera._computeLocalCameraSpeed() * 50.0;
  15125. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  15126. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  15127. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  15128. }
  15129. };
  15130. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  15131. // Only the first gamepad can control the camera
  15132. if (gamepad.index === 0) {
  15133. this.gamepad = gamepad;
  15134. }
  15135. };
  15136. FreeCameraGamepadInput.prototype.getTypeName = function () {
  15137. return "FreeCameraGamepadInput";
  15138. };
  15139. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  15140. return "gamepad";
  15141. };
  15142. return FreeCameraGamepadInput;
  15143. }());
  15144. __decorate([
  15145. BABYLON.serialize()
  15146. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  15147. __decorate([
  15148. BABYLON.serialize()
  15149. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  15150. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  15151. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  15152. })(BABYLON || (BABYLON = {}));
  15153. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  15154. var BABYLON;
  15155. (function (BABYLON) {
  15156. var ArcRotateCameraKeyboardMoveInput = (function () {
  15157. function ArcRotateCameraKeyboardMoveInput() {
  15158. this._keys = [];
  15159. this.keysUp = [38];
  15160. this.keysDown = [40];
  15161. this.keysLeft = [37];
  15162. this.keysRight = [39];
  15163. }
  15164. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  15165. var _this = this;
  15166. element.tabIndex = 1;
  15167. this._onKeyDown = function (evt) {
  15168. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  15169. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  15170. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  15171. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  15172. var index = _this._keys.indexOf(evt.keyCode);
  15173. if (index === -1) {
  15174. _this._keys.push(evt.keyCode);
  15175. }
  15176. if (evt.preventDefault) {
  15177. if (!noPreventDefault) {
  15178. evt.preventDefault();
  15179. }
  15180. }
  15181. }
  15182. };
  15183. this._onKeyUp = function (evt) {
  15184. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  15185. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  15186. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  15187. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  15188. var index = _this._keys.indexOf(evt.keyCode);
  15189. if (index >= 0) {
  15190. _this._keys.splice(index, 1);
  15191. }
  15192. if (evt.preventDefault) {
  15193. if (!noPreventDefault) {
  15194. evt.preventDefault();
  15195. }
  15196. }
  15197. }
  15198. };
  15199. this._onLostFocus = function () {
  15200. _this._keys = [];
  15201. };
  15202. element.addEventListener("keydown", this._onKeyDown, false);
  15203. element.addEventListener("keyup", this._onKeyUp, false);
  15204. BABYLON.Tools.RegisterTopRootEvents([
  15205. { name: "blur", handler: this._onLostFocus }
  15206. ]);
  15207. };
  15208. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  15209. if (element) {
  15210. element.removeEventListener("keydown", this._onKeyDown);
  15211. element.removeEventListener("keyup", this._onKeyUp);
  15212. }
  15213. BABYLON.Tools.UnregisterTopRootEvents([
  15214. { name: "blur", handler: this._onLostFocus }
  15215. ]);
  15216. this._keys = [];
  15217. this._onKeyDown = null;
  15218. this._onKeyUp = null;
  15219. this._onLostFocus = null;
  15220. };
  15221. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  15222. if (this._onKeyDown) {
  15223. var camera = this.camera;
  15224. for (var index = 0; index < this._keys.length; index++) {
  15225. var keyCode = this._keys[index];
  15226. if (this.keysLeft.indexOf(keyCode) !== -1) {
  15227. camera.inertialAlphaOffset -= 0.01;
  15228. }
  15229. else if (this.keysUp.indexOf(keyCode) !== -1) {
  15230. camera.inertialBetaOffset -= 0.01;
  15231. }
  15232. else if (this.keysRight.indexOf(keyCode) !== -1) {
  15233. camera.inertialAlphaOffset += 0.01;
  15234. }
  15235. else if (this.keysDown.indexOf(keyCode) !== -1) {
  15236. camera.inertialBetaOffset += 0.01;
  15237. }
  15238. }
  15239. }
  15240. };
  15241. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  15242. return "ArcRotateCameraKeyboardMoveInput";
  15243. };
  15244. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  15245. return "keyboard";
  15246. };
  15247. return ArcRotateCameraKeyboardMoveInput;
  15248. }());
  15249. __decorate([
  15250. BABYLON.serialize()
  15251. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  15252. __decorate([
  15253. BABYLON.serialize()
  15254. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  15255. __decorate([
  15256. BABYLON.serialize()
  15257. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  15258. __decorate([
  15259. BABYLON.serialize()
  15260. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  15261. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  15262. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  15263. })(BABYLON || (BABYLON = {}));
  15264. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  15265. var BABYLON;
  15266. (function (BABYLON) {
  15267. var ArcRotateCameraMouseWheelInput = (function () {
  15268. function ArcRotateCameraMouseWheelInput() {
  15269. this.wheelPrecision = 3.0;
  15270. }
  15271. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  15272. var _this = this;
  15273. this._wheel = function (p, s) {
  15274. //sanity check - this should be a PointerWheel event.
  15275. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  15276. return;
  15277. var event = p.event;
  15278. var delta = 0;
  15279. if (event.wheelDelta) {
  15280. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  15281. }
  15282. else if (event.detail) {
  15283. delta = -event.detail / _this.wheelPrecision;
  15284. }
  15285. if (delta)
  15286. _this.camera.inertialRadiusOffset += delta;
  15287. if (event.preventDefault) {
  15288. if (!noPreventDefault) {
  15289. event.preventDefault();
  15290. }
  15291. }
  15292. };
  15293. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  15294. };
  15295. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  15296. if (this._observer && element) {
  15297. this.camera.getScene().onPointerObservable.remove(this._observer);
  15298. this._observer = null;
  15299. this._wheel = null;
  15300. }
  15301. };
  15302. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  15303. return "ArcRotateCameraMouseWheelInput";
  15304. };
  15305. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  15306. return "mousewheel";
  15307. };
  15308. return ArcRotateCameraMouseWheelInput;
  15309. }());
  15310. __decorate([
  15311. BABYLON.serialize()
  15312. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  15313. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  15314. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  15315. })(BABYLON || (BABYLON = {}));
  15316. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  15317. var BABYLON;
  15318. (function (BABYLON) {
  15319. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  15320. var ArcRotateCameraPointersInput = (function () {
  15321. function ArcRotateCameraPointersInput() {
  15322. this.buttons = [0, 1, 2];
  15323. this.angularSensibilityX = 1000.0;
  15324. this.angularSensibilityY = 1000.0;
  15325. this.pinchPrecision = 6.0;
  15326. this.panningSensibility = 50.0;
  15327. this._isPanClick = false;
  15328. this.pinchInwards = true;
  15329. }
  15330. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  15331. var _this = this;
  15332. var engine = this.camera.getEngine();
  15333. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  15334. var pointA, pointB;
  15335. var previousPinchDistance = 0;
  15336. this._pointerInput = function (p, s) {
  15337. var evt = p.event;
  15338. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  15339. return;
  15340. }
  15341. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  15342. try {
  15343. evt.srcElement.setPointerCapture(evt.pointerId);
  15344. }
  15345. catch (e) {
  15346. }
  15347. // Manage panning with pan button click
  15348. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  15349. // manage pointers
  15350. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  15351. if (pointA === undefined) {
  15352. pointA = cacheSoloPointer;
  15353. }
  15354. else if (pointB === undefined) {
  15355. pointB = cacheSoloPointer;
  15356. }
  15357. if (!noPreventDefault) {
  15358. evt.preventDefault();
  15359. element.focus();
  15360. }
  15361. }
  15362. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  15363. try {
  15364. evt.srcElement.releasePointerCapture(evt.pointerId);
  15365. }
  15366. catch (e) {
  15367. }
  15368. cacheSoloPointer = null;
  15369. previousPinchDistance = 0;
  15370. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  15371. //but emptying completly pointers collection is required to fix a bug on iPhone :
  15372. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  15373. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  15374. pointA = pointB = undefined;
  15375. if (!noPreventDefault) {
  15376. evt.preventDefault();
  15377. }
  15378. }
  15379. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  15380. if (!noPreventDefault) {
  15381. evt.preventDefault();
  15382. }
  15383. // One button down
  15384. if (pointA && pointB === undefined) {
  15385. if (_this.panningSensibility !== 0 &&
  15386. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  15387. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  15388. _this.camera
  15389. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  15390. _this.camera
  15391. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  15392. }
  15393. else {
  15394. var offsetX = evt.clientX - cacheSoloPointer.x;
  15395. var offsetY = evt.clientY - cacheSoloPointer.y;
  15396. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  15397. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  15398. }
  15399. cacheSoloPointer.x = evt.clientX;
  15400. cacheSoloPointer.y = evt.clientY;
  15401. }
  15402. else if (pointA && pointB) {
  15403. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  15404. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  15405. ed.x = evt.clientX;
  15406. ed.y = evt.clientY;
  15407. var direction = _this.pinchInwards ? 1 : -1;
  15408. var distX = pointA.x - pointB.x;
  15409. var distY = pointA.y - pointB.y;
  15410. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  15411. if (previousPinchDistance === 0) {
  15412. previousPinchDistance = pinchSquaredDistance;
  15413. return;
  15414. }
  15415. if (pinchSquaredDistance !== previousPinchDistance) {
  15416. _this.camera
  15417. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  15418. (_this.pinchPrecision *
  15419. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  15420. direction);
  15421. previousPinchDistance = pinchSquaredDistance;
  15422. }
  15423. }
  15424. }
  15425. };
  15426. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  15427. this._onContextMenu = function (evt) {
  15428. evt.preventDefault();
  15429. };
  15430. if (!this.camera._useCtrlForPanning) {
  15431. element.addEventListener("contextmenu", this._onContextMenu, false);
  15432. }
  15433. this._onLostFocus = function () {
  15434. //this._keys = [];
  15435. pointA = pointB = undefined;
  15436. previousPinchDistance = 0;
  15437. cacheSoloPointer = null;
  15438. };
  15439. this._onMouseMove = function (evt) {
  15440. if (!engine.isPointerLock) {
  15441. return;
  15442. }
  15443. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  15444. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  15445. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  15446. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  15447. if (!noPreventDefault) {
  15448. evt.preventDefault();
  15449. }
  15450. };
  15451. this._onGestureStart = function (e) {
  15452. if (window.MSGesture === undefined) {
  15453. return;
  15454. }
  15455. if (!_this._MSGestureHandler) {
  15456. _this._MSGestureHandler = new MSGesture();
  15457. _this._MSGestureHandler.target = element;
  15458. }
  15459. _this._MSGestureHandler.addPointer(e.pointerId);
  15460. };
  15461. this._onGesture = function (e) {
  15462. _this.camera.radius *= e.scale;
  15463. if (e.preventDefault) {
  15464. if (!noPreventDefault) {
  15465. e.stopPropagation();
  15466. e.preventDefault();
  15467. }
  15468. }
  15469. };
  15470. element.addEventListener("mousemove", this._onMouseMove, false);
  15471. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  15472. element.addEventListener("MSGestureChange", this._onGesture, false);
  15473. element.addEventListener("keydown", this._onKeyDown, false);
  15474. element.addEventListener("keyup", this._onKeyUp, false);
  15475. BABYLON.Tools.RegisterTopRootEvents([
  15476. { name: "blur", handler: this._onLostFocus }
  15477. ]);
  15478. };
  15479. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  15480. if (element && this._observer) {
  15481. this.camera.getScene().onPointerObservable.remove(this._observer);
  15482. this._observer = null;
  15483. element.removeEventListener("contextmenu", this._onContextMenu);
  15484. element.removeEventListener("mousemove", this._onMouseMove);
  15485. element.removeEventListener("MSPointerDown", this._onGestureStart);
  15486. element.removeEventListener("MSGestureChange", this._onGesture);
  15487. element.removeEventListener("keydown", this._onKeyDown);
  15488. element.removeEventListener("keyup", this._onKeyUp);
  15489. this._isPanClick = false;
  15490. this.pinchInwards = true;
  15491. this._onKeyDown = null;
  15492. this._onKeyUp = null;
  15493. this._onMouseMove = null;
  15494. this._onGestureStart = null;
  15495. this._onGesture = null;
  15496. this._MSGestureHandler = null;
  15497. this._onLostFocus = null;
  15498. this._onContextMenu = null;
  15499. }
  15500. BABYLON.Tools.UnregisterTopRootEvents([
  15501. { name: "blur", handler: this._onLostFocus }
  15502. ]);
  15503. };
  15504. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  15505. return "ArcRotateCameraPointersInput";
  15506. };
  15507. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  15508. return "pointers";
  15509. };
  15510. return ArcRotateCameraPointersInput;
  15511. }());
  15512. __decorate([
  15513. BABYLON.serialize()
  15514. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  15515. __decorate([
  15516. BABYLON.serialize()
  15517. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  15518. __decorate([
  15519. BABYLON.serialize()
  15520. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  15521. __decorate([
  15522. BABYLON.serialize()
  15523. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  15524. __decorate([
  15525. BABYLON.serialize()
  15526. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  15527. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  15528. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  15529. })(BABYLON || (BABYLON = {}));
  15530. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  15531. var BABYLON;
  15532. (function (BABYLON) {
  15533. var ArcRotateCameraGamepadInput = (function () {
  15534. function ArcRotateCameraGamepadInput() {
  15535. this.gamepadRotationSensibility = 80;
  15536. this.gamepadMoveSensibility = 40;
  15537. }
  15538. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  15539. var _this = this;
  15540. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  15541. };
  15542. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  15543. if (this._gamepads) {
  15544. this._gamepads.dispose();
  15545. }
  15546. this.gamepad = null;
  15547. };
  15548. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  15549. if (this.gamepad) {
  15550. var camera = this.camera;
  15551. var RSValues = this.gamepad.rightStick;
  15552. if (RSValues.x != 0) {
  15553. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  15554. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  15555. camera.inertialAlphaOffset += normalizedRX;
  15556. }
  15557. }
  15558. if (RSValues.y != 0) {
  15559. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  15560. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  15561. camera.inertialBetaOffset += normalizedRY;
  15562. }
  15563. }
  15564. var LSValues = this.gamepad.leftStick;
  15565. if (LSValues.y != 0) {
  15566. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  15567. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  15568. this.camera.inertialRadiusOffset -= normalizedLY;
  15569. }
  15570. }
  15571. }
  15572. };
  15573. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  15574. // Only the first gamepad can control the camera
  15575. if (gamepad.index === 0) {
  15576. this.gamepad = gamepad;
  15577. }
  15578. };
  15579. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  15580. return "ArcRotateCameraGamepadInput";
  15581. };
  15582. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  15583. return "gamepad";
  15584. };
  15585. return ArcRotateCameraGamepadInput;
  15586. }());
  15587. __decorate([
  15588. BABYLON.serialize()
  15589. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  15590. __decorate([
  15591. BABYLON.serialize()
  15592. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  15593. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  15594. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  15595. })(BABYLON || (BABYLON = {}));
  15596. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  15597. var BABYLON;
  15598. (function (BABYLON) {
  15599. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  15600. function ArcRotateCameraVRDeviceOrientationInput() {
  15601. this.alphaCorrection = 1;
  15602. this.betaCorrection = 1;
  15603. this.gammaCorrection = 1;
  15604. this._alpha = 0;
  15605. this._beta = 0;
  15606. this._gamma = 0;
  15607. this._dirty = false;
  15608. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  15609. }
  15610. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  15611. this.camera.attachControl(element, noPreventDefault);
  15612. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  15613. };
  15614. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  15615. var camera = this.camera;
  15616. this._alpha = +evt.alpha | 0;
  15617. this._beta = +evt.beta | 0;
  15618. this._gamma = +evt.gamma | 0;
  15619. this._dirty = true;
  15620. };
  15621. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  15622. if (this._dirty) {
  15623. this._dirty = false;
  15624. if (this._gamma < 0) {
  15625. this._gamma = 180 + this._gamma;
  15626. }
  15627. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  15628. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  15629. }
  15630. };
  15631. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  15632. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  15633. };
  15634. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  15635. return "ArcRotateCameraVRDeviceOrientationInput";
  15636. };
  15637. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  15638. return "VRDeviceOrientation";
  15639. };
  15640. return ArcRotateCameraVRDeviceOrientationInput;
  15641. }());
  15642. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  15643. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  15644. })(BABYLON || (BABYLON = {}));
  15645. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  15646. var BABYLON;
  15647. (function (BABYLON) {
  15648. var TargetCamera = (function (_super) {
  15649. __extends(TargetCamera, _super);
  15650. function TargetCamera(name, position, scene) {
  15651. var _this = _super.call(this, name, position, scene) || this;
  15652. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15653. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  15654. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  15655. _this.speed = 2.0;
  15656. _this.noRotationConstraint = false;
  15657. _this.lockedTarget = null;
  15658. _this._currentTarget = BABYLON.Vector3.Zero();
  15659. _this._viewMatrix = BABYLON.Matrix.Zero();
  15660. _this._camMatrix = BABYLON.Matrix.Zero();
  15661. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  15662. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  15663. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  15664. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  15665. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  15666. _this._lookAtTemp = BABYLON.Matrix.Zero();
  15667. _this._tempMatrix = BABYLON.Matrix.Zero();
  15668. return _this;
  15669. }
  15670. TargetCamera.prototype.getFrontPosition = function (distance) {
  15671. var direction = this.getTarget().subtract(this.position);
  15672. direction.normalize();
  15673. direction.scaleInPlace(distance);
  15674. return this.globalPosition.add(direction);
  15675. };
  15676. TargetCamera.prototype._getLockedTargetPosition = function () {
  15677. if (!this.lockedTarget) {
  15678. return null;
  15679. }
  15680. if (this.lockedTarget.absolutePosition) {
  15681. this.lockedTarget.computeWorldMatrix();
  15682. }
  15683. return this.lockedTarget.absolutePosition || this.lockedTarget;
  15684. };
  15685. // Cache
  15686. TargetCamera.prototype._initCache = function () {
  15687. _super.prototype._initCache.call(this);
  15688. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15689. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15690. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15691. };
  15692. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  15693. if (!ignoreParentClass) {
  15694. _super.prototype._updateCache.call(this);
  15695. }
  15696. var lockedTargetPosition = this._getLockedTargetPosition();
  15697. if (!lockedTargetPosition) {
  15698. this._cache.lockedTarget = null;
  15699. }
  15700. else {
  15701. if (!this._cache.lockedTarget) {
  15702. this._cache.lockedTarget = lockedTargetPosition.clone();
  15703. }
  15704. else {
  15705. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  15706. }
  15707. }
  15708. this._cache.rotation.copyFrom(this.rotation);
  15709. if (this.rotationQuaternion)
  15710. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15711. };
  15712. // Synchronized
  15713. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  15714. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  15715. return false;
  15716. }
  15717. var lockedTargetPosition = this._getLockedTargetPosition();
  15718. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  15719. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  15720. };
  15721. // Methods
  15722. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  15723. var engine = this.getEngine();
  15724. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  15725. };
  15726. // Target
  15727. TargetCamera.prototype.setTarget = function (target) {
  15728. this.upVector.normalize();
  15729. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  15730. this._camMatrix.invert();
  15731. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  15732. var vDir = target.subtract(this.position);
  15733. if (vDir.x >= 0.0) {
  15734. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  15735. }
  15736. else {
  15737. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  15738. }
  15739. this.rotation.z = 0;
  15740. if (isNaN(this.rotation.x)) {
  15741. this.rotation.x = 0;
  15742. }
  15743. if (isNaN(this.rotation.y)) {
  15744. this.rotation.y = 0;
  15745. }
  15746. if (isNaN(this.rotation.z)) {
  15747. this.rotation.z = 0;
  15748. }
  15749. if (this.rotationQuaternion) {
  15750. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  15751. }
  15752. };
  15753. TargetCamera.prototype.getTarget = function () {
  15754. return this._currentTarget;
  15755. };
  15756. TargetCamera.prototype._decideIfNeedsToMove = function () {
  15757. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15758. };
  15759. TargetCamera.prototype._updatePosition = function () {
  15760. this.position.addInPlace(this.cameraDirection);
  15761. };
  15762. TargetCamera.prototype._checkInputs = function () {
  15763. var needToMove = this._decideIfNeedsToMove();
  15764. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  15765. // Move
  15766. if (needToMove) {
  15767. this._updatePosition();
  15768. }
  15769. // Rotate
  15770. if (needToRotate) {
  15771. this.rotation.x += this.cameraRotation.x;
  15772. this.rotation.y += this.cameraRotation.y;
  15773. if (!this.noRotationConstraint) {
  15774. var limit = (Math.PI / 2) * 0.95;
  15775. if (this.rotation.x > limit)
  15776. this.rotation.x = limit;
  15777. if (this.rotation.x < -limit)
  15778. this.rotation.x = -limit;
  15779. }
  15780. }
  15781. // Inertia
  15782. if (needToMove) {
  15783. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  15784. this.cameraDirection.x = 0;
  15785. }
  15786. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  15787. this.cameraDirection.y = 0;
  15788. }
  15789. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  15790. this.cameraDirection.z = 0;
  15791. }
  15792. this.cameraDirection.scaleInPlace(this.inertia);
  15793. }
  15794. if (needToRotate) {
  15795. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  15796. this.cameraRotation.x = 0;
  15797. }
  15798. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  15799. this.cameraRotation.y = 0;
  15800. }
  15801. this.cameraRotation.scaleInPlace(this.inertia);
  15802. }
  15803. _super.prototype._checkInputs.call(this);
  15804. };
  15805. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  15806. if (this.rotationQuaternion) {
  15807. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  15808. //update the up vector!
  15809. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  15810. }
  15811. else {
  15812. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  15813. }
  15814. };
  15815. TargetCamera.prototype._getViewMatrix = function () {
  15816. if (!this.lockedTarget) {
  15817. // Compute
  15818. this._updateCameraRotationMatrix();
  15819. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  15820. // Computing target and final matrix
  15821. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  15822. }
  15823. else {
  15824. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  15825. }
  15826. if (this.getScene().useRightHandedSystem) {
  15827. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  15828. }
  15829. else {
  15830. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  15831. }
  15832. return this._viewMatrix;
  15833. };
  15834. /**
  15835. * @override
  15836. * Override Camera.createRigCamera
  15837. */
  15838. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15839. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  15840. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  15841. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  15842. if (!this.rotationQuaternion) {
  15843. this.rotationQuaternion = new BABYLON.Quaternion();
  15844. }
  15845. rigCamera._cameraRigParams = {};
  15846. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  15847. }
  15848. return rigCamera;
  15849. }
  15850. return null;
  15851. };
  15852. /**
  15853. * @override
  15854. * Override Camera._updateRigCameras
  15855. */
  15856. TargetCamera.prototype._updateRigCameras = function () {
  15857. var camLeft = this._rigCameras[0];
  15858. var camRight = this._rigCameras[1];
  15859. switch (this.cameraRigMode) {
  15860. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15861. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15862. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15863. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15864. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  15865. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  15866. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  15867. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  15868. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  15869. camLeft.setTarget(this.getTarget());
  15870. camRight.setTarget(this.getTarget());
  15871. break;
  15872. case BABYLON.Camera.RIG_MODE_VR:
  15873. case BABYLON.Camera.RIG_MODE_WEBVR:
  15874. if (camLeft.rotationQuaternion) {
  15875. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15876. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15877. }
  15878. else {
  15879. camLeft.rotation.copyFrom(this.rotation);
  15880. camRight.rotation.copyFrom(this.rotation);
  15881. }
  15882. camLeft.position.copyFrom(this.position);
  15883. camRight.position.copyFrom(this.position);
  15884. break;
  15885. }
  15886. _super.prototype._updateRigCameras.call(this);
  15887. };
  15888. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  15889. if (!this._rigCamTransformMatrix) {
  15890. this._rigCamTransformMatrix = new BABYLON.Matrix();
  15891. }
  15892. var target = this.getTarget();
  15893. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  15894. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  15895. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  15896. };
  15897. TargetCamera.prototype.getClassName = function () {
  15898. return "TargetCamera";
  15899. };
  15900. return TargetCamera;
  15901. }(BABYLON.Camera));
  15902. __decorate([
  15903. BABYLON.serializeAsVector3()
  15904. ], TargetCamera.prototype, "rotation", void 0);
  15905. __decorate([
  15906. BABYLON.serialize()
  15907. ], TargetCamera.prototype, "speed", void 0);
  15908. __decorate([
  15909. BABYLON.serializeAsMeshReference("lockedTargetId")
  15910. ], TargetCamera.prototype, "lockedTarget", void 0);
  15911. BABYLON.TargetCamera = TargetCamera;
  15912. })(BABYLON || (BABYLON = {}));
  15913. //# sourceMappingURL=babylon.targetCamera.js.map
  15914. var BABYLON;
  15915. (function (BABYLON) {
  15916. var FreeCamera = (function (_super) {
  15917. __extends(FreeCamera, _super);
  15918. function FreeCamera(name, position, scene) {
  15919. var _this = _super.call(this, name, position, scene) || this;
  15920. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15921. _this.checkCollisions = false;
  15922. _this.applyGravity = false;
  15923. _this._collider = new BABYLON.Collider();
  15924. _this._needMoveForGravity = false;
  15925. _this._oldPosition = BABYLON.Vector3.Zero();
  15926. _this._diffPosition = BABYLON.Vector3.Zero();
  15927. _this._newPosition = BABYLON.Vector3.Zero();
  15928. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15929. if (collidedMesh === void 0) { collidedMesh = null; }
  15930. //TODO move this to the collision coordinator!
  15931. if (_this.getScene().workerCollisions)
  15932. newPosition.multiplyInPlace(_this._collider.radius);
  15933. var updatePosition = function (newPos) {
  15934. _this._newPosition.copyFrom(newPos);
  15935. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  15936. var oldPosition = _this.position.clone();
  15937. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  15938. _this.position.addInPlace(_this._diffPosition);
  15939. if (_this.onCollide && collidedMesh) {
  15940. _this.onCollide(collidedMesh);
  15941. }
  15942. }
  15943. };
  15944. updatePosition(newPosition);
  15945. };
  15946. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  15947. _this.inputs.addKeyboard().addMouse();
  15948. return _this;
  15949. }
  15950. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  15951. //-- begin properties for backward compatibility for inputs
  15952. get: function () {
  15953. var mouse = this.inputs.attached["mouse"];
  15954. if (mouse)
  15955. return mouse.angularSensibility;
  15956. },
  15957. set: function (value) {
  15958. var mouse = this.inputs.attached["mouse"];
  15959. if (mouse)
  15960. mouse.angularSensibility = value;
  15961. },
  15962. enumerable: true,
  15963. configurable: true
  15964. });
  15965. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  15966. get: function () {
  15967. var keyboard = this.inputs.attached["keyboard"];
  15968. if (keyboard)
  15969. return keyboard.keysUp;
  15970. },
  15971. set: function (value) {
  15972. var keyboard = this.inputs.attached["keyboard"];
  15973. if (keyboard)
  15974. keyboard.keysUp = value;
  15975. },
  15976. enumerable: true,
  15977. configurable: true
  15978. });
  15979. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  15980. get: function () {
  15981. var keyboard = this.inputs.attached["keyboard"];
  15982. if (keyboard)
  15983. return keyboard.keysDown;
  15984. },
  15985. set: function (value) {
  15986. var keyboard = this.inputs.attached["keyboard"];
  15987. if (keyboard)
  15988. keyboard.keysDown = value;
  15989. },
  15990. enumerable: true,
  15991. configurable: true
  15992. });
  15993. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  15994. get: function () {
  15995. var keyboard = this.inputs.attached["keyboard"];
  15996. if (keyboard)
  15997. return keyboard.keysLeft;
  15998. },
  15999. set: function (value) {
  16000. var keyboard = this.inputs.attached["keyboard"];
  16001. if (keyboard)
  16002. keyboard.keysLeft = value;
  16003. },
  16004. enumerable: true,
  16005. configurable: true
  16006. });
  16007. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  16008. get: function () {
  16009. var keyboard = this.inputs.attached["keyboard"];
  16010. if (keyboard)
  16011. return keyboard.keysRight;
  16012. },
  16013. set: function (value) {
  16014. var keyboard = this.inputs.attached["keyboard"];
  16015. if (keyboard)
  16016. keyboard.keysRight = value;
  16017. },
  16018. enumerable: true,
  16019. configurable: true
  16020. });
  16021. // Controls
  16022. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  16023. this.inputs.attachElement(element, noPreventDefault);
  16024. };
  16025. FreeCamera.prototype.detachControl = function (element) {
  16026. this.inputs.detachElement(element);
  16027. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  16028. this.cameraRotation = new BABYLON.Vector2(0, 0);
  16029. };
  16030. FreeCamera.prototype._collideWithWorld = function (velocity) {
  16031. var globalPosition;
  16032. if (this.parent) {
  16033. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  16034. }
  16035. else {
  16036. globalPosition = this.position;
  16037. }
  16038. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  16039. this._collider.radius = this.ellipsoid;
  16040. //no need for clone, as long as gravity is not on.
  16041. var actualVelocity = velocity;
  16042. //add gravity to the velocity to prevent the dual-collision checking
  16043. if (this.applyGravity) {
  16044. //this prevents mending with cameraDirection, a global variable of the free camera class.
  16045. actualVelocity = velocity.add(this.getScene().gravity);
  16046. }
  16047. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  16048. };
  16049. FreeCamera.prototype._checkInputs = function () {
  16050. if (!this._localDirection) {
  16051. this._localDirection = BABYLON.Vector3.Zero();
  16052. this._transformedDirection = BABYLON.Vector3.Zero();
  16053. }
  16054. this.inputs.checkInputs();
  16055. _super.prototype._checkInputs.call(this);
  16056. };
  16057. FreeCamera.prototype._decideIfNeedsToMove = function () {
  16058. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  16059. };
  16060. FreeCamera.prototype._updatePosition = function () {
  16061. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  16062. this._collideWithWorld(this.cameraDirection);
  16063. }
  16064. else {
  16065. this.position.addInPlace(this.cameraDirection);
  16066. }
  16067. };
  16068. FreeCamera.prototype.dispose = function () {
  16069. this.inputs.clear();
  16070. _super.prototype.dispose.call(this);
  16071. };
  16072. FreeCamera.prototype.getClassName = function () {
  16073. return "FreeCamera";
  16074. };
  16075. return FreeCamera;
  16076. }(BABYLON.TargetCamera));
  16077. __decorate([
  16078. BABYLON.serializeAsVector3()
  16079. ], FreeCamera.prototype, "ellipsoid", void 0);
  16080. __decorate([
  16081. BABYLON.serialize()
  16082. ], FreeCamera.prototype, "checkCollisions", void 0);
  16083. __decorate([
  16084. BABYLON.serialize()
  16085. ], FreeCamera.prototype, "applyGravity", void 0);
  16086. BABYLON.FreeCamera = FreeCamera;
  16087. })(BABYLON || (BABYLON = {}));
  16088. //# sourceMappingURL=babylon.freeCamera.js.map
  16089. var BABYLON;
  16090. (function (BABYLON) {
  16091. var FreeCameraInputsManager = (function (_super) {
  16092. __extends(FreeCameraInputsManager, _super);
  16093. function FreeCameraInputsManager(camera) {
  16094. return _super.call(this, camera) || this;
  16095. }
  16096. FreeCameraInputsManager.prototype.addKeyboard = function () {
  16097. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  16098. return this;
  16099. };
  16100. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  16101. if (touchEnabled === void 0) { touchEnabled = true; }
  16102. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  16103. return this;
  16104. };
  16105. FreeCameraInputsManager.prototype.addGamepad = function () {
  16106. this.add(new BABYLON.FreeCameraGamepadInput());
  16107. return this;
  16108. };
  16109. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  16110. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  16111. return this;
  16112. };
  16113. FreeCameraInputsManager.prototype.addTouch = function () {
  16114. this.add(new BABYLON.FreeCameraTouchInput());
  16115. return this;
  16116. };
  16117. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  16118. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  16119. return this;
  16120. };
  16121. return FreeCameraInputsManager;
  16122. }(BABYLON.CameraInputsManager));
  16123. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  16124. })(BABYLON || (BABYLON = {}));
  16125. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  16126. var BABYLON;
  16127. (function (BABYLON) {
  16128. var FollowCamera = (function (_super) {
  16129. __extends(FollowCamera, _super);
  16130. function FollowCamera(name, position, scene, lockedTarget) {
  16131. var _this = _super.call(this, name, position, scene) || this;
  16132. _this.radius = 12;
  16133. _this.rotationOffset = 0;
  16134. _this.heightOffset = 4;
  16135. _this.cameraAcceleration = 0.05;
  16136. _this.maxCameraSpeed = 20;
  16137. _this.lockedTarget = lockedTarget;
  16138. return _this;
  16139. }
  16140. FollowCamera.prototype.getRadians = function (degrees) {
  16141. return degrees * Math.PI / 180;
  16142. };
  16143. FollowCamera.prototype.follow = function (cameraTarget) {
  16144. if (!cameraTarget)
  16145. return;
  16146. var yRotation;
  16147. if (cameraTarget.rotationQuaternion) {
  16148. var rotMatrix = new BABYLON.Matrix();
  16149. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  16150. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  16151. }
  16152. else {
  16153. yRotation = cameraTarget.rotation.y;
  16154. }
  16155. var radians = this.getRadians(this.rotationOffset) + yRotation;
  16156. var targetPosition = cameraTarget.getAbsolutePosition();
  16157. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  16158. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  16159. var dx = targetX - this.position.x;
  16160. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  16161. var dz = (targetZ) - this.position.z;
  16162. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  16163. var vy = dy * this.cameraAcceleration;
  16164. var vz = dz * this.cameraAcceleration * 2;
  16165. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  16166. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  16167. }
  16168. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  16169. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  16170. }
  16171. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  16172. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  16173. }
  16174. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  16175. this.setTarget(targetPosition);
  16176. };
  16177. FollowCamera.prototype._checkInputs = function () {
  16178. _super.prototype._checkInputs.call(this);
  16179. this.follow(this.lockedTarget);
  16180. };
  16181. FollowCamera.prototype.getClassName = function () {
  16182. return "FollowCamera";
  16183. };
  16184. return FollowCamera;
  16185. }(BABYLON.TargetCamera));
  16186. __decorate([
  16187. BABYLON.serialize()
  16188. ], FollowCamera.prototype, "radius", void 0);
  16189. __decorate([
  16190. BABYLON.serialize()
  16191. ], FollowCamera.prototype, "rotationOffset", void 0);
  16192. __decorate([
  16193. BABYLON.serialize()
  16194. ], FollowCamera.prototype, "heightOffset", void 0);
  16195. __decorate([
  16196. BABYLON.serialize()
  16197. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  16198. __decorate([
  16199. BABYLON.serialize()
  16200. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  16201. __decorate([
  16202. BABYLON.serializeAsMeshReference("lockedTargetId")
  16203. ], FollowCamera.prototype, "lockedTarget", void 0);
  16204. BABYLON.FollowCamera = FollowCamera;
  16205. var ArcFollowCamera = (function (_super) {
  16206. __extends(ArcFollowCamera, _super);
  16207. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  16208. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  16209. _this.alpha = alpha;
  16210. _this.beta = beta;
  16211. _this.radius = radius;
  16212. _this.target = target;
  16213. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  16214. _this.follow();
  16215. return _this;
  16216. }
  16217. ArcFollowCamera.prototype.follow = function () {
  16218. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  16219. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  16220. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  16221. var targetPosition = this.target.getAbsolutePosition();
  16222. this.position = targetPosition.add(this._cartesianCoordinates);
  16223. this.setTarget(targetPosition);
  16224. };
  16225. ArcFollowCamera.prototype._checkInputs = function () {
  16226. _super.prototype._checkInputs.call(this);
  16227. this.follow();
  16228. };
  16229. ArcFollowCamera.prototype.getClassName = function () {
  16230. return "ArcFollowCamera";
  16231. };
  16232. return ArcFollowCamera;
  16233. }(BABYLON.TargetCamera));
  16234. BABYLON.ArcFollowCamera = ArcFollowCamera;
  16235. })(BABYLON || (BABYLON = {}));
  16236. //# sourceMappingURL=babylon.followCamera.js.map
  16237. var BABYLON;
  16238. (function (BABYLON) {
  16239. // We're mainly based on the logic defined into the FreeCamera code
  16240. var TouchCamera = (function (_super) {
  16241. __extends(TouchCamera, _super);
  16242. //-- end properties for backward compatibility for inputs
  16243. function TouchCamera(name, position, scene) {
  16244. var _this = _super.call(this, name, position, scene) || this;
  16245. _this.inputs.addTouch();
  16246. _this._setupInputs();
  16247. return _this;
  16248. }
  16249. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  16250. //-- Begin properties for backward compatibility for inputs
  16251. get: function () {
  16252. var touch = this.inputs.attached["touch"];
  16253. if (touch)
  16254. return touch.touchAngularSensibility;
  16255. },
  16256. set: function (value) {
  16257. var touch = this.inputs.attached["touch"];
  16258. if (touch)
  16259. touch.touchAngularSensibility = value;
  16260. },
  16261. enumerable: true,
  16262. configurable: true
  16263. });
  16264. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  16265. get: function () {
  16266. var touch = this.inputs.attached["touch"];
  16267. if (touch)
  16268. return touch.touchMoveSensibility;
  16269. },
  16270. set: function (value) {
  16271. var touch = this.inputs.attached["touch"];
  16272. if (touch)
  16273. touch.touchMoveSensibility = value;
  16274. },
  16275. enumerable: true,
  16276. configurable: true
  16277. });
  16278. TouchCamera.prototype.getClassName = function () {
  16279. return "TouchCamera";
  16280. };
  16281. TouchCamera.prototype._setupInputs = function () {
  16282. var mouse = this.inputs.attached["mouse"];
  16283. if (mouse) {
  16284. mouse.touchEnabled = false;
  16285. }
  16286. };
  16287. return TouchCamera;
  16288. }(BABYLON.FreeCamera));
  16289. BABYLON.TouchCamera = TouchCamera;
  16290. })(BABYLON || (BABYLON = {}));
  16291. //# sourceMappingURL=babylon.touchCamera.js.map
  16292. var BABYLON;
  16293. (function (BABYLON) {
  16294. var ArcRotateCamera = (function (_super) {
  16295. __extends(ArcRotateCamera, _super);
  16296. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  16297. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  16298. _this.inertialAlphaOffset = 0;
  16299. _this.inertialBetaOffset = 0;
  16300. _this.inertialRadiusOffset = 0;
  16301. _this.lowerAlphaLimit = null;
  16302. _this.upperAlphaLimit = null;
  16303. _this.lowerBetaLimit = 0.01;
  16304. _this.upperBetaLimit = Math.PI;
  16305. _this.lowerRadiusLimit = null;
  16306. _this.upperRadiusLimit = null;
  16307. _this.inertialPanningX = 0;
  16308. _this.inertialPanningY = 0;
  16309. //-- end properties for backward compatibility for inputs
  16310. _this.zoomOnFactor = 1;
  16311. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  16312. _this.allowUpsideDown = true;
  16313. _this._viewMatrix = new BABYLON.Matrix();
  16314. // Panning
  16315. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  16316. _this.checkCollisions = false;
  16317. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  16318. _this._collider = new BABYLON.Collider();
  16319. _this._previousPosition = BABYLON.Vector3.Zero();
  16320. _this._collisionVelocity = BABYLON.Vector3.Zero();
  16321. _this._newPosition = BABYLON.Vector3.Zero();
  16322. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  16323. if (collidedMesh === void 0) { collidedMesh = null; }
  16324. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  16325. newPosition.multiplyInPlace(_this._collider.radius);
  16326. }
  16327. if (!collidedMesh) {
  16328. _this._previousPosition.copyFrom(_this.position);
  16329. }
  16330. else {
  16331. _this.setPosition(newPosition);
  16332. if (_this.onCollide) {
  16333. _this.onCollide(collidedMesh);
  16334. }
  16335. }
  16336. // Recompute because of constraints
  16337. var cosa = Math.cos(_this.alpha);
  16338. var sina = Math.sin(_this.alpha);
  16339. var cosb = Math.cos(_this.beta);
  16340. var sinb = Math.sin(_this.beta);
  16341. if (sinb === 0) {
  16342. sinb = 0.0001;
  16343. }
  16344. var target = _this._getTargetPosition();
  16345. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  16346. _this.position.copyFrom(_this._newPosition);
  16347. var up = _this.upVector;
  16348. if (_this.allowUpsideDown && _this.beta < 0) {
  16349. up = up.clone();
  16350. up = up.negate();
  16351. }
  16352. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  16353. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  16354. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  16355. _this._collisionTriggered = false;
  16356. };
  16357. if (!target) {
  16358. _this.target = BABYLON.Vector3.Zero();
  16359. }
  16360. else {
  16361. _this.target = target;
  16362. }
  16363. _this.alpha = alpha;
  16364. _this.beta = beta;
  16365. _this.radius = radius;
  16366. _this.getViewMatrix();
  16367. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  16368. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  16369. return _this;
  16370. }
  16371. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  16372. //-- begin properties for backward compatibility for inputs
  16373. get: function () {
  16374. var pointers = this.inputs.attached["pointers"];
  16375. if (pointers)
  16376. return pointers.angularSensibilityX;
  16377. },
  16378. set: function (value) {
  16379. var pointers = this.inputs.attached["pointers"];
  16380. if (pointers) {
  16381. pointers.angularSensibilityX = value;
  16382. }
  16383. },
  16384. enumerable: true,
  16385. configurable: true
  16386. });
  16387. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  16388. get: function () {
  16389. var pointers = this.inputs.attached["pointers"];
  16390. if (pointers)
  16391. return pointers.angularSensibilityY;
  16392. },
  16393. set: function (value) {
  16394. var pointers = this.inputs.attached["pointers"];
  16395. if (pointers) {
  16396. pointers.angularSensibilityY = value;
  16397. }
  16398. },
  16399. enumerable: true,
  16400. configurable: true
  16401. });
  16402. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  16403. get: function () {
  16404. var pointers = this.inputs.attached["pointers"];
  16405. if (pointers)
  16406. return pointers.pinchPrecision;
  16407. },
  16408. set: function (value) {
  16409. var pointers = this.inputs.attached["pointers"];
  16410. if (pointers) {
  16411. pointers.pinchPrecision = value;
  16412. }
  16413. },
  16414. enumerable: true,
  16415. configurable: true
  16416. });
  16417. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  16418. get: function () {
  16419. var pointers = this.inputs.attached["pointers"];
  16420. if (pointers)
  16421. return pointers.panningSensibility;
  16422. },
  16423. set: function (value) {
  16424. var pointers = this.inputs.attached["pointers"];
  16425. if (pointers) {
  16426. pointers.panningSensibility = value;
  16427. }
  16428. },
  16429. enumerable: true,
  16430. configurable: true
  16431. });
  16432. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  16433. get: function () {
  16434. var keyboard = this.inputs.attached["keyboard"];
  16435. if (keyboard)
  16436. return keyboard.keysUp;
  16437. },
  16438. set: function (value) {
  16439. var keyboard = this.inputs.attached["keyboard"];
  16440. if (keyboard)
  16441. keyboard.keysUp = value;
  16442. },
  16443. enumerable: true,
  16444. configurable: true
  16445. });
  16446. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  16447. get: function () {
  16448. var keyboard = this.inputs.attached["keyboard"];
  16449. if (keyboard)
  16450. return keyboard.keysDown;
  16451. },
  16452. set: function (value) {
  16453. var keyboard = this.inputs.attached["keyboard"];
  16454. if (keyboard)
  16455. keyboard.keysDown = value;
  16456. },
  16457. enumerable: true,
  16458. configurable: true
  16459. });
  16460. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  16461. get: function () {
  16462. var keyboard = this.inputs.attached["keyboard"];
  16463. if (keyboard)
  16464. return keyboard.keysLeft;
  16465. },
  16466. set: function (value) {
  16467. var keyboard = this.inputs.attached["keyboard"];
  16468. if (keyboard)
  16469. keyboard.keysLeft = value;
  16470. },
  16471. enumerable: true,
  16472. configurable: true
  16473. });
  16474. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  16475. get: function () {
  16476. var keyboard = this.inputs.attached["keyboard"];
  16477. if (keyboard)
  16478. return keyboard.keysRight;
  16479. },
  16480. set: function (value) {
  16481. var keyboard = this.inputs.attached["keyboard"];
  16482. if (keyboard)
  16483. keyboard.keysRight = value;
  16484. },
  16485. enumerable: true,
  16486. configurable: true
  16487. });
  16488. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  16489. get: function () {
  16490. var mousewheel = this.inputs.attached["mousewheel"];
  16491. if (mousewheel)
  16492. return mousewheel.wheelPrecision;
  16493. },
  16494. set: function (value) {
  16495. var mousewheel = this.inputs.attached["mousewheel"];
  16496. if (mousewheel)
  16497. mousewheel.wheelPrecision = value;
  16498. },
  16499. enumerable: true,
  16500. configurable: true
  16501. });
  16502. // Cache
  16503. ArcRotateCamera.prototype._initCache = function () {
  16504. _super.prototype._initCache.call(this);
  16505. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  16506. this._cache.alpha = undefined;
  16507. this._cache.beta = undefined;
  16508. this._cache.radius = undefined;
  16509. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  16510. };
  16511. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  16512. if (!ignoreParentClass) {
  16513. _super.prototype._updateCache.call(this);
  16514. }
  16515. this._cache.target.copyFrom(this._getTargetPosition());
  16516. this._cache.alpha = this.alpha;
  16517. this._cache.beta = this.beta;
  16518. this._cache.radius = this.radius;
  16519. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  16520. };
  16521. ArcRotateCamera.prototype._getTargetPosition = function () {
  16522. if (this.target.getAbsolutePosition) {
  16523. var pos = this.target.getAbsolutePosition();
  16524. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  16525. }
  16526. return this.target;
  16527. };
  16528. // Synchronized
  16529. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  16530. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  16531. return false;
  16532. return this._cache.target.equals(this.target)
  16533. && this._cache.alpha === this.alpha
  16534. && this._cache.beta === this.beta
  16535. && this._cache.radius === this.radius
  16536. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  16537. };
  16538. // Methods
  16539. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  16540. var _this = this;
  16541. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  16542. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  16543. this._useCtrlForPanning = useCtrlForPanning;
  16544. this._panningMouseButton = panningMouseButton;
  16545. this.inputs.attachElement(element, noPreventDefault);
  16546. this._reset = function () {
  16547. _this.inertialAlphaOffset = 0;
  16548. _this.inertialBetaOffset = 0;
  16549. _this.inertialRadiusOffset = 0;
  16550. };
  16551. };
  16552. ArcRotateCamera.prototype.detachControl = function (element) {
  16553. this.inputs.detachElement(element);
  16554. if (this._reset) {
  16555. this._reset();
  16556. }
  16557. };
  16558. ArcRotateCamera.prototype._checkInputs = function () {
  16559. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  16560. if (this._collisionTriggered) {
  16561. return;
  16562. }
  16563. this.inputs.checkInputs();
  16564. // Inertia
  16565. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  16566. if (this.getScene().useRightHandedSystem) {
  16567. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  16568. }
  16569. else {
  16570. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  16571. }
  16572. this.beta += this.inertialBetaOffset;
  16573. this.radius -= this.inertialRadiusOffset;
  16574. this.inertialAlphaOffset *= this.inertia;
  16575. this.inertialBetaOffset *= this.inertia;
  16576. this.inertialRadiusOffset *= this.inertia;
  16577. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  16578. this.inertialAlphaOffset = 0;
  16579. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  16580. this.inertialBetaOffset = 0;
  16581. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  16582. this.inertialRadiusOffset = 0;
  16583. }
  16584. // Panning inertia
  16585. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  16586. if (!this._localDirection) {
  16587. this._localDirection = BABYLON.Vector3.Zero();
  16588. this._transformedDirection = BABYLON.Vector3.Zero();
  16589. }
  16590. this.inertialPanningX *= this.inertia;
  16591. this.inertialPanningY *= this.inertia;
  16592. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  16593. this.inertialPanningX = 0;
  16594. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  16595. this.inertialPanningY = 0;
  16596. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  16597. this._localDirection.multiplyInPlace(this.panningAxis);
  16598. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  16599. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  16600. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  16601. if (!this.panningAxis.y) {
  16602. this._transformedDirection.y = 0;
  16603. }
  16604. if (!this.target.getAbsolutePosition) {
  16605. this.target.addInPlace(this._transformedDirection);
  16606. }
  16607. }
  16608. // Limits
  16609. this._checkLimits();
  16610. _super.prototype._checkInputs.call(this);
  16611. };
  16612. ArcRotateCamera.prototype._checkLimits = function () {
  16613. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  16614. if (this.allowUpsideDown && this.beta > Math.PI) {
  16615. this.beta = this.beta - (2 * Math.PI);
  16616. }
  16617. }
  16618. else {
  16619. if (this.beta < this.lowerBetaLimit) {
  16620. this.beta = this.lowerBetaLimit;
  16621. }
  16622. }
  16623. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  16624. if (this.allowUpsideDown && this.beta < -Math.PI) {
  16625. this.beta = this.beta + (2 * Math.PI);
  16626. }
  16627. }
  16628. else {
  16629. if (this.beta > this.upperBetaLimit) {
  16630. this.beta = this.upperBetaLimit;
  16631. }
  16632. }
  16633. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  16634. this.alpha = this.lowerAlphaLimit;
  16635. }
  16636. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  16637. this.alpha = this.upperAlphaLimit;
  16638. }
  16639. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  16640. this.radius = this.lowerRadiusLimit;
  16641. }
  16642. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  16643. this.radius = this.upperRadiusLimit;
  16644. }
  16645. };
  16646. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  16647. var radiusv3 = this.position.subtract(this._getTargetPosition());
  16648. this.radius = radiusv3.length();
  16649. // Alpha
  16650. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  16651. if (radiusv3.z < 0) {
  16652. this.alpha = 2 * Math.PI - this.alpha;
  16653. }
  16654. // Beta
  16655. this.beta = Math.acos(radiusv3.y / this.radius);
  16656. this._checkLimits();
  16657. };
  16658. ArcRotateCamera.prototype.setPosition = function (position) {
  16659. if (this.position.equals(position)) {
  16660. return;
  16661. }
  16662. this.position.copyFrom(position);
  16663. this.rebuildAnglesAndRadius();
  16664. };
  16665. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  16666. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  16667. if (allowSamePosition === void 0) { allowSamePosition = false; }
  16668. if (!allowSamePosition && this._getTargetPosition().equals(target)) {
  16669. return;
  16670. }
  16671. if (toBoundingCenter && target.getBoundingInfo) {
  16672. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  16673. }
  16674. else {
  16675. this._targetBoundingCenter = null;
  16676. }
  16677. this.target = target;
  16678. this.rebuildAnglesAndRadius();
  16679. };
  16680. ArcRotateCamera.prototype._getViewMatrix = function () {
  16681. // Compute
  16682. var cosa = Math.cos(this.alpha);
  16683. var sina = Math.sin(this.alpha);
  16684. var cosb = Math.cos(this.beta);
  16685. var sinb = Math.sin(this.beta);
  16686. if (sinb === 0) {
  16687. sinb = 0.0001;
  16688. }
  16689. var target = this._getTargetPosition();
  16690. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  16691. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  16692. this._collider.radius = this.collisionRadius;
  16693. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  16694. this._collisionTriggered = true;
  16695. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  16696. }
  16697. else {
  16698. this.position.copyFrom(this._newPosition);
  16699. var up = this.upVector;
  16700. if (this.allowUpsideDown && this.beta < 0) {
  16701. up = up.clone();
  16702. up = up.negate();
  16703. }
  16704. if (this.getScene().useRightHandedSystem) {
  16705. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  16706. }
  16707. else {
  16708. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  16709. }
  16710. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  16711. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  16712. }
  16713. this._currentTarget = target;
  16714. return this._viewMatrix;
  16715. };
  16716. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  16717. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  16718. meshes = meshes || this.getScene().meshes;
  16719. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  16720. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  16721. this.radius = distance * this.zoomOnFactor;
  16722. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  16723. };
  16724. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  16725. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  16726. var meshesOrMinMaxVector;
  16727. var distance;
  16728. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  16729. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  16730. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  16731. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  16732. }
  16733. else {
  16734. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  16735. distance = meshesOrMinMaxVectorAndDistance.distance;
  16736. }
  16737. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  16738. if (!doNotUpdateMaxZ) {
  16739. this.maxZ = distance * 2;
  16740. }
  16741. };
  16742. /**
  16743. * @override
  16744. * Override Camera.createRigCamera
  16745. */
  16746. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  16747. var alphaShift;
  16748. switch (this.cameraRigMode) {
  16749. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16750. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16751. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16752. case BABYLON.Camera.RIG_MODE_VR:
  16753. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  16754. break;
  16755. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16756. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  16757. break;
  16758. }
  16759. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  16760. rigCam._cameraRigParams = {};
  16761. return rigCam;
  16762. };
  16763. /**
  16764. * @override
  16765. * Override Camera._updateRigCameras
  16766. */
  16767. ArcRotateCamera.prototype._updateRigCameras = function () {
  16768. var camLeft = this._rigCameras[0];
  16769. var camRight = this._rigCameras[1];
  16770. camLeft.beta = camRight.beta = this.beta;
  16771. camLeft.radius = camRight.radius = this.radius;
  16772. switch (this.cameraRigMode) {
  16773. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  16774. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  16775. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  16776. case BABYLON.Camera.RIG_MODE_VR:
  16777. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  16778. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  16779. break;
  16780. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  16781. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  16782. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  16783. break;
  16784. }
  16785. _super.prototype._updateRigCameras.call(this);
  16786. };
  16787. ArcRotateCamera.prototype.dispose = function () {
  16788. this.inputs.clear();
  16789. _super.prototype.dispose.call(this);
  16790. };
  16791. ArcRotateCamera.prototype.getClassName = function () {
  16792. return "ArcRotateCamera";
  16793. };
  16794. return ArcRotateCamera;
  16795. }(BABYLON.TargetCamera));
  16796. __decorate([
  16797. BABYLON.serialize()
  16798. ], ArcRotateCamera.prototype, "alpha", void 0);
  16799. __decorate([
  16800. BABYLON.serialize()
  16801. ], ArcRotateCamera.prototype, "beta", void 0);
  16802. __decorate([
  16803. BABYLON.serialize()
  16804. ], ArcRotateCamera.prototype, "radius", void 0);
  16805. __decorate([
  16806. BABYLON.serializeAsVector3()
  16807. ], ArcRotateCamera.prototype, "target", void 0);
  16808. __decorate([
  16809. BABYLON.serialize()
  16810. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  16811. __decorate([
  16812. BABYLON.serialize()
  16813. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  16814. __decorate([
  16815. BABYLON.serialize()
  16816. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  16817. __decorate([
  16818. BABYLON.serialize()
  16819. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  16820. __decorate([
  16821. BABYLON.serialize()
  16822. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  16823. __decorate([
  16824. BABYLON.serialize()
  16825. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  16826. __decorate([
  16827. BABYLON.serialize()
  16828. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  16829. __decorate([
  16830. BABYLON.serialize()
  16831. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  16832. __decorate([
  16833. BABYLON.serialize()
  16834. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  16835. __decorate([
  16836. BABYLON.serialize()
  16837. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  16838. __decorate([
  16839. BABYLON.serialize()
  16840. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  16841. __decorate([
  16842. BABYLON.serialize()
  16843. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  16844. __decorate([
  16845. BABYLON.serialize()
  16846. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  16847. BABYLON.ArcRotateCamera = ArcRotateCamera;
  16848. })(BABYLON || (BABYLON = {}));
  16849. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  16850. var BABYLON;
  16851. (function (BABYLON) {
  16852. var ArcRotateCameraInputsManager = (function (_super) {
  16853. __extends(ArcRotateCameraInputsManager, _super);
  16854. function ArcRotateCameraInputsManager(camera) {
  16855. return _super.call(this, camera) || this;
  16856. }
  16857. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  16858. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  16859. return this;
  16860. };
  16861. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  16862. this.add(new BABYLON.ArcRotateCameraPointersInput());
  16863. return this;
  16864. };
  16865. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  16866. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  16867. return this;
  16868. };
  16869. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  16870. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  16871. return this;
  16872. };
  16873. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  16874. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  16875. return this;
  16876. };
  16877. return ArcRotateCameraInputsManager;
  16878. }(BABYLON.CameraInputsManager));
  16879. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  16880. })(BABYLON || (BABYLON = {}));
  16881. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  16882. var BABYLON;
  16883. (function (BABYLON) {
  16884. var RenderingManager = (function () {
  16885. function RenderingManager(scene) {
  16886. this._renderingGroups = new Array();
  16887. this._autoClearDepthStencil = {};
  16888. this._customOpaqueSortCompareFn = {};
  16889. this._customAlphaTestSortCompareFn = {};
  16890. this._customTransparentSortCompareFn = {};
  16891. this._renderinGroupInfo = null;
  16892. this._scene = scene;
  16893. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16894. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16895. }
  16896. }
  16897. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16898. if (depth === void 0) { depth = true; }
  16899. if (stencil === void 0) { stencil = true; }
  16900. if (this._depthStencilBufferAlreadyCleaned) {
  16901. return;
  16902. }
  16903. this._scene.getEngine().clear(null, false, depth, stencil);
  16904. this._depthStencilBufferAlreadyCleaned = true;
  16905. };
  16906. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16907. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16908. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16909. var info = null;
  16910. if (observable) {
  16911. if (!this._renderinGroupInfo) {
  16912. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16913. }
  16914. info = this._renderinGroupInfo;
  16915. info.scene = this._scene;
  16916. info.camera = this._scene.activeCamera;
  16917. }
  16918. // Dispatch sprites
  16919. if (renderSprites) {
  16920. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16921. var manager = this._scene.spriteManagers[index];
  16922. this.dispatchSprites(manager);
  16923. }
  16924. }
  16925. // Render
  16926. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16927. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16928. var renderingGroup = this._renderingGroups[index];
  16929. if (!renderingGroup && !observable)
  16930. continue;
  16931. this._currentIndex = index;
  16932. var renderingGroupMask = 0;
  16933. // Fire PRECLEAR stage
  16934. if (observable) {
  16935. renderingGroupMask = Math.pow(2, index);
  16936. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16937. info.renderingGroupId = index;
  16938. observable.notifyObservers(info, renderingGroupMask);
  16939. }
  16940. // Clear depth/stencil if needed
  16941. var autoClear = this._autoClearDepthStencil[index];
  16942. if (autoClear && autoClear.autoClear) {
  16943. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16944. }
  16945. if (observable) {
  16946. // Fire PREOPAQUE stage
  16947. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16948. observable.notifyObservers(info, renderingGroupMask);
  16949. // Fire PRETRANSPARENT stage
  16950. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16951. observable.notifyObservers(info, renderingGroupMask);
  16952. }
  16953. if (renderingGroup)
  16954. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16955. // Fire POSTTRANSPARENT stage
  16956. if (observable) {
  16957. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16958. observable.notifyObservers(info, renderingGroupMask);
  16959. }
  16960. }
  16961. };
  16962. RenderingManager.prototype.reset = function () {
  16963. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16964. var renderingGroup = this._renderingGroups[index];
  16965. if (renderingGroup) {
  16966. renderingGroup.prepare();
  16967. }
  16968. }
  16969. };
  16970. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16971. if (!this._renderingGroups[renderingGroupId]) {
  16972. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16973. }
  16974. };
  16975. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16976. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16977. this._prepareRenderingGroup(renderingGroupId);
  16978. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16979. };
  16980. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16981. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16982. this._prepareRenderingGroup(renderingGroupId);
  16983. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16984. };
  16985. RenderingManager.prototype.dispatch = function (subMesh) {
  16986. var mesh = subMesh.getMesh();
  16987. var renderingGroupId = mesh.renderingGroupId || 0;
  16988. this._prepareRenderingGroup(renderingGroupId);
  16989. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16990. };
  16991. /**
  16992. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16993. * This allowed control for front to back rendering or reversly depending of the special needs.
  16994. *
  16995. * @param renderingGroupId The rendering group id corresponding to its index
  16996. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16997. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16998. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16999. */
  17000. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17001. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17002. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17003. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17004. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  17005. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  17006. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  17007. if (this._renderingGroups[renderingGroupId]) {
  17008. var group = this._renderingGroups[renderingGroupId];
  17009. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  17010. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  17011. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  17012. }
  17013. };
  17014. /**
  17015. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  17016. *
  17017. * @param renderingGroupId The rendering group id corresponding to its index
  17018. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  17019. * @param depth Automatically clears depth between groups if true and autoClear is true.
  17020. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  17021. */
  17022. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  17023. if (depth === void 0) { depth = true; }
  17024. if (stencil === void 0) { stencil = true; }
  17025. this._autoClearDepthStencil[renderingGroupId] = {
  17026. autoClear: autoClearDepthStencil,
  17027. depth: depth,
  17028. stencil: stencil
  17029. };
  17030. };
  17031. return RenderingManager;
  17032. }());
  17033. /**
  17034. * The max id used for rendering groups (not included)
  17035. */
  17036. RenderingManager.MAX_RENDERINGGROUPS = 4;
  17037. /**
  17038. * The min id used for rendering groups (included)
  17039. */
  17040. RenderingManager.MIN_RENDERINGGROUPS = 0;
  17041. BABYLON.RenderingManager = RenderingManager;
  17042. })(BABYLON || (BABYLON = {}));
  17043. //# sourceMappingURL=babylon.renderingManager.js.map
  17044. var BABYLON;
  17045. (function (BABYLON) {
  17046. var RenderingGroup = (function () {
  17047. /**
  17048. * Creates a new rendering group.
  17049. * @param index The rendering group index
  17050. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  17051. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  17052. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  17053. */
  17054. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  17055. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  17056. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  17057. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  17058. this.index = index;
  17059. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  17060. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  17061. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  17062. this._particleSystems = new BABYLON.SmartArray(256);
  17063. this._spriteManagers = new BABYLON.SmartArray(256);
  17064. this._scene = scene;
  17065. this.opaqueSortCompareFn = opaqueSortCompareFn;
  17066. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  17067. this.transparentSortCompareFn = transparentSortCompareFn;
  17068. }
  17069. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  17070. /**
  17071. * Set the opaque sort comparison function.
  17072. * If null the sub meshes will be render in the order they were created
  17073. */
  17074. set: function (value) {
  17075. this._opaqueSortCompareFn = value;
  17076. if (value) {
  17077. this._renderOpaque = this.renderOpaqueSorted;
  17078. }
  17079. else {
  17080. this._renderOpaque = RenderingGroup.renderUnsorted;
  17081. }
  17082. },
  17083. enumerable: true,
  17084. configurable: true
  17085. });
  17086. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  17087. /**
  17088. * Set the alpha test sort comparison function.
  17089. * If null the sub meshes will be render in the order they were created
  17090. */
  17091. set: function (value) {
  17092. this._alphaTestSortCompareFn = value;
  17093. if (value) {
  17094. this._renderAlphaTest = this.renderAlphaTestSorted;
  17095. }
  17096. else {
  17097. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  17098. }
  17099. },
  17100. enumerable: true,
  17101. configurable: true
  17102. });
  17103. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  17104. /**
  17105. * Set the transparent sort comparison function.
  17106. * If null the sub meshes will be render in the order they were created
  17107. */
  17108. set: function (value) {
  17109. if (value) {
  17110. this._transparentSortCompareFn = value;
  17111. }
  17112. else {
  17113. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  17114. }
  17115. this._renderTransparent = this.renderTransparentSorted;
  17116. },
  17117. enumerable: true,
  17118. configurable: true
  17119. });
  17120. /**
  17121. * Render all the sub meshes contained in the group.
  17122. * @param customRenderFunction Used to override the default render behaviour of the group.
  17123. * @returns true if rendered some submeshes.
  17124. */
  17125. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  17126. if (customRenderFunction) {
  17127. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  17128. return;
  17129. }
  17130. var engine = this._scene.getEngine();
  17131. // Opaque
  17132. if (this._opaqueSubMeshes.length !== 0) {
  17133. this._renderOpaque(this._opaqueSubMeshes);
  17134. }
  17135. // Alpha test
  17136. if (this._alphaTestSubMeshes.length !== 0) {
  17137. engine.setAlphaTesting(true);
  17138. this._renderAlphaTest(this._alphaTestSubMeshes);
  17139. engine.setAlphaTesting(false);
  17140. }
  17141. // Sprites
  17142. if (renderSprites) {
  17143. this._renderSprites();
  17144. }
  17145. // Particles
  17146. if (renderParticles) {
  17147. this._renderParticles(activeMeshes);
  17148. }
  17149. if (this.onBeforeTransparentRendering) {
  17150. this.onBeforeTransparentRendering();
  17151. }
  17152. // Transparent
  17153. if (this._transparentSubMeshes.length !== 0) {
  17154. this._renderTransparent(this._transparentSubMeshes);
  17155. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  17156. }
  17157. };
  17158. /**
  17159. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  17160. * @param subMeshes The submeshes to render
  17161. */
  17162. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  17163. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  17164. };
  17165. /**
  17166. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  17167. * @param subMeshes The submeshes to render
  17168. */
  17169. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  17170. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  17171. };
  17172. /**
  17173. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  17174. * @param subMeshes The submeshes to render
  17175. */
  17176. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  17177. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  17178. };
  17179. /**
  17180. * Renders the submeshes in a specified order.
  17181. * @param subMeshes The submeshes to sort before render
  17182. * @param sortCompareFn The comparison function use to sort
  17183. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  17184. * @param transparent Specifies to activate blending if true
  17185. */
  17186. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  17187. var subIndex = 0;
  17188. var subMesh;
  17189. for (; subIndex < subMeshes.length; subIndex++) {
  17190. subMesh = subMeshes.data[subIndex];
  17191. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  17192. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  17193. }
  17194. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  17195. sortedArray.sort(sortCompareFn);
  17196. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  17197. subMesh = sortedArray[subIndex];
  17198. subMesh.render(transparent);
  17199. }
  17200. };
  17201. /**
  17202. * Renders the submeshes in the order they were dispatched (no sort applied).
  17203. * @param subMeshes The submeshes to render
  17204. */
  17205. RenderingGroup.renderUnsorted = function (subMeshes) {
  17206. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  17207. var submesh = subMeshes.data[subIndex];
  17208. submesh.render(false);
  17209. }
  17210. };
  17211. /**
  17212. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17213. * are rendered back to front if in the same alpha index.
  17214. *
  17215. * @param a The first submesh
  17216. * @param b The second submesh
  17217. * @returns The result of the comparison
  17218. */
  17219. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  17220. // Alpha index first
  17221. if (a._alphaIndex > b._alphaIndex) {
  17222. return 1;
  17223. }
  17224. if (a._alphaIndex < b._alphaIndex) {
  17225. return -1;
  17226. }
  17227. // Then distance to camera
  17228. return RenderingGroup.backToFrontSortCompare(a, b);
  17229. };
  17230. /**
  17231. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17232. * are rendered back to front.
  17233. *
  17234. * @param a The first submesh
  17235. * @param b The second submesh
  17236. * @returns The result of the comparison
  17237. */
  17238. RenderingGroup.backToFrontSortCompare = function (a, b) {
  17239. // Then distance to camera
  17240. if (a._distanceToCamera < b._distanceToCamera) {
  17241. return 1;
  17242. }
  17243. if (a._distanceToCamera > b._distanceToCamera) {
  17244. return -1;
  17245. }
  17246. return 0;
  17247. };
  17248. /**
  17249. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  17250. * are rendered front to back (prevent overdraw).
  17251. *
  17252. * @param a The first submesh
  17253. * @param b The second submesh
  17254. * @returns The result of the comparison
  17255. */
  17256. RenderingGroup.frontToBackSortCompare = function (a, b) {
  17257. // Then distance to camera
  17258. if (a._distanceToCamera < b._distanceToCamera) {
  17259. return -1;
  17260. }
  17261. if (a._distanceToCamera > b._distanceToCamera) {
  17262. return 1;
  17263. }
  17264. return 0;
  17265. };
  17266. /**
  17267. * Resets the different lists of submeshes to prepare a new frame.
  17268. */
  17269. RenderingGroup.prototype.prepare = function () {
  17270. this._opaqueSubMeshes.reset();
  17271. this._transparentSubMeshes.reset();
  17272. this._alphaTestSubMeshes.reset();
  17273. this._particleSystems.reset();
  17274. this._spriteManagers.reset();
  17275. };
  17276. /**
  17277. * Inserts the submesh in its correct queue depending on its material.
  17278. * @param subMesh The submesh to dispatch
  17279. */
  17280. RenderingGroup.prototype.dispatch = function (subMesh) {
  17281. var material = subMesh.getMaterial();
  17282. var mesh = subMesh.getMesh();
  17283. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  17284. this._transparentSubMeshes.push(subMesh);
  17285. }
  17286. else if (material.needAlphaTesting()) {
  17287. this._alphaTestSubMeshes.push(subMesh);
  17288. }
  17289. else {
  17290. this._opaqueSubMeshes.push(subMesh); // Opaque
  17291. }
  17292. };
  17293. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  17294. this._spriteManagers.push(spriteManager);
  17295. };
  17296. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  17297. this._particleSystems.push(particleSystem);
  17298. };
  17299. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  17300. if (this._particleSystems.length === 0) {
  17301. return;
  17302. }
  17303. // Particles
  17304. var activeCamera = this._scene.activeCamera;
  17305. this._scene._particlesDuration.beginMonitoring();
  17306. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  17307. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  17308. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  17309. continue;
  17310. }
  17311. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  17312. this._scene._activeParticles.addCount(particleSystem.render(), false);
  17313. }
  17314. }
  17315. this._scene._particlesDuration.endMonitoring(false);
  17316. };
  17317. RenderingGroup.prototype._renderSprites = function () {
  17318. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  17319. return;
  17320. }
  17321. // Sprites
  17322. var activeCamera = this._scene.activeCamera;
  17323. this._scene._spritesDuration.beginMonitoring();
  17324. for (var id = 0; id < this._spriteManagers.length; id++) {
  17325. var spriteManager = this._scene.spriteManagers[id];
  17326. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  17327. spriteManager.render();
  17328. }
  17329. }
  17330. this._scene._spritesDuration.endMonitoring(false);
  17331. };
  17332. return RenderingGroup;
  17333. }());
  17334. BABYLON.RenderingGroup = RenderingGroup;
  17335. })(BABYLON || (BABYLON = {}));
  17336. //# sourceMappingURL=babylon.renderingGroup.js.map
  17337. var BABYLON;
  17338. (function (BABYLON) {
  17339. var PointerEventTypes = (function () {
  17340. function PointerEventTypes() {
  17341. }
  17342. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  17343. get: function () {
  17344. return PointerEventTypes._POINTERDOWN;
  17345. },
  17346. enumerable: true,
  17347. configurable: true
  17348. });
  17349. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  17350. get: function () {
  17351. return PointerEventTypes._POINTERUP;
  17352. },
  17353. enumerable: true,
  17354. configurable: true
  17355. });
  17356. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  17357. get: function () {
  17358. return PointerEventTypes._POINTERMOVE;
  17359. },
  17360. enumerable: true,
  17361. configurable: true
  17362. });
  17363. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  17364. get: function () {
  17365. return PointerEventTypes._POINTERWHEEL;
  17366. },
  17367. enumerable: true,
  17368. configurable: true
  17369. });
  17370. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  17371. get: function () {
  17372. return PointerEventTypes._POINTERPICK;
  17373. },
  17374. enumerable: true,
  17375. configurable: true
  17376. });
  17377. return PointerEventTypes;
  17378. }());
  17379. PointerEventTypes._POINTERDOWN = 0x01;
  17380. PointerEventTypes._POINTERUP = 0x02;
  17381. PointerEventTypes._POINTERMOVE = 0x04;
  17382. PointerEventTypes._POINTERWHEEL = 0x08;
  17383. PointerEventTypes._POINTERPICK = 0x10;
  17384. BABYLON.PointerEventTypes = PointerEventTypes;
  17385. var PointerInfoBase = (function () {
  17386. function PointerInfoBase(type, event) {
  17387. this.type = type;
  17388. this.event = event;
  17389. }
  17390. return PointerInfoBase;
  17391. }());
  17392. BABYLON.PointerInfoBase = PointerInfoBase;
  17393. /**
  17394. * This class is used to store pointer related info for the onPrePointerObservable event.
  17395. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  17396. */
  17397. var PointerInfoPre = (function (_super) {
  17398. __extends(PointerInfoPre, _super);
  17399. function PointerInfoPre(type, event, localX, localY) {
  17400. var _this = _super.call(this, type, event) || this;
  17401. _this.skipOnPointerObservable = false;
  17402. _this.localPosition = new BABYLON.Vector2(localX, localY);
  17403. return _this;
  17404. }
  17405. return PointerInfoPre;
  17406. }(PointerInfoBase));
  17407. BABYLON.PointerInfoPre = PointerInfoPre;
  17408. /**
  17409. * This type contains all the data related to a pointer event in Babylon.js.
  17410. * 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.
  17411. */
  17412. var PointerInfo = (function (_super) {
  17413. __extends(PointerInfo, _super);
  17414. function PointerInfo(type, event, pickInfo) {
  17415. var _this = _super.call(this, type, event) || this;
  17416. _this.pickInfo = pickInfo;
  17417. return _this;
  17418. }
  17419. return PointerInfo;
  17420. }(PointerInfoBase));
  17421. BABYLON.PointerInfo = PointerInfo;
  17422. /**
  17423. * This class is used by the onRenderingGroupObservable
  17424. */
  17425. var RenderingGroupInfo = (function () {
  17426. function RenderingGroupInfo() {
  17427. }
  17428. return RenderingGroupInfo;
  17429. }());
  17430. /**
  17431. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  17432. * This stage will be fired no matter what
  17433. */
  17434. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  17435. /**
  17436. * Called before opaque object are rendered.
  17437. * This stage will be fired only if there's 3D Opaque content to render
  17438. */
  17439. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  17440. /**
  17441. * Called after the opaque objects are rendered and before the transparent ones
  17442. * This stage will be fired only if there's 3D transparent content to render
  17443. */
  17444. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  17445. /**
  17446. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  17447. * This stage will be fired no matter what
  17448. */
  17449. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  17450. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  17451. /**
  17452. * Represents a scene to be rendered by the engine.
  17453. * @see http://doc.babylonjs.com/page.php?p=21911
  17454. */
  17455. var Scene = (function () {
  17456. /**
  17457. * @constructor
  17458. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  17459. */
  17460. function Scene(engine) {
  17461. // Members
  17462. this.autoClear = true;
  17463. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  17464. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  17465. this.forceWireframe = false;
  17466. this.forcePointsCloud = false;
  17467. this.forceShowBoundingBoxes = false;
  17468. this.animationsEnabled = true;
  17469. this.constantlyUpdateMeshUnderPointer = false;
  17470. this.useRightHandedSystem = false;
  17471. this.hoverCursor = "pointer";
  17472. // Metadata
  17473. this.metadata = null;
  17474. // Events
  17475. /**
  17476. * An event triggered when the scene is disposed.
  17477. * @type {BABYLON.Observable}
  17478. */
  17479. this.onDisposeObservable = new BABYLON.Observable();
  17480. /**
  17481. * An event triggered before rendering the scene
  17482. * @type {BABYLON.Observable}
  17483. */
  17484. this.onBeforeRenderObservable = new BABYLON.Observable();
  17485. /**
  17486. * An event triggered after rendering the scene
  17487. * @type {BABYLON.Observable}
  17488. */
  17489. this.onAfterRenderObservable = new BABYLON.Observable();
  17490. /**
  17491. * An event triggered when the scene is ready
  17492. * @type {BABYLON.Observable}
  17493. */
  17494. this.onReadyObservable = new BABYLON.Observable();
  17495. /**
  17496. * An event triggered before rendering a camera
  17497. * @type {BABYLON.Observable}
  17498. */
  17499. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  17500. /**
  17501. * An event triggered after rendering a camera
  17502. * @type {BABYLON.Observable}
  17503. */
  17504. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  17505. /**
  17506. * An event triggered when a camera is created
  17507. * @type {BABYLON.Observable}
  17508. */
  17509. this.onNewCameraAddedObservable = new BABYLON.Observable();
  17510. /**
  17511. * An event triggered when a camera is removed
  17512. * @type {BABYLON.Observable}
  17513. */
  17514. this.onCameraRemovedObservable = new BABYLON.Observable();
  17515. /**
  17516. * An event triggered when a light is created
  17517. * @type {BABYLON.Observable}
  17518. */
  17519. this.onNewLightAddedObservable = new BABYLON.Observable();
  17520. /**
  17521. * An event triggered when a light is removed
  17522. * @type {BABYLON.Observable}
  17523. */
  17524. this.onLightRemovedObservable = new BABYLON.Observable();
  17525. /**
  17526. * An event triggered when a geometry is created
  17527. * @type {BABYLON.Observable}
  17528. */
  17529. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  17530. /**
  17531. * An event triggered when a geometry is removed
  17532. * @type {BABYLON.Observable}
  17533. */
  17534. this.onGeometryRemovedObservable = new BABYLON.Observable();
  17535. /**
  17536. * An event triggered when a mesh is created
  17537. * @type {BABYLON.Observable}
  17538. */
  17539. this.onNewMeshAddedObservable = new BABYLON.Observable();
  17540. /**
  17541. * An event triggered when a mesh is removed
  17542. * @type {BABYLON.Observable}
  17543. */
  17544. this.onMeshRemovedObservable = new BABYLON.Observable();
  17545. /**
  17546. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  17547. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  17548. * 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)
  17549. */
  17550. this.onRenderingGroupObservable = new BABYLON.Observable();
  17551. // Animations
  17552. this.animations = [];
  17553. /**
  17554. * 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).
  17555. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  17556. */
  17557. this.onPrePointerObservable = new BABYLON.Observable();
  17558. /**
  17559. * Observable event triggered each time an input event is received from the rendering canvas
  17560. */
  17561. this.onPointerObservable = new BABYLON.Observable();
  17562. 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
  17563. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  17564. this._startingPointerTime = 0;
  17565. // Fog
  17566. /**
  17567. * is fog enabled on this scene.
  17568. * @type {boolean}
  17569. */
  17570. this.fogEnabled = true;
  17571. this.fogMode = Scene.FOGMODE_NONE;
  17572. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  17573. this.fogDensity = 0.1;
  17574. this.fogStart = 0;
  17575. this.fogEnd = 1000.0;
  17576. // Lights
  17577. /**
  17578. * is shadow enabled on this scene.
  17579. * @type {boolean}
  17580. */
  17581. this.shadowsEnabled = true;
  17582. /**
  17583. * is light enabled on this scene.
  17584. * @type {boolean}
  17585. */
  17586. this.lightsEnabled = true;
  17587. /**
  17588. * All of the lights added to this scene.
  17589. * @see BABYLON.Light
  17590. * @type {BABYLON.Light[]}
  17591. */
  17592. this.lights = new Array();
  17593. // Cameras
  17594. /**
  17595. * All of the cameras added to this scene.
  17596. * @see BABYLON.Camera
  17597. * @type {BABYLON.Camera[]}
  17598. */
  17599. this.cameras = new Array();
  17600. this.activeCameras = new Array();
  17601. // Meshes
  17602. /**
  17603. * All of the (abstract) meshes added to this scene.
  17604. * @see BABYLON.AbstractMesh
  17605. * @type {BABYLON.AbstractMesh[]}
  17606. */
  17607. this.meshes = new Array();
  17608. // Geometries
  17609. this._geometries = new Array();
  17610. this.materials = new Array();
  17611. this.multiMaterials = new Array();
  17612. // Textures
  17613. this.texturesEnabled = true;
  17614. this.textures = new Array();
  17615. // Particles
  17616. this.particlesEnabled = true;
  17617. this.particleSystems = new Array();
  17618. // Sprites
  17619. this.spritesEnabled = true;
  17620. this.spriteManagers = new Array();
  17621. // Layers
  17622. this.layers = new Array();
  17623. this.highlightLayers = new Array();
  17624. // Skeletons
  17625. this.skeletonsEnabled = true;
  17626. this.skeletons = new Array();
  17627. // Lens flares
  17628. this.lensFlaresEnabled = true;
  17629. this.lensFlareSystems = new Array();
  17630. // Collisions
  17631. this.collisionsEnabled = true;
  17632. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  17633. // Postprocesses
  17634. this.postProcessesEnabled = true;
  17635. // Customs render targets
  17636. this.renderTargetsEnabled = true;
  17637. this.dumpNextRenderTargets = false;
  17638. this.customRenderTargets = new Array();
  17639. // Imported meshes
  17640. this.importedMeshesFiles = new Array();
  17641. // Probes
  17642. this.probesEnabled = true;
  17643. this.reflectionProbes = new Array();
  17644. this._actionManagers = new Array();
  17645. this._meshesForIntersections = new BABYLON.SmartArray(256);
  17646. // Procedural textures
  17647. this.proceduralTexturesEnabled = true;
  17648. this._proceduralTextures = new Array();
  17649. this.soundTracks = new Array();
  17650. this._audioEnabled = true;
  17651. this._headphone = false;
  17652. // Performance counters
  17653. this._totalMeshesCounter = new BABYLON.PerfCounter();
  17654. this._totalLightsCounter = new BABYLON.PerfCounter();
  17655. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  17656. this._totalTexturesCounter = new BABYLON.PerfCounter();
  17657. this._totalVertices = new BABYLON.PerfCounter();
  17658. this._activeIndices = new BABYLON.PerfCounter();
  17659. this._activeParticles = new BABYLON.PerfCounter();
  17660. this._lastFrameDuration = new BABYLON.PerfCounter();
  17661. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  17662. this._renderTargetsDuration = new BABYLON.PerfCounter();
  17663. this._particlesDuration = new BABYLON.PerfCounter();
  17664. this._renderDuration = new BABYLON.PerfCounter();
  17665. this._spritesDuration = new BABYLON.PerfCounter();
  17666. this._activeBones = new BABYLON.PerfCounter();
  17667. this._animationTime = 0;
  17668. this.animationTimeScale = 1;
  17669. this._renderId = 0;
  17670. this._executeWhenReadyTimeoutId = -1;
  17671. this._intermediateRendering = false;
  17672. this._toBeDisposed = new BABYLON.SmartArray(256);
  17673. this._pendingData = []; //ANY
  17674. this._activeMeshes = new BABYLON.SmartArray(256);
  17675. this._processedMaterials = new BABYLON.SmartArray(256);
  17676. this._renderTargets = new BABYLON.SmartArray(256);
  17677. this._activeParticleSystems = new BABYLON.SmartArray(256);
  17678. this._activeSkeletons = new BABYLON.SmartArray(32);
  17679. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  17680. this._activeAnimatables = new Array();
  17681. this._transformMatrix = BABYLON.Matrix.Zero();
  17682. this._edgesRenderers = new BABYLON.SmartArray(16);
  17683. this._uniqueIdCounter = 0;
  17684. this._engine = engine;
  17685. engine.scenes.push(this);
  17686. this._externalData = new BABYLON.StringDictionary();
  17687. this._uid = null;
  17688. this._renderingManager = new BABYLON.RenderingManager(this);
  17689. this.postProcessManager = new BABYLON.PostProcessManager(this);
  17690. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  17691. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  17692. if (BABYLON.OutlineRenderer) {
  17693. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  17694. }
  17695. this.attachControl();
  17696. if (BABYLON.SoundTrack) {
  17697. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  17698. }
  17699. //simplification queue
  17700. if (BABYLON.SimplificationQueue) {
  17701. this.simplificationQueue = new BABYLON.SimplificationQueue();
  17702. }
  17703. //collision coordinator initialization. For now legacy per default.
  17704. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  17705. }
  17706. Object.defineProperty(Scene, "FOGMODE_NONE", {
  17707. get: function () {
  17708. return Scene._FOGMODE_NONE;
  17709. },
  17710. enumerable: true,
  17711. configurable: true
  17712. });
  17713. Object.defineProperty(Scene, "FOGMODE_EXP", {
  17714. get: function () {
  17715. return Scene._FOGMODE_EXP;
  17716. },
  17717. enumerable: true,
  17718. configurable: true
  17719. });
  17720. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  17721. get: function () {
  17722. return Scene._FOGMODE_EXP2;
  17723. },
  17724. enumerable: true,
  17725. configurable: true
  17726. });
  17727. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  17728. get: function () {
  17729. return Scene._FOGMODE_LINEAR;
  17730. },
  17731. enumerable: true,
  17732. configurable: true
  17733. });
  17734. Object.defineProperty(Scene.prototype, "onDispose", {
  17735. set: function (callback) {
  17736. if (this._onDisposeObserver) {
  17737. this.onDisposeObservable.remove(this._onDisposeObserver);
  17738. }
  17739. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17740. },
  17741. enumerable: true,
  17742. configurable: true
  17743. });
  17744. Object.defineProperty(Scene.prototype, "beforeRender", {
  17745. set: function (callback) {
  17746. if (this._onBeforeRenderObserver) {
  17747. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  17748. }
  17749. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  17750. },
  17751. enumerable: true,
  17752. configurable: true
  17753. });
  17754. Object.defineProperty(Scene.prototype, "afterRender", {
  17755. set: function (callback) {
  17756. if (this._onAfterRenderObserver) {
  17757. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  17758. }
  17759. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  17760. },
  17761. enumerable: true,
  17762. configurable: true
  17763. });
  17764. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  17765. set: function (callback) {
  17766. if (this._onBeforeCameraRenderObserver) {
  17767. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  17768. }
  17769. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  17770. },
  17771. enumerable: true,
  17772. configurable: true
  17773. });
  17774. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  17775. set: function (callback) {
  17776. if (this._onAfterCameraRenderObserver) {
  17777. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  17778. }
  17779. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  17780. },
  17781. enumerable: true,
  17782. configurable: true
  17783. });
  17784. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  17785. get: function () {
  17786. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  17787. },
  17788. enumerable: true,
  17789. configurable: true
  17790. });
  17791. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  17792. get: function () {
  17793. if (!this._defaultMaterial) {
  17794. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  17795. }
  17796. return this._defaultMaterial;
  17797. },
  17798. enumerable: true,
  17799. configurable: true
  17800. });
  17801. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  17802. get: function () {
  17803. return this._frustumPlanes;
  17804. },
  17805. enumerable: true,
  17806. configurable: true
  17807. });
  17808. Object.defineProperty(Scene.prototype, "debugLayer", {
  17809. // Properties
  17810. get: function () {
  17811. if (!this._debugLayer) {
  17812. this._debugLayer = new BABYLON.DebugLayer(this);
  17813. }
  17814. return this._debugLayer;
  17815. },
  17816. enumerable: true,
  17817. configurable: true
  17818. });
  17819. Object.defineProperty(Scene.prototype, "workerCollisions", {
  17820. get: function () {
  17821. return this._workerCollisions;
  17822. },
  17823. set: function (enabled) {
  17824. enabled = (enabled && !!Worker);
  17825. this._workerCollisions = enabled;
  17826. if (this.collisionCoordinator) {
  17827. this.collisionCoordinator.destroy();
  17828. }
  17829. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  17830. this.collisionCoordinator.init(this);
  17831. },
  17832. enumerable: true,
  17833. configurable: true
  17834. });
  17835. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  17836. get: function () {
  17837. return this._selectionOctree;
  17838. },
  17839. enumerable: true,
  17840. configurable: true
  17841. });
  17842. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  17843. /**
  17844. * The mesh that is currently under the pointer.
  17845. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17846. */
  17847. get: function () {
  17848. return this._pointerOverMesh;
  17849. },
  17850. enumerable: true,
  17851. configurable: true
  17852. });
  17853. Object.defineProperty(Scene.prototype, "pointerX", {
  17854. /**
  17855. * Current on-screen X position of the pointer
  17856. * @return {number} X position of the pointer
  17857. */
  17858. get: function () {
  17859. return this._pointerX;
  17860. },
  17861. enumerable: true,
  17862. configurable: true
  17863. });
  17864. Object.defineProperty(Scene.prototype, "pointerY", {
  17865. /**
  17866. * Current on-screen Y position of the pointer
  17867. * @return {number} Y position of the pointer
  17868. */
  17869. get: function () {
  17870. return this._pointerY;
  17871. },
  17872. enumerable: true,
  17873. configurable: true
  17874. });
  17875. Scene.prototype.getCachedMaterial = function () {
  17876. return this._cachedMaterial;
  17877. };
  17878. Scene.prototype.getBoundingBoxRenderer = function () {
  17879. return this._boundingBoxRenderer;
  17880. };
  17881. Scene.prototype.getOutlineRenderer = function () {
  17882. return this._outlineRenderer;
  17883. };
  17884. Scene.prototype.getEngine = function () {
  17885. return this._engine;
  17886. };
  17887. Scene.prototype.getTotalVertices = function () {
  17888. return this._totalVertices.current;
  17889. };
  17890. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17891. get: function () {
  17892. return this._totalVertices;
  17893. },
  17894. enumerable: true,
  17895. configurable: true
  17896. });
  17897. Scene.prototype.getActiveIndices = function () {
  17898. return this._activeIndices.current;
  17899. };
  17900. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17901. get: function () {
  17902. return this._activeIndices;
  17903. },
  17904. enumerable: true,
  17905. configurable: true
  17906. });
  17907. Scene.prototype.getActiveParticles = function () {
  17908. return this._activeParticles.current;
  17909. };
  17910. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17911. get: function () {
  17912. return this._activeParticles;
  17913. },
  17914. enumerable: true,
  17915. configurable: true
  17916. });
  17917. Scene.prototype.getActiveBones = function () {
  17918. return this._activeBones.current;
  17919. };
  17920. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17921. get: function () {
  17922. return this._activeBones;
  17923. },
  17924. enumerable: true,
  17925. configurable: true
  17926. });
  17927. // Stats
  17928. Scene.prototype.getLastFrameDuration = function () {
  17929. return this._lastFrameDuration.current;
  17930. };
  17931. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17932. get: function () {
  17933. return this._lastFrameDuration;
  17934. },
  17935. enumerable: true,
  17936. configurable: true
  17937. });
  17938. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17939. return this._evaluateActiveMeshesDuration.current;
  17940. };
  17941. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17942. get: function () {
  17943. return this._evaluateActiveMeshesDuration;
  17944. },
  17945. enumerable: true,
  17946. configurable: true
  17947. });
  17948. Scene.prototype.getActiveMeshes = function () {
  17949. return this._activeMeshes;
  17950. };
  17951. Scene.prototype.getRenderTargetsDuration = function () {
  17952. return this._renderTargetsDuration.current;
  17953. };
  17954. Scene.prototype.getRenderDuration = function () {
  17955. return this._renderDuration.current;
  17956. };
  17957. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17958. get: function () {
  17959. return this._renderDuration;
  17960. },
  17961. enumerable: true,
  17962. configurable: true
  17963. });
  17964. Scene.prototype.getParticlesDuration = function () {
  17965. return this._particlesDuration.current;
  17966. };
  17967. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17968. get: function () {
  17969. return this._particlesDuration;
  17970. },
  17971. enumerable: true,
  17972. configurable: true
  17973. });
  17974. Scene.prototype.getSpritesDuration = function () {
  17975. return this._spritesDuration.current;
  17976. };
  17977. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17978. get: function () {
  17979. return this._spritesDuration;
  17980. },
  17981. enumerable: true,
  17982. configurable: true
  17983. });
  17984. Scene.prototype.getAnimationRatio = function () {
  17985. return this._animationRatio;
  17986. };
  17987. Scene.prototype.getRenderId = function () {
  17988. return this._renderId;
  17989. };
  17990. Scene.prototype.incrementRenderId = function () {
  17991. this._renderId++;
  17992. };
  17993. Scene.prototype._updatePointerPosition = function (evt) {
  17994. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17995. this._pointerX = evt.clientX - canvasRect.left;
  17996. this._pointerY = evt.clientY - canvasRect.top;
  17997. this._unTranslatedPointerX = this._pointerX;
  17998. this._unTranslatedPointerY = this._pointerY;
  17999. if (this.cameraToUseForPointers) {
  18000. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  18001. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  18002. }
  18003. };
  18004. // Pointers handling
  18005. /**
  18006. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  18007. * @param attachUp defines if you want to attach events to pointerup
  18008. * @param attachDown defines if you want to attach events to pointerdown
  18009. * @param attachMove defines if you want to attach events to pointermove
  18010. */
  18011. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  18012. var _this = this;
  18013. if (attachUp === void 0) { attachUp = true; }
  18014. if (attachDown === void 0) { attachDown = true; }
  18015. if (attachMove === void 0) { attachMove = true; }
  18016. var spritePredicate = function (sprite) {
  18017. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  18018. };
  18019. this._onPointerMove = function (evt) {
  18020. _this._updatePointerPosition(evt);
  18021. // PreObservable support
  18022. if (_this.onPrePointerObservable.hasObservers()) {
  18023. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  18024. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18025. _this.onPrePointerObservable.notifyObservers(pi, type);
  18026. if (pi.skipOnPointerObservable) {
  18027. return;
  18028. }
  18029. }
  18030. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18031. return;
  18032. }
  18033. var canvas = _this._engine.getRenderingCanvas();
  18034. if (!_this.pointerMovePredicate) {
  18035. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  18036. }
  18037. // Meshes
  18038. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  18039. if (pickResult.hit && pickResult.pickedMesh) {
  18040. _this.setPointerOverSprite(null);
  18041. _this.setPointerOverMesh(pickResult.pickedMesh);
  18042. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  18043. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  18044. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  18045. }
  18046. else {
  18047. canvas.style.cursor = _this.hoverCursor;
  18048. }
  18049. }
  18050. else {
  18051. canvas.style.cursor = "";
  18052. }
  18053. }
  18054. else {
  18055. _this.setPointerOverMesh(null);
  18056. // Sprites
  18057. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  18058. if (pickResult.hit && pickResult.pickedSprite) {
  18059. _this.setPointerOverSprite(pickResult.pickedSprite);
  18060. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  18061. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  18062. }
  18063. else {
  18064. canvas.style.cursor = _this.hoverCursor;
  18065. }
  18066. }
  18067. else {
  18068. _this.setPointerOverSprite(null);
  18069. // Restore pointer
  18070. canvas.style.cursor = "";
  18071. }
  18072. }
  18073. if (_this.onPointerMove) {
  18074. _this.onPointerMove(evt, pickResult);
  18075. }
  18076. if (_this.onPointerObservable.hasObservers()) {
  18077. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  18078. var pi = new PointerInfo(type, evt, pickResult);
  18079. _this.onPointerObservable.notifyObservers(pi, type);
  18080. }
  18081. };
  18082. this._onPointerDown = function (evt) {
  18083. _this._updatePointerPosition(evt);
  18084. // PreObservable support
  18085. if (_this.onPrePointerObservable.hasObservers()) {
  18086. var type = PointerEventTypes.POINTERDOWN;
  18087. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18088. _this.onPrePointerObservable.notifyObservers(pi, type);
  18089. if (pi.skipOnPointerObservable) {
  18090. return;
  18091. }
  18092. }
  18093. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18094. return;
  18095. }
  18096. _this._startingPointerPosition.x = _this._pointerX;
  18097. _this._startingPointerPosition.y = _this._pointerY;
  18098. _this._startingPointerTime = new Date().getTime();
  18099. if (!_this.pointerDownPredicate) {
  18100. _this.pointerDownPredicate = function (mesh) {
  18101. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  18102. };
  18103. }
  18104. // Meshes
  18105. _this._pickedDownMesh = null;
  18106. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  18107. if (pickResult.hit && pickResult.pickedMesh) {
  18108. if (pickResult.pickedMesh.actionManager) {
  18109. _this._pickedDownMesh = pickResult.pickedMesh;
  18110. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  18111. switch (evt.button) {
  18112. case 0:
  18113. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18114. break;
  18115. case 1:
  18116. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18117. break;
  18118. case 2:
  18119. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18120. break;
  18121. }
  18122. if (pickResult.pickedMesh.actionManager) {
  18123. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18124. }
  18125. }
  18126. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  18127. var that = _this;
  18128. window.setTimeout(function () {
  18129. 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);
  18130. if (pickResult.hit && pickResult.pickedMesh) {
  18131. if (pickResult.pickedMesh.actionManager) {
  18132. 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)) {
  18133. that._startingPointerTime = 0;
  18134. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18135. }
  18136. }
  18137. }
  18138. }, BABYLON.ActionManager.LongPressDelay);
  18139. }
  18140. }
  18141. }
  18142. if (_this.onPointerDown) {
  18143. _this.onPointerDown(evt, pickResult);
  18144. }
  18145. if (_this.onPointerObservable.hasObservers()) {
  18146. var type = PointerEventTypes.POINTERDOWN;
  18147. var pi = new PointerInfo(type, evt, pickResult);
  18148. _this.onPointerObservable.notifyObservers(pi, type);
  18149. }
  18150. // Sprites
  18151. _this._pickedDownSprite = null;
  18152. if (_this.spriteManagers.length > 0) {
  18153. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  18154. if (pickResult.hit && pickResult.pickedSprite) {
  18155. if (pickResult.pickedSprite.actionManager) {
  18156. _this._pickedDownSprite = pickResult.pickedSprite;
  18157. switch (evt.button) {
  18158. case 0:
  18159. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18160. break;
  18161. case 1:
  18162. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18163. break;
  18164. case 2:
  18165. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18166. break;
  18167. }
  18168. if (pickResult.pickedSprite.actionManager) {
  18169. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18170. }
  18171. }
  18172. }
  18173. }
  18174. };
  18175. this._onPointerUp = function (evt) {
  18176. _this._updatePointerPosition(evt);
  18177. // PreObservable support
  18178. if (_this.onPrePointerObservable.hasObservers()) {
  18179. var type = PointerEventTypes.POINTERUP;
  18180. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  18181. _this.onPrePointerObservable.notifyObservers(pi, type);
  18182. if (pi.skipOnPointerObservable) {
  18183. return;
  18184. }
  18185. }
  18186. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  18187. return;
  18188. }
  18189. if (!_this.pointerUpPredicate) {
  18190. _this.pointerUpPredicate = function (mesh) {
  18191. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  18192. };
  18193. }
  18194. // Meshes
  18195. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  18196. if (pickResult.hit && pickResult.pickedMesh) {
  18197. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  18198. if (_this.onPointerPick) {
  18199. _this.onPointerPick(evt, pickResult);
  18200. }
  18201. if (_this.onPointerObservable.hasObservers()) {
  18202. var type = PointerEventTypes.POINTERPICK;
  18203. var pi = new PointerInfo(type, evt, pickResult);
  18204. _this.onPointerObservable.notifyObservers(pi, type);
  18205. }
  18206. }
  18207. if (pickResult.pickedMesh.actionManager) {
  18208. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18209. if (pickResult.pickedMesh.actionManager) {
  18210. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  18211. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  18212. }
  18213. }
  18214. }
  18215. }
  18216. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  18217. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  18218. }
  18219. if (_this.onPointerUp) {
  18220. _this.onPointerUp(evt, pickResult);
  18221. }
  18222. if (_this.onPointerObservable.hasObservers()) {
  18223. var type = PointerEventTypes.POINTERUP;
  18224. var pi = new PointerInfo(type, evt, pickResult);
  18225. _this.onPointerObservable.notifyObservers(pi, type);
  18226. }
  18227. _this._startingPointerTime = 0;
  18228. // Sprites
  18229. if (_this.spriteManagers.length > 0) {
  18230. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  18231. if (pickResult.hit && pickResult.pickedSprite) {
  18232. if (pickResult.pickedSprite.actionManager) {
  18233. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18234. if (pickResult.pickedSprite.actionManager) {
  18235. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  18236. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  18237. }
  18238. }
  18239. }
  18240. }
  18241. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  18242. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  18243. }
  18244. }
  18245. };
  18246. this._onKeyDown = function (evt) {
  18247. if (_this.actionManager) {
  18248. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18249. }
  18250. };
  18251. this._onKeyUp = function (evt) {
  18252. if (_this.actionManager) {
  18253. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  18254. }
  18255. };
  18256. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18257. var canvas = this._engine.getRenderingCanvas();
  18258. if (attachMove) {
  18259. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  18260. // Wheel
  18261. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  18262. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  18263. }
  18264. if (attachDown) {
  18265. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  18266. }
  18267. if (attachUp) {
  18268. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  18269. }
  18270. canvas.tabIndex = 1;
  18271. canvas.addEventListener("keydown", this._onKeyDown, false);
  18272. canvas.addEventListener("keyup", this._onKeyUp, false);
  18273. };
  18274. Scene.prototype.detachControl = function () {
  18275. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  18276. var canvas = this._engine.getRenderingCanvas();
  18277. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  18278. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  18279. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  18280. // Wheel
  18281. canvas.removeEventListener('mousewheel', this._onPointerMove);
  18282. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  18283. canvas.removeEventListener("keydown", this._onKeyDown);
  18284. canvas.removeEventListener("keyup", this._onKeyUp);
  18285. };
  18286. // Ready
  18287. Scene.prototype.isReady = function () {
  18288. if (this._pendingData.length > 0) {
  18289. return false;
  18290. }
  18291. var index;
  18292. for (index = 0; index < this._geometries.length; index++) {
  18293. var geometry = this._geometries[index];
  18294. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  18295. return false;
  18296. }
  18297. }
  18298. for (index = 0; index < this.meshes.length; index++) {
  18299. var mesh = this.meshes[index];
  18300. if (!mesh.isReady()) {
  18301. return false;
  18302. }
  18303. var mat = mesh.material;
  18304. if (mat) {
  18305. if (!mat.isReady(mesh)) {
  18306. return false;
  18307. }
  18308. }
  18309. }
  18310. return true;
  18311. };
  18312. Scene.prototype.resetCachedMaterial = function () {
  18313. this._cachedMaterial = null;
  18314. };
  18315. Scene.prototype.registerBeforeRender = function (func) {
  18316. this.onBeforeRenderObservable.add(func);
  18317. };
  18318. Scene.prototype.unregisterBeforeRender = function (func) {
  18319. this.onBeforeRenderObservable.removeCallback(func);
  18320. };
  18321. Scene.prototype.registerAfterRender = function (func) {
  18322. this.onAfterRenderObservable.add(func);
  18323. };
  18324. Scene.prototype.unregisterAfterRender = function (func) {
  18325. this.onAfterRenderObservable.removeCallback(func);
  18326. };
  18327. Scene.prototype._addPendingData = function (data) {
  18328. this._pendingData.push(data);
  18329. };
  18330. Scene.prototype._removePendingData = function (data) {
  18331. var index = this._pendingData.indexOf(data);
  18332. if (index !== -1) {
  18333. this._pendingData.splice(index, 1);
  18334. }
  18335. };
  18336. Scene.prototype.getWaitingItemsCount = function () {
  18337. return this._pendingData.length;
  18338. };
  18339. /**
  18340. * Registers a function to be executed when the scene is ready.
  18341. * @param {Function} func - the function to be executed.
  18342. */
  18343. Scene.prototype.executeWhenReady = function (func) {
  18344. var _this = this;
  18345. this.onReadyObservable.add(func);
  18346. if (this._executeWhenReadyTimeoutId !== -1) {
  18347. return;
  18348. }
  18349. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18350. _this._checkIsReady();
  18351. }, 150);
  18352. };
  18353. Scene.prototype._checkIsReady = function () {
  18354. var _this = this;
  18355. if (this.isReady()) {
  18356. this.onReadyObservable.notifyObservers(this);
  18357. this.onReadyObservable.clear();
  18358. this._executeWhenReadyTimeoutId = -1;
  18359. return;
  18360. }
  18361. this._executeWhenReadyTimeoutId = setTimeout(function () {
  18362. _this._checkIsReady();
  18363. }, 150);
  18364. };
  18365. // Animations
  18366. /**
  18367. * Will start the animation sequence of a given target
  18368. * @param target - the target
  18369. * @param {number} from - from which frame should animation start
  18370. * @param {number} to - till which frame should animation run.
  18371. * @param {boolean} [loop] - should the animation loop
  18372. * @param {number} [speedRatio] - the speed in which to run the animation
  18373. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  18374. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  18375. * @return {BABYLON.Animatable} the animatable object created for this animation
  18376. * @see BABYLON.Animatable
  18377. * @see http://doc.babylonjs.com/page.php?p=22081
  18378. */
  18379. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  18380. if (speedRatio === void 0) { speedRatio = 1.0; }
  18381. this.stopAnimation(target);
  18382. if (!animatable) {
  18383. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  18384. }
  18385. // Local animations
  18386. if (target.animations) {
  18387. animatable.appendAnimations(target, target.animations);
  18388. }
  18389. // Children animations
  18390. if (target.getAnimatables) {
  18391. var animatables = target.getAnimatables();
  18392. for (var index = 0; index < animatables.length; index++) {
  18393. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  18394. }
  18395. }
  18396. animatable.reset();
  18397. return animatable;
  18398. };
  18399. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  18400. if (speedRatio === undefined) {
  18401. speedRatio = 1.0;
  18402. }
  18403. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  18404. return animatable;
  18405. };
  18406. Scene.prototype.getAnimatableByTarget = function (target) {
  18407. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18408. if (this._activeAnimatables[index].target === target) {
  18409. return this._activeAnimatables[index];
  18410. }
  18411. }
  18412. return null;
  18413. };
  18414. Object.defineProperty(Scene.prototype, "Animatables", {
  18415. get: function () {
  18416. return this._activeAnimatables;
  18417. },
  18418. enumerable: true,
  18419. configurable: true
  18420. });
  18421. /**
  18422. * Will stop the animation of the given target
  18423. * @param target - the target
  18424. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  18425. * @see beginAnimation
  18426. */
  18427. Scene.prototype.stopAnimation = function (target, animationName) {
  18428. var animatable = this.getAnimatableByTarget(target);
  18429. if (animatable) {
  18430. animatable.stop(animationName);
  18431. }
  18432. };
  18433. Scene.prototype._animate = function () {
  18434. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  18435. return;
  18436. }
  18437. // Getting time
  18438. var now = BABYLON.Tools.Now;
  18439. if (!this._animationTimeLast) {
  18440. if (this._pendingData.length > 0) {
  18441. return;
  18442. }
  18443. this._animationTimeLast = now;
  18444. }
  18445. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  18446. this._animationTime += deltaTime;
  18447. this._animationTimeLast = now;
  18448. for (var index = 0; index < this._activeAnimatables.length; index++) {
  18449. this._activeAnimatables[index]._animate(this._animationTime);
  18450. }
  18451. };
  18452. // Matrix
  18453. Scene.prototype.getViewMatrix = function () {
  18454. return this._viewMatrix;
  18455. };
  18456. Scene.prototype.getProjectionMatrix = function () {
  18457. return this._projectionMatrix;
  18458. };
  18459. Scene.prototype.getTransformMatrix = function () {
  18460. return this._transformMatrix;
  18461. };
  18462. Scene.prototype.setTransformMatrix = function (view, projection) {
  18463. this._viewMatrix = view;
  18464. this._projectionMatrix = projection;
  18465. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  18466. // Update frustum
  18467. if (!this._frustumPlanes) {
  18468. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  18469. }
  18470. else {
  18471. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  18472. }
  18473. };
  18474. // Methods
  18475. Scene.prototype.addMesh = function (newMesh) {
  18476. newMesh.uniqueId = this._uniqueIdCounter++;
  18477. var position = this.meshes.push(newMesh);
  18478. //notify the collision coordinator
  18479. this.collisionCoordinator.onMeshAdded(newMesh);
  18480. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  18481. };
  18482. Scene.prototype.removeMesh = function (toRemove) {
  18483. var index = this.meshes.indexOf(toRemove);
  18484. if (index !== -1) {
  18485. // Remove from the scene if mesh found
  18486. this.meshes.splice(index, 1);
  18487. }
  18488. //notify the collision coordinator
  18489. this.collisionCoordinator.onMeshRemoved(toRemove);
  18490. this.onMeshRemovedObservable.notifyObservers(toRemove);
  18491. return index;
  18492. };
  18493. Scene.prototype.removeSkeleton = function (toRemove) {
  18494. var index = this.skeletons.indexOf(toRemove);
  18495. if (index !== -1) {
  18496. // Remove from the scene if mesh found
  18497. this.skeletons.splice(index, 1);
  18498. }
  18499. return index;
  18500. };
  18501. Scene.prototype.removeLight = function (toRemove) {
  18502. var index = this.lights.indexOf(toRemove);
  18503. if (index !== -1) {
  18504. // Remove from the scene if mesh found
  18505. this.lights.splice(index, 1);
  18506. }
  18507. this.onLightRemovedObservable.notifyObservers(toRemove);
  18508. return index;
  18509. };
  18510. Scene.prototype.removeCamera = function (toRemove) {
  18511. var index = this.cameras.indexOf(toRemove);
  18512. if (index !== -1) {
  18513. // Remove from the scene if mesh found
  18514. this.cameras.splice(index, 1);
  18515. }
  18516. // Remove from activeCameras
  18517. var index2 = this.activeCameras.indexOf(toRemove);
  18518. if (index2 !== -1) {
  18519. // Remove from the scene if mesh found
  18520. this.activeCameras.splice(index2, 1);
  18521. }
  18522. // Reset the activeCamera
  18523. if (this.activeCamera === toRemove) {
  18524. if (this.cameras.length > 0) {
  18525. this.activeCamera = this.cameras[0];
  18526. }
  18527. else {
  18528. this.activeCamera = null;
  18529. }
  18530. }
  18531. this.onCameraRemovedObservable.notifyObservers(toRemove);
  18532. return index;
  18533. };
  18534. Scene.prototype.addLight = function (newLight) {
  18535. newLight.uniqueId = this._uniqueIdCounter++;
  18536. var position = this.lights.push(newLight);
  18537. this.onNewLightAddedObservable.notifyObservers(newLight);
  18538. };
  18539. Scene.prototype.addCamera = function (newCamera) {
  18540. newCamera.uniqueId = this._uniqueIdCounter++;
  18541. var position = this.cameras.push(newCamera);
  18542. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  18543. };
  18544. /**
  18545. * Switch active camera
  18546. * @param {Camera} newCamera - new active camera
  18547. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  18548. */
  18549. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  18550. if (attachControl === void 0) { attachControl = true; }
  18551. var canvas = this._engine.getRenderingCanvas();
  18552. this.activeCamera.detachControl(canvas);
  18553. this.activeCamera = newCamera;
  18554. if (attachControl) {
  18555. newCamera.attachControl(canvas);
  18556. }
  18557. };
  18558. /**
  18559. * sets the active camera of the scene using its ID
  18560. * @param {string} id - the camera's ID
  18561. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18562. * @see activeCamera
  18563. */
  18564. Scene.prototype.setActiveCameraByID = function (id) {
  18565. var camera = this.getCameraByID(id);
  18566. if (camera) {
  18567. this.activeCamera = camera;
  18568. return camera;
  18569. }
  18570. return null;
  18571. };
  18572. /**
  18573. * sets the active camera of the scene using its name
  18574. * @param {string} name - the camera's name
  18575. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  18576. * @see activeCamera
  18577. */
  18578. Scene.prototype.setActiveCameraByName = function (name) {
  18579. var camera = this.getCameraByName(name);
  18580. if (camera) {
  18581. this.activeCamera = camera;
  18582. return camera;
  18583. }
  18584. return null;
  18585. };
  18586. /**
  18587. * get a material using its id
  18588. * @param {string} the material's ID
  18589. * @return {BABYLON.Material|null} the material or null if none found.
  18590. */
  18591. Scene.prototype.getMaterialByID = function (id) {
  18592. for (var index = 0; index < this.materials.length; index++) {
  18593. if (this.materials[index].id === id) {
  18594. return this.materials[index];
  18595. }
  18596. }
  18597. return null;
  18598. };
  18599. /**
  18600. * get a material using its name
  18601. * @param {string} the material's name
  18602. * @return {BABYLON.Material|null} the material or null if none found.
  18603. */
  18604. Scene.prototype.getMaterialByName = function (name) {
  18605. for (var index = 0; index < this.materials.length; index++) {
  18606. if (this.materials[index].name === name) {
  18607. return this.materials[index];
  18608. }
  18609. }
  18610. return null;
  18611. };
  18612. Scene.prototype.getLensFlareSystemByName = function (name) {
  18613. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18614. if (this.lensFlareSystems[index].name === name) {
  18615. return this.lensFlareSystems[index];
  18616. }
  18617. }
  18618. return null;
  18619. };
  18620. Scene.prototype.getLensFlareSystemByID = function (id) {
  18621. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  18622. if (this.lensFlareSystems[index].id === id) {
  18623. return this.lensFlareSystems[index];
  18624. }
  18625. }
  18626. return null;
  18627. };
  18628. Scene.prototype.getCameraByID = function (id) {
  18629. for (var index = 0; index < this.cameras.length; index++) {
  18630. if (this.cameras[index].id === id) {
  18631. return this.cameras[index];
  18632. }
  18633. }
  18634. return null;
  18635. };
  18636. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  18637. for (var index = 0; index < this.cameras.length; index++) {
  18638. if (this.cameras[index].uniqueId === uniqueId) {
  18639. return this.cameras[index];
  18640. }
  18641. }
  18642. return null;
  18643. };
  18644. /**
  18645. * get a camera using its name
  18646. * @param {string} the camera's name
  18647. * @return {BABYLON.Camera|null} the camera or null if none found.
  18648. */
  18649. Scene.prototype.getCameraByName = function (name) {
  18650. for (var index = 0; index < this.cameras.length; index++) {
  18651. if (this.cameras[index].name === name) {
  18652. return this.cameras[index];
  18653. }
  18654. }
  18655. return null;
  18656. };
  18657. /**
  18658. * get a bone using its id
  18659. * @param {string} the bone's id
  18660. * @return {BABYLON.Bone|null} the bone or null if not found
  18661. */
  18662. Scene.prototype.getBoneByID = function (id) {
  18663. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18664. var skeleton = this.skeletons[skeletonIndex];
  18665. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18666. if (skeleton.bones[boneIndex].id === id) {
  18667. return skeleton.bones[boneIndex];
  18668. }
  18669. }
  18670. }
  18671. return null;
  18672. };
  18673. /**
  18674. * get a bone using its id
  18675. * @param {string} the bone's name
  18676. * @return {BABYLON.Bone|null} the bone or null if not found
  18677. */
  18678. Scene.prototype.getBoneByName = function (name) {
  18679. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  18680. var skeleton = this.skeletons[skeletonIndex];
  18681. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  18682. if (skeleton.bones[boneIndex].name === name) {
  18683. return skeleton.bones[boneIndex];
  18684. }
  18685. }
  18686. }
  18687. return null;
  18688. };
  18689. /**
  18690. * get a light node using its name
  18691. * @param {string} the light's name
  18692. * @return {BABYLON.Light|null} the light or null if none found.
  18693. */
  18694. Scene.prototype.getLightByName = function (name) {
  18695. for (var index = 0; index < this.lights.length; index++) {
  18696. if (this.lights[index].name === name) {
  18697. return this.lights[index];
  18698. }
  18699. }
  18700. return null;
  18701. };
  18702. /**
  18703. * get a light node using its ID
  18704. * @param {string} the light's id
  18705. * @return {BABYLON.Light|null} the light or null if none found.
  18706. */
  18707. Scene.prototype.getLightByID = function (id) {
  18708. for (var index = 0; index < this.lights.length; index++) {
  18709. if (this.lights[index].id === id) {
  18710. return this.lights[index];
  18711. }
  18712. }
  18713. return null;
  18714. };
  18715. /**
  18716. * get a light node using its scene-generated unique ID
  18717. * @param {number} the light's unique id
  18718. * @return {BABYLON.Light|null} the light or null if none found.
  18719. */
  18720. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  18721. for (var index = 0; index < this.lights.length; index++) {
  18722. if (this.lights[index].uniqueId === uniqueId) {
  18723. return this.lights[index];
  18724. }
  18725. }
  18726. return null;
  18727. };
  18728. /**
  18729. * get a particle system by id
  18730. * @param id {number} the particle system id
  18731. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  18732. */
  18733. Scene.prototype.getParticleSystemByID = function (id) {
  18734. for (var index = 0; index < this.particleSystems.length; index++) {
  18735. if (this.particleSystems[index].id === id) {
  18736. return this.particleSystems[index];
  18737. }
  18738. }
  18739. return null;
  18740. };
  18741. /**
  18742. * get a geometry using its ID
  18743. * @param {string} the geometry's id
  18744. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  18745. */
  18746. Scene.prototype.getGeometryByID = function (id) {
  18747. for (var index = 0; index < this._geometries.length; index++) {
  18748. if (this._geometries[index].id === id) {
  18749. return this._geometries[index];
  18750. }
  18751. }
  18752. return null;
  18753. };
  18754. /**
  18755. * add a new geometry to this scene.
  18756. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  18757. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  18758. * @return {boolean} was the geometry added or not
  18759. */
  18760. Scene.prototype.pushGeometry = function (geometry, force) {
  18761. if (!force && this.getGeometryByID(geometry.id)) {
  18762. return false;
  18763. }
  18764. this._geometries.push(geometry);
  18765. //notify the collision coordinator
  18766. this.collisionCoordinator.onGeometryAdded(geometry);
  18767. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  18768. return true;
  18769. };
  18770. /**
  18771. * Removes an existing geometry
  18772. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18773. * @return {boolean} was the geometry removed or not
  18774. */
  18775. Scene.prototype.removeGeometry = function (geometry) {
  18776. var index = this._geometries.indexOf(geometry);
  18777. if (index > -1) {
  18778. this._geometries.splice(index, 1);
  18779. //notify the collision coordinator
  18780. this.collisionCoordinator.onGeometryDeleted(geometry);
  18781. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18782. return true;
  18783. }
  18784. return false;
  18785. };
  18786. Scene.prototype.getGeometries = function () {
  18787. return this._geometries;
  18788. };
  18789. /**
  18790. * Get the first added mesh found of a given ID
  18791. * @param {string} id - the id to search for
  18792. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18793. */
  18794. Scene.prototype.getMeshByID = function (id) {
  18795. for (var index = 0; index < this.meshes.length; index++) {
  18796. if (this.meshes[index].id === id) {
  18797. return this.meshes[index];
  18798. }
  18799. }
  18800. return null;
  18801. };
  18802. Scene.prototype.getMeshesByID = function (id) {
  18803. return this.meshes.filter(function (m) {
  18804. return m.id === id;
  18805. });
  18806. };
  18807. /**
  18808. * Get a mesh with its auto-generated unique id
  18809. * @param {number} uniqueId - the unique id to search for
  18810. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18811. */
  18812. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18813. for (var index = 0; index < this.meshes.length; index++) {
  18814. if (this.meshes[index].uniqueId === uniqueId) {
  18815. return this.meshes[index];
  18816. }
  18817. }
  18818. return null;
  18819. };
  18820. /**
  18821. * Get a the last added mesh found of a given ID
  18822. * @param {string} id - the id to search for
  18823. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18824. */
  18825. Scene.prototype.getLastMeshByID = function (id) {
  18826. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18827. if (this.meshes[index].id === id) {
  18828. return this.meshes[index];
  18829. }
  18830. }
  18831. return null;
  18832. };
  18833. /**
  18834. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18835. * @param {string} id - the id to search for
  18836. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18837. */
  18838. Scene.prototype.getLastEntryByID = function (id) {
  18839. var index;
  18840. for (index = this.meshes.length - 1; index >= 0; index--) {
  18841. if (this.meshes[index].id === id) {
  18842. return this.meshes[index];
  18843. }
  18844. }
  18845. for (index = this.cameras.length - 1; index >= 0; index--) {
  18846. if (this.cameras[index].id === id) {
  18847. return this.cameras[index];
  18848. }
  18849. }
  18850. for (index = this.lights.length - 1; index >= 0; index--) {
  18851. if (this.lights[index].id === id) {
  18852. return this.lights[index];
  18853. }
  18854. }
  18855. return null;
  18856. };
  18857. Scene.prototype.getNodeByID = function (id) {
  18858. var mesh = this.getMeshByID(id);
  18859. if (mesh) {
  18860. return mesh;
  18861. }
  18862. var light = this.getLightByID(id);
  18863. if (light) {
  18864. return light;
  18865. }
  18866. var camera = this.getCameraByID(id);
  18867. if (camera) {
  18868. return camera;
  18869. }
  18870. var bone = this.getBoneByID(id);
  18871. return bone;
  18872. };
  18873. Scene.prototype.getNodeByName = function (name) {
  18874. var mesh = this.getMeshByName(name);
  18875. if (mesh) {
  18876. return mesh;
  18877. }
  18878. var light = this.getLightByName(name);
  18879. if (light) {
  18880. return light;
  18881. }
  18882. var camera = this.getCameraByName(name);
  18883. if (camera) {
  18884. return camera;
  18885. }
  18886. var bone = this.getBoneByName(name);
  18887. return bone;
  18888. };
  18889. Scene.prototype.getMeshByName = function (name) {
  18890. for (var index = 0; index < this.meshes.length; index++) {
  18891. if (this.meshes[index].name === name) {
  18892. return this.meshes[index];
  18893. }
  18894. }
  18895. return null;
  18896. };
  18897. Scene.prototype.getSoundByName = function (name) {
  18898. var index;
  18899. if (BABYLON.AudioEngine) {
  18900. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18901. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18902. return this.mainSoundTrack.soundCollection[index];
  18903. }
  18904. }
  18905. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18906. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18907. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18908. return this.soundTracks[sdIndex].soundCollection[index];
  18909. }
  18910. }
  18911. }
  18912. }
  18913. return null;
  18914. };
  18915. Scene.prototype.getLastSkeletonByID = function (id) {
  18916. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18917. if (this.skeletons[index].id === id) {
  18918. return this.skeletons[index];
  18919. }
  18920. }
  18921. return null;
  18922. };
  18923. Scene.prototype.getSkeletonById = function (id) {
  18924. for (var index = 0; index < this.skeletons.length; index++) {
  18925. if (this.skeletons[index].id === id) {
  18926. return this.skeletons[index];
  18927. }
  18928. }
  18929. return null;
  18930. };
  18931. Scene.prototype.getSkeletonByName = function (name) {
  18932. for (var index = 0; index < this.skeletons.length; index++) {
  18933. if (this.skeletons[index].name === name) {
  18934. return this.skeletons[index];
  18935. }
  18936. }
  18937. return null;
  18938. };
  18939. Scene.prototype.isActiveMesh = function (mesh) {
  18940. return (this._activeMeshes.indexOf(mesh) !== -1);
  18941. };
  18942. Object.defineProperty(Scene.prototype, "uid", {
  18943. /**
  18944. * Return a unique id as a string which can serve as an identifier for the scene
  18945. */
  18946. get: function () {
  18947. if (!this._uid) {
  18948. this._uid = BABYLON.Tools.RandomId();
  18949. }
  18950. return this._uid;
  18951. },
  18952. enumerable: true,
  18953. configurable: true
  18954. });
  18955. /**
  18956. * Add an externaly attached data from its key.
  18957. * This method call will fail and return false, if such key already exists.
  18958. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18959. * @param key the unique key that identifies the data
  18960. * @param data the data object to associate to the key for this Engine instance
  18961. * @return true if no such key were already present and the data was added successfully, false otherwise
  18962. */
  18963. Scene.prototype.addExternalData = function (key, data) {
  18964. return this._externalData.add(key, data);
  18965. };
  18966. /**
  18967. * Get an externaly attached data from its key
  18968. * @param key the unique key that identifies the data
  18969. * @return the associated data, if present (can be null), or undefined if not present
  18970. */
  18971. Scene.prototype.getExternalData = function (key) {
  18972. return this._externalData.get(key);
  18973. };
  18974. /**
  18975. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18976. * @param key the unique key that identifies the data
  18977. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18978. * @return the associated data, can be null if the factory returned null.
  18979. */
  18980. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18981. return this._externalData.getOrAddWithFactory(key, factory);
  18982. };
  18983. /**
  18984. * Remove an externaly attached data from the Engine instance
  18985. * @param key the unique key that identifies the data
  18986. * @return true if the data was successfully removed, false if it doesn't exist
  18987. */
  18988. Scene.prototype.removeExternalData = function (key) {
  18989. return this._externalData.remove(key);
  18990. };
  18991. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18992. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18993. var material = subMesh.getMaterial();
  18994. if (mesh.showSubMeshesBoundingBox) {
  18995. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  18996. }
  18997. if (material) {
  18998. // Render targets
  18999. if (material.getRenderTargetTextures) {
  19000. if (this._processedMaterials.indexOf(material) === -1) {
  19001. this._processedMaterials.push(material);
  19002. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  19003. }
  19004. }
  19005. // Dispatch
  19006. this._activeIndices.addCount(subMesh.indexCount, false);
  19007. this._renderingManager.dispatch(subMesh);
  19008. }
  19009. }
  19010. };
  19011. Scene.prototype._isInIntermediateRendering = function () {
  19012. return this._intermediateRendering;
  19013. };
  19014. Scene.prototype._evaluateActiveMeshes = function () {
  19015. this.activeCamera._activeMeshes.reset();
  19016. this._activeMeshes.reset();
  19017. this._renderingManager.reset();
  19018. this._processedMaterials.reset();
  19019. this._activeParticleSystems.reset();
  19020. this._activeSkeletons.reset();
  19021. this._softwareSkinnedMeshes.reset();
  19022. this._boundingBoxRenderer.reset();
  19023. this._edgesRenderers.reset();
  19024. // Meshes
  19025. var meshes;
  19026. var len;
  19027. if (this._selectionOctree) {
  19028. var selection = this._selectionOctree.select(this._frustumPlanes);
  19029. meshes = selection.data;
  19030. len = selection.length;
  19031. }
  19032. else {
  19033. len = this.meshes.length;
  19034. meshes = this.meshes;
  19035. }
  19036. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  19037. var mesh = meshes[meshIndex];
  19038. if (mesh.isBlocked) {
  19039. continue;
  19040. }
  19041. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  19042. if (!mesh.isReady() || !mesh.isEnabled()) {
  19043. continue;
  19044. }
  19045. mesh.computeWorldMatrix();
  19046. // Intersections
  19047. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  19048. this._meshesForIntersections.pushNoDuplicate(mesh);
  19049. }
  19050. // Switch to current LOD
  19051. var meshLOD = mesh.getLOD(this.activeCamera);
  19052. if (!meshLOD) {
  19053. continue;
  19054. }
  19055. mesh._preActivate();
  19056. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  19057. this._activeMeshes.push(mesh);
  19058. this.activeCamera._activeMeshes.push(mesh);
  19059. mesh._activate(this._renderId);
  19060. this._activeMesh(mesh, meshLOD);
  19061. }
  19062. }
  19063. // Particle systems
  19064. this._particlesDuration.beginMonitoring();
  19065. var beforeParticlesDate = BABYLON.Tools.Now;
  19066. if (this.particlesEnabled) {
  19067. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  19068. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  19069. var particleSystem = this.particleSystems[particleIndex];
  19070. if (!particleSystem.isStarted()) {
  19071. continue;
  19072. }
  19073. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  19074. this._activeParticleSystems.push(particleSystem);
  19075. particleSystem.animate();
  19076. this._renderingManager.dispatchParticles(particleSystem);
  19077. }
  19078. }
  19079. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  19080. }
  19081. this._particlesDuration.endMonitoring(false);
  19082. };
  19083. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  19084. if (mesh.skeleton && this.skeletonsEnabled) {
  19085. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  19086. mesh.skeleton.prepare();
  19087. }
  19088. if (!mesh.computeBonesUsingShaders) {
  19089. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  19090. }
  19091. }
  19092. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  19093. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  19094. }
  19095. if (sourceMesh._edgesRenderer) {
  19096. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  19097. }
  19098. if (mesh && mesh.subMeshes) {
  19099. // Submeshes Octrees
  19100. var len;
  19101. var subMeshes;
  19102. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  19103. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  19104. len = intersections.length;
  19105. subMeshes = intersections.data;
  19106. }
  19107. else {
  19108. subMeshes = mesh.subMeshes;
  19109. len = subMeshes.length;
  19110. }
  19111. for (var subIndex = 0; subIndex < len; subIndex++) {
  19112. var subMesh = subMeshes[subIndex];
  19113. this._evaluateSubMesh(subMesh, mesh);
  19114. }
  19115. }
  19116. };
  19117. Scene.prototype.updateTransformMatrix = function (force) {
  19118. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  19119. };
  19120. Scene.prototype._renderForCamera = function (camera) {
  19121. var engine = this._engine;
  19122. var startTime = BABYLON.Tools.Now;
  19123. this.activeCamera = camera;
  19124. if (!this.activeCamera)
  19125. throw new Error("Active camera not set");
  19126. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19127. // Viewport
  19128. engine.setViewport(this.activeCamera.viewport);
  19129. // Camera
  19130. this.resetCachedMaterial();
  19131. this._renderId++;
  19132. this.updateTransformMatrix();
  19133. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  19134. // Meshes
  19135. this._evaluateActiveMeshesDuration.beginMonitoring();
  19136. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  19137. this._evaluateActiveMeshes();
  19138. this._evaluateActiveMeshesDuration.endMonitoring(false);
  19139. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  19140. // Software skinning
  19141. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  19142. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  19143. mesh.applySkeleton(mesh.skeleton);
  19144. }
  19145. // Render targets
  19146. this._renderTargetsDuration.beginMonitoring();
  19147. var needsRestoreFrameBuffer = false;
  19148. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19149. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  19150. this._intermediateRendering = true;
  19151. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19152. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  19153. var renderTarget = this._renderTargets.data[renderIndex];
  19154. if (renderTarget._shouldRender()) {
  19155. this._renderId++;
  19156. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  19157. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  19158. }
  19159. }
  19160. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  19161. this._intermediateRendering = false;
  19162. this._renderId++;
  19163. needsRestoreFrameBuffer = true; // Restore back buffer
  19164. }
  19165. // Render HighlightLayer Texture
  19166. var stencilState = this._engine.getStencilBuffer();
  19167. var renderhighlights = false;
  19168. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  19169. this._intermediateRendering = true;
  19170. for (var i = 0; i < this.highlightLayers.length; i++) {
  19171. var highlightLayer = this.highlightLayers[i];
  19172. if (highlightLayer.shouldRender() &&
  19173. (!highlightLayer.camera ||
  19174. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  19175. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  19176. renderhighlights = true;
  19177. var renderTarget = highlightLayer._mainTexture;
  19178. if (renderTarget._shouldRender()) {
  19179. this._renderId++;
  19180. renderTarget.render(false, false);
  19181. needsRestoreFrameBuffer = true;
  19182. }
  19183. }
  19184. }
  19185. this._intermediateRendering = false;
  19186. this._renderId++;
  19187. }
  19188. if (needsRestoreFrameBuffer) {
  19189. engine.restoreDefaultFramebuffer();
  19190. }
  19191. this._renderTargetsDuration.endMonitoring(false);
  19192. // Prepare Frame
  19193. this.postProcessManager._prepareFrame();
  19194. this._renderDuration.beginMonitoring();
  19195. // Backgrounds
  19196. var layerIndex;
  19197. var layer;
  19198. if (this.layers.length) {
  19199. engine.setDepthBuffer(false);
  19200. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19201. layer = this.layers[layerIndex];
  19202. if (layer.isBackground) {
  19203. layer.render();
  19204. }
  19205. }
  19206. engine.setDepthBuffer(true);
  19207. }
  19208. // Render
  19209. BABYLON.Tools.StartPerformanceCounter("Main render");
  19210. // Activate HighlightLayer stencil
  19211. if (renderhighlights) {
  19212. this._engine.setStencilBuffer(true);
  19213. }
  19214. this._renderingManager.render(null, null, true, true);
  19215. // Restore HighlightLayer stencil
  19216. if (renderhighlights) {
  19217. this._engine.setStencilBuffer(stencilState);
  19218. }
  19219. BABYLON.Tools.EndPerformanceCounter("Main render");
  19220. // Bounding boxes
  19221. this._boundingBoxRenderer.render();
  19222. // Edges
  19223. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  19224. this._edgesRenderers.data[edgesRendererIndex].render();
  19225. }
  19226. // Lens flares
  19227. if (this.lensFlaresEnabled) {
  19228. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19229. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  19230. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  19231. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  19232. lensFlareSystem.render();
  19233. }
  19234. }
  19235. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  19236. }
  19237. // Foregrounds
  19238. if (this.layers.length) {
  19239. engine.setDepthBuffer(false);
  19240. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  19241. layer = this.layers[layerIndex];
  19242. if (!layer.isBackground) {
  19243. layer.render();
  19244. }
  19245. }
  19246. engine.setDepthBuffer(true);
  19247. }
  19248. // Highlight Layer
  19249. if (renderhighlights) {
  19250. engine.setDepthBuffer(false);
  19251. for (var i = 0; i < this.highlightLayers.length; i++) {
  19252. if (this.highlightLayers[i].shouldRender()) {
  19253. this.highlightLayers[i].render();
  19254. }
  19255. }
  19256. engine.setDepthBuffer(true);
  19257. }
  19258. this._renderDuration.endMonitoring(false);
  19259. // Finalize frame
  19260. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  19261. // Update camera
  19262. this.activeCamera._updateFromScene();
  19263. // Reset some special arrays
  19264. this._renderTargets.reset();
  19265. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  19266. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  19267. };
  19268. Scene.prototype._processSubCameras = function (camera) {
  19269. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  19270. this._renderForCamera(camera);
  19271. return;
  19272. }
  19273. // rig cameras
  19274. for (var index = 0; index < camera._rigCameras.length; index++) {
  19275. this._renderForCamera(camera._rigCameras[index]);
  19276. }
  19277. this.activeCamera = camera;
  19278. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  19279. // Update camera
  19280. this.activeCamera._updateFromScene();
  19281. };
  19282. Scene.prototype._checkIntersections = function () {
  19283. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  19284. var sourceMesh = this._meshesForIntersections.data[index];
  19285. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  19286. var action = sourceMesh.actionManager.actions[actionIndex];
  19287. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19288. var parameters = action.getTriggerParameter();
  19289. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  19290. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  19291. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  19292. if (areIntersecting && currentIntersectionInProgress === -1) {
  19293. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  19294. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19295. sourceMesh._intersectionsInProgress.push(otherMesh);
  19296. }
  19297. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19298. sourceMesh._intersectionsInProgress.push(otherMesh);
  19299. }
  19300. }
  19301. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  19302. //They intersected, and now they don't.
  19303. //is this trigger an exit trigger? execute an event.
  19304. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19305. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  19306. }
  19307. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  19308. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  19309. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  19310. }
  19311. }
  19312. }
  19313. }
  19314. }
  19315. };
  19316. Scene.prototype.render = function () {
  19317. this._lastFrameDuration.beginMonitoring();
  19318. this._particlesDuration.fetchNewFrame();
  19319. this._spritesDuration.fetchNewFrame();
  19320. this._activeParticles.fetchNewFrame();
  19321. this._renderDuration.fetchNewFrame();
  19322. this._renderTargetsDuration.fetchNewFrame();
  19323. this._evaluateActiveMeshesDuration.fetchNewFrame();
  19324. this._totalVertices.fetchNewFrame();
  19325. this._activeIndices.fetchNewFrame();
  19326. this._activeBones.fetchNewFrame();
  19327. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  19328. this._meshesForIntersections.reset();
  19329. this.resetCachedMaterial();
  19330. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  19331. // Actions
  19332. if (this.actionManager) {
  19333. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  19334. }
  19335. //Simplification Queue
  19336. if (this.simplificationQueue && !this.simplificationQueue.running) {
  19337. this.simplificationQueue.executeNext();
  19338. }
  19339. // Animations
  19340. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  19341. this._animationRatio = deltaTime * (60.0 / 1000.0);
  19342. this._animate();
  19343. // Physics
  19344. if (this._physicsEngine) {
  19345. BABYLON.Tools.StartPerformanceCounter("Physics");
  19346. this._physicsEngine._step(deltaTime / 1000.0);
  19347. BABYLON.Tools.EndPerformanceCounter("Physics");
  19348. }
  19349. // Before render
  19350. this.onBeforeRenderObservable.notifyObservers(this);
  19351. // Customs render targets
  19352. this._renderTargetsDuration.beginMonitoring();
  19353. var beforeRenderTargetDate = BABYLON.Tools.Now;
  19354. var engine = this.getEngine();
  19355. var currentActiveCamera = this.activeCamera;
  19356. if (this.renderTargetsEnabled) {
  19357. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19358. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  19359. var renderTarget = this.customRenderTargets[customIndex];
  19360. if (renderTarget._shouldRender()) {
  19361. this._renderId++;
  19362. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  19363. if (!this.activeCamera)
  19364. throw new Error("Active camera not set");
  19365. // Viewport
  19366. engine.setViewport(this.activeCamera.viewport);
  19367. // Camera
  19368. this.updateTransformMatrix();
  19369. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  19370. }
  19371. }
  19372. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  19373. this._renderId++;
  19374. }
  19375. if (this.customRenderTargets.length > 0) {
  19376. engine.restoreDefaultFramebuffer();
  19377. }
  19378. this._renderTargetsDuration.endMonitoring();
  19379. this.activeCamera = currentActiveCamera;
  19380. // Procedural textures
  19381. if (this.proceduralTexturesEnabled) {
  19382. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19383. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  19384. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  19385. if (proceduralTexture._shouldRender()) {
  19386. proceduralTexture.render();
  19387. }
  19388. }
  19389. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  19390. }
  19391. // Clear
  19392. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  19393. // Shadows
  19394. if (this.shadowsEnabled) {
  19395. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  19396. var light = this.lights[lightIndex];
  19397. var shadowGenerator = light.getShadowGenerator();
  19398. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  19399. this._renderTargets.push(shadowGenerator.getShadowMap());
  19400. }
  19401. }
  19402. }
  19403. // Depth renderer
  19404. if (this._depthRenderer) {
  19405. this._renderTargets.push(this._depthRenderer.getDepthMap());
  19406. }
  19407. // RenderPipeline
  19408. this.postProcessRenderPipelineManager.update();
  19409. // Multi-cameras?
  19410. if (this.activeCameras.length > 0) {
  19411. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  19412. if (cameraIndex > 0) {
  19413. this._engine.clear(null, false, true, true);
  19414. }
  19415. this._processSubCameras(this.activeCameras[cameraIndex]);
  19416. }
  19417. }
  19418. else {
  19419. if (!this.activeCamera) {
  19420. throw new Error("No camera defined");
  19421. }
  19422. this._processSubCameras(this.activeCamera);
  19423. }
  19424. // Intersection checks
  19425. this._checkIntersections();
  19426. // Update the audio listener attached to the camera
  19427. if (BABYLON.AudioEngine) {
  19428. this._updateAudioParameters();
  19429. }
  19430. // After render
  19431. if (this.afterRender) {
  19432. this.afterRender();
  19433. }
  19434. this.onAfterRenderObservable.notifyObservers(this);
  19435. // Cleaning
  19436. for (var index = 0; index < this._toBeDisposed.length; index++) {
  19437. this._toBeDisposed.data[index].dispose();
  19438. this._toBeDisposed[index] = null;
  19439. }
  19440. this._toBeDisposed.reset();
  19441. if (this.dumpNextRenderTargets) {
  19442. this.dumpNextRenderTargets = false;
  19443. }
  19444. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  19445. this._lastFrameDuration.endMonitoring();
  19446. this._totalMeshesCounter.addCount(this.meshes.length, true);
  19447. this._totalLightsCounter.addCount(this.lights.length, true);
  19448. this._totalMaterialsCounter.addCount(this.materials.length, true);
  19449. this._totalTexturesCounter.addCount(this.textures.length, true);
  19450. this._activeBones.addCount(0, true);
  19451. this._activeIndices.addCount(0, true);
  19452. this._activeParticles.addCount(0, true);
  19453. };
  19454. Scene.prototype._updateAudioParameters = function () {
  19455. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  19456. return;
  19457. }
  19458. var listeningCamera;
  19459. var audioEngine = BABYLON.Engine.audioEngine;
  19460. if (this.activeCameras.length > 0) {
  19461. listeningCamera = this.activeCameras[0];
  19462. }
  19463. else {
  19464. listeningCamera = this.activeCamera;
  19465. }
  19466. if (listeningCamera && audioEngine.canUseWebAudio) {
  19467. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  19468. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  19469. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  19470. cameraDirection.normalize();
  19471. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  19472. var i;
  19473. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19474. var sound = this.mainSoundTrack.soundCollection[i];
  19475. if (sound.useCustomAttenuation) {
  19476. sound.updateDistanceFromListener();
  19477. }
  19478. }
  19479. for (i = 0; i < this.soundTracks.length; i++) {
  19480. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19481. sound = this.soundTracks[i].soundCollection[j];
  19482. if (sound.useCustomAttenuation) {
  19483. sound.updateDistanceFromListener();
  19484. }
  19485. }
  19486. }
  19487. }
  19488. };
  19489. Object.defineProperty(Scene.prototype, "audioEnabled", {
  19490. // Audio
  19491. get: function () {
  19492. return this._audioEnabled;
  19493. },
  19494. set: function (value) {
  19495. this._audioEnabled = value;
  19496. if (BABYLON.AudioEngine) {
  19497. if (this._audioEnabled) {
  19498. this._enableAudio();
  19499. }
  19500. else {
  19501. this._disableAudio();
  19502. }
  19503. }
  19504. },
  19505. enumerable: true,
  19506. configurable: true
  19507. });
  19508. Scene.prototype._disableAudio = function () {
  19509. var i;
  19510. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19511. this.mainSoundTrack.soundCollection[i].pause();
  19512. }
  19513. for (i = 0; i < this.soundTracks.length; i++) {
  19514. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19515. this.soundTracks[i].soundCollection[j].pause();
  19516. }
  19517. }
  19518. };
  19519. Scene.prototype._enableAudio = function () {
  19520. var i;
  19521. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  19522. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  19523. this.mainSoundTrack.soundCollection[i].play();
  19524. }
  19525. }
  19526. for (i = 0; i < this.soundTracks.length; i++) {
  19527. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  19528. if (this.soundTracks[i].soundCollection[j].isPaused) {
  19529. this.soundTracks[i].soundCollection[j].play();
  19530. }
  19531. }
  19532. }
  19533. };
  19534. Object.defineProperty(Scene.prototype, "headphone", {
  19535. get: function () {
  19536. return this._headphone;
  19537. },
  19538. set: function (value) {
  19539. this._headphone = value;
  19540. if (BABYLON.AudioEngine) {
  19541. if (this._headphone) {
  19542. this._switchAudioModeForHeadphones();
  19543. }
  19544. else {
  19545. this._switchAudioModeForNormalSpeakers();
  19546. }
  19547. }
  19548. },
  19549. enumerable: true,
  19550. configurable: true
  19551. });
  19552. Scene.prototype._switchAudioModeForHeadphones = function () {
  19553. this.mainSoundTrack.switchPanningModelToHRTF();
  19554. for (var i = 0; i < this.soundTracks.length; i++) {
  19555. this.soundTracks[i].switchPanningModelToHRTF();
  19556. }
  19557. };
  19558. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  19559. this.mainSoundTrack.switchPanningModelToEqualPower();
  19560. for (var i = 0; i < this.soundTracks.length; i++) {
  19561. this.soundTracks[i].switchPanningModelToEqualPower();
  19562. }
  19563. };
  19564. Scene.prototype.enableDepthRenderer = function () {
  19565. if (this._depthRenderer) {
  19566. return this._depthRenderer;
  19567. }
  19568. this._depthRenderer = new BABYLON.DepthRenderer(this);
  19569. return this._depthRenderer;
  19570. };
  19571. Scene.prototype.disableDepthRenderer = function () {
  19572. if (!this._depthRenderer) {
  19573. return;
  19574. }
  19575. this._depthRenderer.dispose();
  19576. this._depthRenderer = null;
  19577. };
  19578. Scene.prototype.freezeMaterials = function () {
  19579. for (var i = 0; i < this.materials.length; i++) {
  19580. this.materials[i].freeze();
  19581. }
  19582. };
  19583. Scene.prototype.unfreezeMaterials = function () {
  19584. for (var i = 0; i < this.materials.length; i++) {
  19585. this.materials[i].unfreeze();
  19586. }
  19587. };
  19588. Scene.prototype.dispose = function () {
  19589. this.beforeRender = null;
  19590. this.afterRender = null;
  19591. this.skeletons = [];
  19592. this._boundingBoxRenderer.dispose();
  19593. if (this._depthRenderer) {
  19594. this._depthRenderer.dispose();
  19595. }
  19596. // Debug layer
  19597. if (this._debugLayer) {
  19598. this._debugLayer.hide();
  19599. }
  19600. // Events
  19601. this.onDisposeObservable.notifyObservers(this);
  19602. this.onDisposeObservable.clear();
  19603. this.onBeforeRenderObservable.clear();
  19604. this.onAfterRenderObservable.clear();
  19605. this.detachControl();
  19606. // Release sounds & sounds tracks
  19607. if (BABYLON.AudioEngine) {
  19608. this.disposeSounds();
  19609. }
  19610. // Detach cameras
  19611. var canvas = this._engine.getRenderingCanvas();
  19612. var index;
  19613. for (index = 0; index < this.cameras.length; index++) {
  19614. this.cameras[index].detachControl(canvas);
  19615. }
  19616. // Release lights
  19617. while (this.lights.length) {
  19618. this.lights[0].dispose();
  19619. }
  19620. // Release meshes
  19621. while (this.meshes.length) {
  19622. this.meshes[0].dispose(true);
  19623. }
  19624. // Release cameras
  19625. while (this.cameras.length) {
  19626. this.cameras[0].dispose();
  19627. }
  19628. // Release materials
  19629. while (this.materials.length) {
  19630. this.materials[0].dispose();
  19631. }
  19632. // Release particles
  19633. while (this.particleSystems.length) {
  19634. this.particleSystems[0].dispose();
  19635. }
  19636. // Release sprites
  19637. while (this.spriteManagers.length) {
  19638. this.spriteManagers[0].dispose();
  19639. }
  19640. // Release layers
  19641. while (this.layers.length) {
  19642. this.layers[0].dispose();
  19643. }
  19644. while (this.highlightLayers.length) {
  19645. this.highlightLayers[0].dispose();
  19646. }
  19647. // Release textures
  19648. while (this.textures.length) {
  19649. this.textures[0].dispose();
  19650. }
  19651. // Post-processes
  19652. this.postProcessManager.dispose();
  19653. // Physics
  19654. if (this._physicsEngine) {
  19655. this.disablePhysicsEngine();
  19656. }
  19657. // Remove from engine
  19658. index = this._engine.scenes.indexOf(this);
  19659. if (index > -1) {
  19660. this._engine.scenes.splice(index, 1);
  19661. }
  19662. this._engine.wipeCaches();
  19663. };
  19664. // Release sounds & sounds tracks
  19665. Scene.prototype.disposeSounds = function () {
  19666. this.mainSoundTrack.dispose();
  19667. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19668. this.soundTracks[scIndex].dispose();
  19669. }
  19670. };
  19671. // Octrees
  19672. Scene.prototype.getWorldExtends = function () {
  19673. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19674. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19675. for (var index = 0; index < this.meshes.length; index++) {
  19676. var mesh = this.meshes[index];
  19677. mesh.computeWorldMatrix(true);
  19678. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19679. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19680. BABYLON.Tools.CheckExtends(minBox, min, max);
  19681. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19682. }
  19683. return {
  19684. min: min,
  19685. max: max
  19686. };
  19687. };
  19688. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19689. if (maxCapacity === void 0) { maxCapacity = 64; }
  19690. if (maxDepth === void 0) { maxDepth = 2; }
  19691. if (!this._selectionOctree) {
  19692. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19693. }
  19694. var worldExtends = this.getWorldExtends();
  19695. // Update octree
  19696. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19697. return this._selectionOctree;
  19698. };
  19699. // Picking
  19700. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19701. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19702. var engine = this._engine;
  19703. if (!camera) {
  19704. if (!this.activeCamera)
  19705. throw new Error("Active camera not set");
  19706. camera = this.activeCamera;
  19707. }
  19708. var cameraViewport = camera.viewport;
  19709. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19710. // Moving coordinates to local viewport world
  19711. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19712. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19713. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19714. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19715. };
  19716. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19717. var engine = this._engine;
  19718. if (!camera) {
  19719. if (!this.activeCamera)
  19720. throw new Error("Active camera not set");
  19721. camera = this.activeCamera;
  19722. }
  19723. var cameraViewport = camera.viewport;
  19724. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19725. var identity = BABYLON.Matrix.Identity();
  19726. // Moving coordinates to local viewport world
  19727. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19728. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19729. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19730. };
  19731. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19732. var pickingInfo = null;
  19733. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19734. var mesh = this.meshes[meshIndex];
  19735. if (predicate) {
  19736. if (!predicate(mesh)) {
  19737. continue;
  19738. }
  19739. }
  19740. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19741. continue;
  19742. }
  19743. var world = mesh.getWorldMatrix();
  19744. var ray = rayFunction(world);
  19745. var result = mesh.intersects(ray, fastCheck);
  19746. if (!result || !result.hit)
  19747. continue;
  19748. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19749. continue;
  19750. pickingInfo = result;
  19751. if (fastCheck) {
  19752. break;
  19753. }
  19754. }
  19755. return pickingInfo || new BABYLON.PickingInfo();
  19756. };
  19757. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19758. var pickingInfos = new Array();
  19759. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19760. var mesh = this.meshes[meshIndex];
  19761. if (predicate) {
  19762. if (!predicate(mesh)) {
  19763. continue;
  19764. }
  19765. }
  19766. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19767. continue;
  19768. }
  19769. var world = mesh.getWorldMatrix();
  19770. var ray = rayFunction(world);
  19771. var result = mesh.intersects(ray, false);
  19772. if (!result || !result.hit)
  19773. continue;
  19774. pickingInfos.push(result);
  19775. }
  19776. return pickingInfos;
  19777. };
  19778. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19779. var pickingInfo = null;
  19780. camera = camera || this.activeCamera;
  19781. if (this.spriteManagers.length > 0) {
  19782. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19783. var spriteManager = this.spriteManagers[spriteIndex];
  19784. if (!spriteManager.isPickable) {
  19785. continue;
  19786. }
  19787. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19788. if (!result || !result.hit)
  19789. continue;
  19790. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19791. continue;
  19792. pickingInfo = result;
  19793. if (fastCheck) {
  19794. break;
  19795. }
  19796. }
  19797. }
  19798. return pickingInfo || new BABYLON.PickingInfo();
  19799. };
  19800. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19801. /// <param name="x">X position on screen</param>
  19802. /// <param name="y">Y position on screen</param>
  19803. /// <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>
  19804. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  19805. /// <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>
  19806. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19807. var _this = this;
  19808. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19809. };
  19810. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19811. /// <param name="x">X position on screen</param>
  19812. /// <param name="y">Y position on screen</param>
  19813. /// <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>
  19814. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  19815. /// <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>
  19816. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19817. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19818. };
  19819. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19820. var _this = this;
  19821. return this._internalPick(function (world) {
  19822. if (!_this._pickWithRayInverseMatrix) {
  19823. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19824. }
  19825. world.invertToRef(_this._pickWithRayInverseMatrix);
  19826. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19827. }, predicate, fastCheck);
  19828. };
  19829. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19830. /// <param name="x">X position on screen</param>
  19831. /// <param name="y">Y position on screen</param>
  19832. /// <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>
  19833. /// <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>
  19834. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19835. var _this = this;
  19836. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19837. };
  19838. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  19839. /// <param name="ray">Ray to use</param>
  19840. /// <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>
  19841. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19842. var _this = this;
  19843. return this._internalMultiPick(function (world) {
  19844. if (!_this._pickWithRayInverseMatrix) {
  19845. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19846. }
  19847. world.invertToRef(_this._pickWithRayInverseMatrix);
  19848. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19849. }, predicate);
  19850. };
  19851. Scene.prototype.setPointerOverMesh = function (mesh) {
  19852. if (this._pointerOverMesh === mesh) {
  19853. return;
  19854. }
  19855. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19856. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19857. }
  19858. this._pointerOverMesh = mesh;
  19859. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19860. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19861. }
  19862. };
  19863. Scene.prototype.getPointerOverMesh = function () {
  19864. return this._pointerOverMesh;
  19865. };
  19866. Scene.prototype.setPointerOverSprite = function (sprite) {
  19867. if (this._pointerOverSprite === sprite) {
  19868. return;
  19869. }
  19870. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19871. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19872. }
  19873. this._pointerOverSprite = sprite;
  19874. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19875. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19876. }
  19877. };
  19878. Scene.prototype.getPointerOverSprite = function () {
  19879. return this._pointerOverSprite;
  19880. };
  19881. // Physics
  19882. Scene.prototype.getPhysicsEngine = function () {
  19883. return this._physicsEngine;
  19884. };
  19885. /**
  19886. * Enables physics to the current scene
  19887. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19888. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19889. * @return {boolean} was the physics engine initialized
  19890. */
  19891. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19892. if (this._physicsEngine) {
  19893. return true;
  19894. }
  19895. try {
  19896. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19897. return true;
  19898. }
  19899. catch (e) {
  19900. BABYLON.Tools.Error(e.message);
  19901. return false;
  19902. }
  19903. };
  19904. Scene.prototype.disablePhysicsEngine = function () {
  19905. if (!this._physicsEngine) {
  19906. return;
  19907. }
  19908. this._physicsEngine.dispose();
  19909. this._physicsEngine = undefined;
  19910. };
  19911. Scene.prototype.isPhysicsEnabled = function () {
  19912. return this._physicsEngine !== undefined;
  19913. };
  19914. /**
  19915. *
  19916. * Sets the gravity of the physics engine (and NOT of the scene)
  19917. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  19918. */
  19919. Scene.prototype.setGravity = function (gravity) {
  19920. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  19921. if (!this._physicsEngine) {
  19922. return;
  19923. }
  19924. this._physicsEngine.setGravity(gravity);
  19925. };
  19926. /**
  19927. * Legacy support, using the new API
  19928. * @Deprecated
  19929. */
  19930. Scene.prototype.createCompoundImpostor = function (parts, options) {
  19931. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  19932. if (parts.parts) {
  19933. options = parts;
  19934. parts = parts.parts;
  19935. }
  19936. var mainMesh = parts[0].mesh;
  19937. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  19938. for (var index = 1; index < parts.length; index++) {
  19939. var mesh = parts[index].mesh;
  19940. if (mesh.parent !== mainMesh) {
  19941. mesh.position = mesh.position.subtract(mainMesh.position);
  19942. mesh.parent = mainMesh;
  19943. }
  19944. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  19945. }
  19946. mainMesh.physicsImpostor.forceUpdate();
  19947. };
  19948. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19949. var mesh = compound.parts[0].mesh;
  19950. mesh.physicsImpostor.dispose();
  19951. mesh.physicsImpostor = null;
  19952. };
  19953. // Misc.
  19954. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  19955. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19956. // Light
  19957. if (this.lights.length === 0) {
  19958. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19959. }
  19960. // Camera
  19961. if (!this.activeCamera) {
  19962. // Compute position
  19963. var worldExtends = this.getWorldExtends();
  19964. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  19965. var camera;
  19966. if (createArcRotateCamera) {
  19967. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  19968. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  19969. camera.setTarget(worldCenter);
  19970. }
  19971. else {
  19972. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  19973. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  19974. camera.setTarget(worldCenter);
  19975. }
  19976. this.activeCamera = camera;
  19977. }
  19978. };
  19979. // Tags
  19980. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19981. if (tagsQuery === undefined) {
  19982. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19983. return list;
  19984. }
  19985. var listByTags = [];
  19986. forEach = forEach || (function (item) { return; });
  19987. for (var i in list) {
  19988. var item = list[i];
  19989. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19990. listByTags.push(item);
  19991. forEach(item);
  19992. }
  19993. }
  19994. return listByTags;
  19995. };
  19996. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19997. return this._getByTags(this.meshes, tagsQuery, forEach);
  19998. };
  19999. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  20000. return this._getByTags(this.cameras, tagsQuery, forEach);
  20001. };
  20002. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  20003. return this._getByTags(this.lights, tagsQuery, forEach);
  20004. };
  20005. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  20006. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  20007. };
  20008. /**
  20009. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  20010. * This allowed control for front to back rendering or reversly depending of the special needs.
  20011. *
  20012. * @param renderingGroupId The rendering group id corresponding to its index
  20013. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  20014. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  20015. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  20016. */
  20017. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  20018. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  20019. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  20020. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  20021. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  20022. };
  20023. /**
  20024. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  20025. *
  20026. * @param renderingGroupId The rendering group id corresponding to its index
  20027. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  20028. * @param depth Automatically clears depth between groups if true and autoClear is true.
  20029. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  20030. */
  20031. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  20032. if (depth === void 0) { depth = true; }
  20033. if (stencil === void 0) { stencil = true; }
  20034. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  20035. };
  20036. return Scene;
  20037. }());
  20038. // Statics
  20039. Scene._FOGMODE_NONE = 0;
  20040. Scene._FOGMODE_EXP = 1;
  20041. Scene._FOGMODE_EXP2 = 2;
  20042. Scene._FOGMODE_LINEAR = 3;
  20043. Scene.MinDeltaTime = 1.0;
  20044. Scene.MaxDeltaTime = 1000.0;
  20045. BABYLON.Scene = Scene;
  20046. })(BABYLON || (BABYLON = {}));
  20047. //# sourceMappingURL=babylon.scene.js.map
  20048. var BABYLON;
  20049. (function (BABYLON) {
  20050. var Buffer = (function () {
  20051. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  20052. if (engine instanceof BABYLON.Mesh) {
  20053. this._engine = engine.getScene().getEngine();
  20054. }
  20055. else {
  20056. this._engine = engine;
  20057. }
  20058. this._updatable = updatable;
  20059. this._data = data;
  20060. this._strideSize = stride;
  20061. if (!postponeInternalCreation) {
  20062. this.create();
  20063. }
  20064. this._instanced = instanced;
  20065. }
  20066. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  20067. // a lot of these parameters are ignored as they are overriden by the buffer
  20068. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  20069. };
  20070. // Properties
  20071. Buffer.prototype.isUpdatable = function () {
  20072. return this._updatable;
  20073. };
  20074. Buffer.prototype.getData = function () {
  20075. return this._data;
  20076. };
  20077. Buffer.prototype.getBuffer = function () {
  20078. return this._buffer;
  20079. };
  20080. Buffer.prototype.getStrideSize = function () {
  20081. return this._strideSize;
  20082. };
  20083. Buffer.prototype.getIsInstanced = function () {
  20084. return this._instanced;
  20085. };
  20086. // Methods
  20087. Buffer.prototype.create = function (data) {
  20088. if (!data && this._buffer) {
  20089. return; // nothing to do
  20090. }
  20091. data = data || this._data;
  20092. if (!this._buffer) {
  20093. if (this._updatable) {
  20094. this._buffer = this._engine.createDynamicVertexBuffer(data);
  20095. this._data = data;
  20096. }
  20097. else {
  20098. this._buffer = this._engine.createVertexBuffer(data);
  20099. }
  20100. }
  20101. else if (this._updatable) {
  20102. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  20103. this._data = data;
  20104. }
  20105. };
  20106. Buffer.prototype.update = function (data) {
  20107. this.create(data);
  20108. };
  20109. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  20110. if (!this._buffer) {
  20111. return;
  20112. }
  20113. if (this._updatable) {
  20114. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  20115. this._data = null;
  20116. }
  20117. };
  20118. Buffer.prototype.dispose = function () {
  20119. if (!this._buffer) {
  20120. return;
  20121. }
  20122. if (this._engine._releaseBuffer(this._buffer)) {
  20123. this._buffer = null;
  20124. }
  20125. };
  20126. return Buffer;
  20127. }());
  20128. BABYLON.Buffer = Buffer;
  20129. })(BABYLON || (BABYLON = {}));
  20130. //# sourceMappingURL=babylon.buffer.js.map
  20131. var BABYLON;
  20132. (function (BABYLON) {
  20133. var VertexBuffer = (function () {
  20134. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  20135. if (!stride) {
  20136. // Deduce stride from kind
  20137. switch (kind) {
  20138. case VertexBuffer.PositionKind:
  20139. stride = 3;
  20140. break;
  20141. case VertexBuffer.NormalKind:
  20142. stride = 3;
  20143. break;
  20144. case VertexBuffer.UVKind:
  20145. case VertexBuffer.UV2Kind:
  20146. case VertexBuffer.UV3Kind:
  20147. case VertexBuffer.UV4Kind:
  20148. case VertexBuffer.UV5Kind:
  20149. case VertexBuffer.UV6Kind:
  20150. stride = 2;
  20151. break;
  20152. case VertexBuffer.ColorKind:
  20153. stride = 4;
  20154. break;
  20155. case VertexBuffer.MatricesIndicesKind:
  20156. case VertexBuffer.MatricesIndicesExtraKind:
  20157. stride = 4;
  20158. break;
  20159. case VertexBuffer.MatricesWeightsKind:
  20160. case VertexBuffer.MatricesWeightsExtraKind:
  20161. stride = 4;
  20162. break;
  20163. }
  20164. }
  20165. if (data instanceof BABYLON.Buffer) {
  20166. if (!stride) {
  20167. stride = data.getStrideSize();
  20168. }
  20169. this._buffer = data;
  20170. this._ownsBuffer = false;
  20171. }
  20172. else {
  20173. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  20174. this._ownsBuffer = true;
  20175. }
  20176. this._stride = stride;
  20177. this._offset = offset ? offset : 0;
  20178. this._size = size ? size : stride;
  20179. this._kind = kind;
  20180. }
  20181. VertexBuffer.prototype.getKind = function () {
  20182. return this._kind;
  20183. };
  20184. // Properties
  20185. VertexBuffer.prototype.isUpdatable = function () {
  20186. return this._buffer.isUpdatable();
  20187. };
  20188. VertexBuffer.prototype.getData = function () {
  20189. return this._buffer.getData();
  20190. };
  20191. VertexBuffer.prototype.getBuffer = function () {
  20192. return this._buffer.getBuffer();
  20193. };
  20194. VertexBuffer.prototype.getStrideSize = function () {
  20195. return this._stride;
  20196. };
  20197. VertexBuffer.prototype.getOffset = function () {
  20198. return this._offset;
  20199. };
  20200. VertexBuffer.prototype.getSize = function () {
  20201. return this._size;
  20202. };
  20203. VertexBuffer.prototype.getIsInstanced = function () {
  20204. return this._buffer.getIsInstanced();
  20205. };
  20206. // Methods
  20207. VertexBuffer.prototype.create = function (data) {
  20208. return this._buffer.create(data);
  20209. };
  20210. VertexBuffer.prototype.update = function (data) {
  20211. return this._buffer.update(data);
  20212. };
  20213. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  20214. return this._buffer.updateDirectly(data, offset);
  20215. };
  20216. VertexBuffer.prototype.dispose = function () {
  20217. if (this._ownsBuffer) {
  20218. this._buffer.dispose();
  20219. }
  20220. };
  20221. Object.defineProperty(VertexBuffer, "PositionKind", {
  20222. get: function () {
  20223. return VertexBuffer._PositionKind;
  20224. },
  20225. enumerable: true,
  20226. configurable: true
  20227. });
  20228. Object.defineProperty(VertexBuffer, "NormalKind", {
  20229. get: function () {
  20230. return VertexBuffer._NormalKind;
  20231. },
  20232. enumerable: true,
  20233. configurable: true
  20234. });
  20235. Object.defineProperty(VertexBuffer, "UVKind", {
  20236. get: function () {
  20237. return VertexBuffer._UVKind;
  20238. },
  20239. enumerable: true,
  20240. configurable: true
  20241. });
  20242. Object.defineProperty(VertexBuffer, "UV2Kind", {
  20243. get: function () {
  20244. return VertexBuffer._UV2Kind;
  20245. },
  20246. enumerable: true,
  20247. configurable: true
  20248. });
  20249. Object.defineProperty(VertexBuffer, "UV3Kind", {
  20250. get: function () {
  20251. return VertexBuffer._UV3Kind;
  20252. },
  20253. enumerable: true,
  20254. configurable: true
  20255. });
  20256. Object.defineProperty(VertexBuffer, "UV4Kind", {
  20257. get: function () {
  20258. return VertexBuffer._UV4Kind;
  20259. },
  20260. enumerable: true,
  20261. configurable: true
  20262. });
  20263. Object.defineProperty(VertexBuffer, "UV5Kind", {
  20264. get: function () {
  20265. return VertexBuffer._UV5Kind;
  20266. },
  20267. enumerable: true,
  20268. configurable: true
  20269. });
  20270. Object.defineProperty(VertexBuffer, "UV6Kind", {
  20271. get: function () {
  20272. return VertexBuffer._UV6Kind;
  20273. },
  20274. enumerable: true,
  20275. configurable: true
  20276. });
  20277. Object.defineProperty(VertexBuffer, "ColorKind", {
  20278. get: function () {
  20279. return VertexBuffer._ColorKind;
  20280. },
  20281. enumerable: true,
  20282. configurable: true
  20283. });
  20284. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  20285. get: function () {
  20286. return VertexBuffer._MatricesIndicesKind;
  20287. },
  20288. enumerable: true,
  20289. configurable: true
  20290. });
  20291. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  20292. get: function () {
  20293. return VertexBuffer._MatricesWeightsKind;
  20294. },
  20295. enumerable: true,
  20296. configurable: true
  20297. });
  20298. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  20299. get: function () {
  20300. return VertexBuffer._MatricesIndicesExtraKind;
  20301. },
  20302. enumerable: true,
  20303. configurable: true
  20304. });
  20305. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  20306. get: function () {
  20307. return VertexBuffer._MatricesWeightsExtraKind;
  20308. },
  20309. enumerable: true,
  20310. configurable: true
  20311. });
  20312. return VertexBuffer;
  20313. }());
  20314. // Enums
  20315. VertexBuffer._PositionKind = "position";
  20316. VertexBuffer._NormalKind = "normal";
  20317. VertexBuffer._UVKind = "uv";
  20318. VertexBuffer._UV2Kind = "uv2";
  20319. VertexBuffer._UV3Kind = "uv3";
  20320. VertexBuffer._UV4Kind = "uv4";
  20321. VertexBuffer._UV5Kind = "uv5";
  20322. VertexBuffer._UV6Kind = "uv6";
  20323. VertexBuffer._ColorKind = "color";
  20324. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  20325. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  20326. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  20327. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  20328. BABYLON.VertexBuffer = VertexBuffer;
  20329. })(BABYLON || (BABYLON = {}));
  20330. //# sourceMappingURL=babylon.vertexBuffer.js.map
  20331. var BABYLON;
  20332. (function (BABYLON) {
  20333. /**
  20334. * Creates an instance based on a source mesh.
  20335. */
  20336. var InstancedMesh = (function (_super) {
  20337. __extends(InstancedMesh, _super);
  20338. function InstancedMesh(name, source) {
  20339. var _this = _super.call(this, name, source.getScene()) || this;
  20340. source.instances.push(_this);
  20341. _this._sourceMesh = source;
  20342. _this.position.copyFrom(source.position);
  20343. _this.rotation.copyFrom(source.rotation);
  20344. _this.scaling.copyFrom(source.scaling);
  20345. if (source.rotationQuaternion) {
  20346. _this.rotationQuaternion = source.rotationQuaternion.clone();
  20347. }
  20348. _this.infiniteDistance = source.infiniteDistance;
  20349. _this.setPivotMatrix(source.getPivotMatrix());
  20350. _this.refreshBoundingInfo();
  20351. _this._syncSubMeshes();
  20352. return _this;
  20353. }
  20354. InstancedMesh.prototype.getClassName = function () {
  20355. return "InstancedMesh";
  20356. };
  20357. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  20358. // Methods
  20359. get: function () {
  20360. return this._sourceMesh.receiveShadows;
  20361. },
  20362. enumerable: true,
  20363. configurable: true
  20364. });
  20365. Object.defineProperty(InstancedMesh.prototype, "material", {
  20366. get: function () {
  20367. return this._sourceMesh.material;
  20368. },
  20369. enumerable: true,
  20370. configurable: true
  20371. });
  20372. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  20373. get: function () {
  20374. return this._sourceMesh.visibility;
  20375. },
  20376. enumerable: true,
  20377. configurable: true
  20378. });
  20379. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  20380. get: function () {
  20381. return this._sourceMesh.skeleton;
  20382. },
  20383. enumerable: true,
  20384. configurable: true
  20385. });
  20386. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  20387. get: function () {
  20388. return this._sourceMesh.renderingGroupId;
  20389. },
  20390. enumerable: true,
  20391. configurable: true
  20392. });
  20393. InstancedMesh.prototype.getTotalVertices = function () {
  20394. return this._sourceMesh.getTotalVertices();
  20395. };
  20396. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  20397. get: function () {
  20398. return this._sourceMesh;
  20399. },
  20400. enumerable: true,
  20401. configurable: true
  20402. });
  20403. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  20404. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  20405. };
  20406. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  20407. return this._sourceMesh.isVerticesDataPresent(kind);
  20408. };
  20409. InstancedMesh.prototype.getIndices = function () {
  20410. return this._sourceMesh.getIndices();
  20411. };
  20412. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  20413. get: function () {
  20414. return this._sourceMesh._positions;
  20415. },
  20416. enumerable: true,
  20417. configurable: true
  20418. });
  20419. InstancedMesh.prototype.refreshBoundingInfo = function () {
  20420. var meshBB = this._sourceMesh.getBoundingInfo();
  20421. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  20422. this._updateBoundingInfo();
  20423. };
  20424. InstancedMesh.prototype._preActivate = function () {
  20425. if (this._currentLOD) {
  20426. this._currentLOD._preActivate();
  20427. }
  20428. };
  20429. InstancedMesh.prototype._activate = function (renderId) {
  20430. if (this._currentLOD) {
  20431. this._currentLOD._registerInstanceForRenderId(this, renderId);
  20432. }
  20433. };
  20434. InstancedMesh.prototype.getLOD = function (camera) {
  20435. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  20436. if (this._currentLOD === this.sourceMesh) {
  20437. return this;
  20438. }
  20439. return this._currentLOD;
  20440. };
  20441. InstancedMesh.prototype._syncSubMeshes = function () {
  20442. this.releaseSubMeshes();
  20443. if (this._sourceMesh.subMeshes) {
  20444. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  20445. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  20446. }
  20447. }
  20448. };
  20449. InstancedMesh.prototype._generatePointsArray = function () {
  20450. return this._sourceMesh._generatePointsArray();
  20451. };
  20452. // Clone
  20453. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20454. var result = this._sourceMesh.createInstance(name);
  20455. // Deep copy
  20456. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  20457. // Bounding info
  20458. this.refreshBoundingInfo();
  20459. // Parent
  20460. if (newParent) {
  20461. result.parent = newParent;
  20462. }
  20463. if (!doNotCloneChildren) {
  20464. // Children
  20465. for (var index = 0; index < this.getScene().meshes.length; index++) {
  20466. var mesh = this.getScene().meshes[index];
  20467. if (mesh.parent === this) {
  20468. mesh.clone(mesh.name, result);
  20469. }
  20470. }
  20471. }
  20472. result.computeWorldMatrix(true);
  20473. return result;
  20474. };
  20475. // Dispose
  20476. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  20477. // Remove from mesh
  20478. var index = this._sourceMesh.instances.indexOf(this);
  20479. this._sourceMesh.instances.splice(index, 1);
  20480. _super.prototype.dispose.call(this, doNotRecurse);
  20481. };
  20482. return InstancedMesh;
  20483. }(BABYLON.AbstractMesh));
  20484. BABYLON.InstancedMesh = InstancedMesh;
  20485. })(BABYLON || (BABYLON = {}));
  20486. //# sourceMappingURL=babylon.instancedMesh.js.map
  20487. var BABYLON;
  20488. (function (BABYLON) {
  20489. var _InstancesBatch = (function () {
  20490. function _InstancesBatch() {
  20491. this.mustReturn = false;
  20492. this.visibleInstances = new Array();
  20493. this.renderSelf = new Array();
  20494. }
  20495. return _InstancesBatch;
  20496. }());
  20497. BABYLON._InstancesBatch = _InstancesBatch;
  20498. var Mesh = (function (_super) {
  20499. __extends(Mesh, _super);
  20500. /**
  20501. * @constructor
  20502. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20503. * @param {Scene} scene The scene to add this mesh to.
  20504. * @param {Node} parent The parent of this mesh, if it has one
  20505. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20506. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20507. * When false, achieved by calling a clone(), also passing False.
  20508. * This will make creation of children, recursive.
  20509. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20510. */
  20511. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20512. if (parent === void 0) { parent = null; }
  20513. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20514. var _this = _super.call(this, name, scene) || this;
  20515. // Events
  20516. /**
  20517. * An event triggered before rendering the mesh
  20518. * @type {BABYLON.Observable}
  20519. */
  20520. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20521. /**
  20522. * An event triggered after rendering the mesh
  20523. * @type {BABYLON.Observable}
  20524. */
  20525. _this.onAfterRenderObservable = new BABYLON.Observable();
  20526. /**
  20527. * An event triggered before drawing the mesh
  20528. * @type {BABYLON.Observable}
  20529. */
  20530. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20531. // Members
  20532. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20533. _this.instances = new Array();
  20534. _this._LODLevels = new Array();
  20535. _this._visibleInstances = {};
  20536. _this._renderIdForInstances = new Array();
  20537. _this._batchCache = new _InstancesBatch();
  20538. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20539. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20540. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20541. // Will be used to save a source mesh reference, If any
  20542. _this._source = null;
  20543. if (source) {
  20544. // Source mesh
  20545. _this._source = source;
  20546. // Geometry
  20547. if (source._geometry) {
  20548. source._geometry.applyToMesh(_this);
  20549. }
  20550. // Deep copy
  20551. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  20552. // Parent
  20553. _this.parent = source.parent;
  20554. // Pivot
  20555. _this.setPivotMatrix(source.getPivotMatrix());
  20556. _this.id = name + "." + source.id;
  20557. // Material
  20558. _this.material = source.material;
  20559. var index;
  20560. if (!doNotCloneChildren) {
  20561. // Children
  20562. for (index = 0; index < scene.meshes.length; index++) {
  20563. var mesh = scene.meshes[index];
  20564. if (mesh.parent === source) {
  20565. // doNotCloneChildren is always going to be False
  20566. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20567. }
  20568. }
  20569. }
  20570. // Physics clone
  20571. var physicsEngine = _this.getScene().getPhysicsEngine();
  20572. if (clonePhysicsImpostor && physicsEngine) {
  20573. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20574. if (impostor) {
  20575. _this.physicsImpostor = impostor.clone(_this);
  20576. }
  20577. }
  20578. // Particles
  20579. for (index = 0; index < scene.particleSystems.length; index++) {
  20580. var system = scene.particleSystems[index];
  20581. if (system.emitter === source) {
  20582. system.clone(system.name, _this);
  20583. }
  20584. }
  20585. _this.computeWorldMatrix(true);
  20586. }
  20587. // Parent
  20588. if (parent !== null) {
  20589. _this.parent = parent;
  20590. }
  20591. return _this;
  20592. }
  20593. Object.defineProperty(Mesh, "FRONTSIDE", {
  20594. /**
  20595. * Mesh side orientation : usually the external or front surface
  20596. */
  20597. get: function () {
  20598. return Mesh._FRONTSIDE;
  20599. },
  20600. enumerable: true,
  20601. configurable: true
  20602. });
  20603. Object.defineProperty(Mesh, "BACKSIDE", {
  20604. /**
  20605. * Mesh side orientation : usually the internal or back surface
  20606. */
  20607. get: function () {
  20608. return Mesh._BACKSIDE;
  20609. },
  20610. enumerable: true,
  20611. configurable: true
  20612. });
  20613. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20614. /**
  20615. * Mesh side orientation : both internal and external or front and back surfaces
  20616. */
  20617. get: function () {
  20618. return Mesh._DOUBLESIDE;
  20619. },
  20620. enumerable: true,
  20621. configurable: true
  20622. });
  20623. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20624. /**
  20625. * Mesh side orientation : by default, `FRONTSIDE`
  20626. */
  20627. get: function () {
  20628. return Mesh._DEFAULTSIDE;
  20629. },
  20630. enumerable: true,
  20631. configurable: true
  20632. });
  20633. Object.defineProperty(Mesh, "NO_CAP", {
  20634. /**
  20635. * Mesh cap setting : no cap
  20636. */
  20637. get: function () {
  20638. return Mesh._NO_CAP;
  20639. },
  20640. enumerable: true,
  20641. configurable: true
  20642. });
  20643. Object.defineProperty(Mesh, "CAP_START", {
  20644. /**
  20645. * Mesh cap setting : one cap at the beginning of the mesh
  20646. */
  20647. get: function () {
  20648. return Mesh._CAP_START;
  20649. },
  20650. enumerable: true,
  20651. configurable: true
  20652. });
  20653. Object.defineProperty(Mesh, "CAP_END", {
  20654. /**
  20655. * Mesh cap setting : one cap at the end of the mesh
  20656. */
  20657. get: function () {
  20658. return Mesh._CAP_END;
  20659. },
  20660. enumerable: true,
  20661. configurable: true
  20662. });
  20663. Object.defineProperty(Mesh, "CAP_ALL", {
  20664. /**
  20665. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  20666. */
  20667. get: function () {
  20668. return Mesh._CAP_ALL;
  20669. },
  20670. enumerable: true,
  20671. configurable: true
  20672. });
  20673. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  20674. set: function (callback) {
  20675. if (this._onBeforeDrawObserver) {
  20676. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  20677. }
  20678. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  20679. },
  20680. enumerable: true,
  20681. configurable: true
  20682. });
  20683. Object.defineProperty(Mesh.prototype, "source", {
  20684. get: function () {
  20685. return this._source;
  20686. },
  20687. enumerable: true,
  20688. configurable: true
  20689. });
  20690. // Methods
  20691. Mesh.prototype.getClassName = function () {
  20692. return "Mesh";
  20693. };
  20694. /**
  20695. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  20696. */
  20697. Mesh.prototype.toString = function (fullDetails) {
  20698. var ret = _super.prototype.toString.call(this, fullDetails);
  20699. ret += ", n vertices: " + this.getTotalVertices();
  20700. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  20701. if (this.animations) {
  20702. for (var i = 0; i < this.animations.length; i++) {
  20703. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  20704. }
  20705. }
  20706. if (fullDetails) {
  20707. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  20708. }
  20709. return ret;
  20710. };
  20711. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  20712. get: function () {
  20713. return this._LODLevels.length > 0;
  20714. },
  20715. enumerable: true,
  20716. configurable: true
  20717. });
  20718. Mesh.prototype._sortLODLevels = function () {
  20719. this._LODLevels.sort(function (a, b) {
  20720. if (a.distance < b.distance) {
  20721. return 1;
  20722. }
  20723. if (a.distance > b.distance) {
  20724. return -1;
  20725. }
  20726. return 0;
  20727. });
  20728. };
  20729. /**
  20730. * Add a mesh as LOD level triggered at the given distance.
  20731. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20732. * @param {number} distance The distance from the center of the object to show this level
  20733. * @param {Mesh} mesh The mesh to be added as LOD level
  20734. * @return {Mesh} This mesh (for chaining)
  20735. */
  20736. Mesh.prototype.addLODLevel = function (distance, mesh) {
  20737. if (mesh && mesh._masterMesh) {
  20738. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  20739. return this;
  20740. }
  20741. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  20742. this._LODLevels.push(level);
  20743. if (mesh) {
  20744. mesh._masterMesh = this;
  20745. }
  20746. this._sortLODLevels();
  20747. return this;
  20748. };
  20749. /**
  20750. * Returns the LOD level mesh at the passed distance or null if not found.
  20751. * It is related to the method `addLODLevel(distance, mesh)`.
  20752. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20753. */
  20754. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  20755. for (var index = 0; index < this._LODLevels.length; index++) {
  20756. var level = this._LODLevels[index];
  20757. if (level.distance === distance) {
  20758. return level.mesh;
  20759. }
  20760. }
  20761. return null;
  20762. };
  20763. /**
  20764. * Remove a mesh from the LOD array
  20765. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20766. * @param {Mesh} mesh The mesh to be removed.
  20767. * @return {Mesh} This mesh (for chaining)
  20768. */
  20769. Mesh.prototype.removeLODLevel = function (mesh) {
  20770. for (var index = 0; index < this._LODLevels.length; index++) {
  20771. if (this._LODLevels[index].mesh === mesh) {
  20772. this._LODLevels.splice(index, 1);
  20773. if (mesh) {
  20774. mesh._masterMesh = null;
  20775. }
  20776. }
  20777. }
  20778. this._sortLODLevels();
  20779. return this;
  20780. };
  20781. /**
  20782. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  20783. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  20784. */
  20785. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  20786. if (!this._LODLevels || this._LODLevels.length === 0) {
  20787. return this;
  20788. }
  20789. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  20790. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  20791. if (this.onLODLevelSelection) {
  20792. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  20793. }
  20794. return this;
  20795. }
  20796. for (var index = 0; index < this._LODLevels.length; index++) {
  20797. var level = this._LODLevels[index];
  20798. if (level.distance < distanceToCamera) {
  20799. if (level.mesh) {
  20800. level.mesh._preActivate();
  20801. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20802. }
  20803. if (this.onLODLevelSelection) {
  20804. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  20805. }
  20806. return level.mesh;
  20807. }
  20808. }
  20809. if (this.onLODLevelSelection) {
  20810. this.onLODLevelSelection(distanceToCamera, this, this);
  20811. }
  20812. return this;
  20813. };
  20814. Object.defineProperty(Mesh.prototype, "geometry", {
  20815. /**
  20816. * Returns the mesh internal Geometry object.
  20817. */
  20818. get: function () {
  20819. return this._geometry;
  20820. },
  20821. enumerable: true,
  20822. configurable: true
  20823. });
  20824. /**
  20825. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  20826. */
  20827. Mesh.prototype.getTotalVertices = function () {
  20828. if (!this._geometry) {
  20829. return 0;
  20830. }
  20831. return this._geometry.getTotalVertices();
  20832. };
  20833. /**
  20834. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  20835. * 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.
  20836. * Returns null if the mesh has no geometry or no vertex buffer.
  20837. * Possible `kind` values :
  20838. * - BABYLON.VertexBuffer.PositionKind
  20839. * - BABYLON.VertexBuffer.UVKind
  20840. * - BABYLON.VertexBuffer.UV2Kind
  20841. * - BABYLON.VertexBuffer.UV3Kind
  20842. * - BABYLON.VertexBuffer.UV4Kind
  20843. * - BABYLON.VertexBuffer.UV5Kind
  20844. * - BABYLON.VertexBuffer.UV6Kind
  20845. * - BABYLON.VertexBuffer.ColorKind
  20846. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20847. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20848. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20849. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20850. */
  20851. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  20852. if (!this._geometry) {
  20853. return null;
  20854. }
  20855. return this._geometry.getVerticesData(kind, copyWhenShared);
  20856. };
  20857. /**
  20858. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  20859. * Returns `undefined` if the mesh has no geometry.
  20860. * Possible `kind` values :
  20861. * - BABYLON.VertexBuffer.PositionKind
  20862. * - BABYLON.VertexBuffer.UVKind
  20863. * - BABYLON.VertexBuffer.UV2Kind
  20864. * - BABYLON.VertexBuffer.UV3Kind
  20865. * - BABYLON.VertexBuffer.UV4Kind
  20866. * - BABYLON.VertexBuffer.UV5Kind
  20867. * - BABYLON.VertexBuffer.UV6Kind
  20868. * - BABYLON.VertexBuffer.ColorKind
  20869. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20870. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20871. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20872. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20873. */
  20874. Mesh.prototype.getVertexBuffer = function (kind) {
  20875. if (!this._geometry) {
  20876. return undefined;
  20877. }
  20878. return this._geometry.getVertexBuffer(kind);
  20879. };
  20880. /**
  20881. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20882. * Possible `kind` values :
  20883. * - BABYLON.VertexBuffer.PositionKind
  20884. * - BABYLON.VertexBuffer.UVKind
  20885. * - BABYLON.VertexBuffer.UV2Kind
  20886. * - BABYLON.VertexBuffer.UV3Kind
  20887. * - BABYLON.VertexBuffer.UV4Kind
  20888. * - BABYLON.VertexBuffer.UV5Kind
  20889. * - BABYLON.VertexBuffer.UV6Kind
  20890. * - BABYLON.VertexBuffer.ColorKind
  20891. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20892. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20893. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20894. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20895. */
  20896. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20897. if (!this._geometry) {
  20898. if (this._delayInfo) {
  20899. return this._delayInfo.indexOf(kind) !== -1;
  20900. }
  20901. return false;
  20902. }
  20903. return this._geometry.isVerticesDataPresent(kind);
  20904. };
  20905. /**
  20906. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20907. * Possible `kind` values :
  20908. * - BABYLON.VertexBuffer.PositionKind
  20909. * - BABYLON.VertexBuffer.UVKind
  20910. * - BABYLON.VertexBuffer.UV2Kind
  20911. * - BABYLON.VertexBuffer.UV3Kind
  20912. * - BABYLON.VertexBuffer.UV4Kind
  20913. * - BABYLON.VertexBuffer.UV5Kind
  20914. * - BABYLON.VertexBuffer.UV6Kind
  20915. * - BABYLON.VertexBuffer.ColorKind
  20916. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20917. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20918. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20919. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20920. */
  20921. Mesh.prototype.getVerticesDataKinds = function () {
  20922. if (!this._geometry) {
  20923. var result = [];
  20924. if (this._delayInfo) {
  20925. this._delayInfo.forEach(function (kind, index, array) {
  20926. result.push(kind);
  20927. });
  20928. }
  20929. return result;
  20930. }
  20931. return this._geometry.getVerticesDataKinds();
  20932. };
  20933. /**
  20934. * Returns a positive integer : the total number of indices in this mesh geometry.
  20935. * Returns zero if the mesh has no geometry.
  20936. */
  20937. Mesh.prototype.getTotalIndices = function () {
  20938. if (!this._geometry) {
  20939. return 0;
  20940. }
  20941. return this._geometry.getTotalIndices();
  20942. };
  20943. /**
  20944. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  20945. * 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.
  20946. * Returns an empty array if the mesh has no geometry.
  20947. */
  20948. Mesh.prototype.getIndices = function (copyWhenShared) {
  20949. if (!this._geometry) {
  20950. return [];
  20951. }
  20952. return this._geometry.getIndices(copyWhenShared);
  20953. };
  20954. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20955. get: function () {
  20956. return this._masterMesh !== null && this._masterMesh !== undefined;
  20957. },
  20958. enumerable: true,
  20959. configurable: true
  20960. });
  20961. /**
  20962. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20963. */
  20964. Mesh.prototype.isReady = function () {
  20965. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20966. return false;
  20967. }
  20968. return _super.prototype.isReady.call(this);
  20969. };
  20970. /**
  20971. * Boolean : true if the mesh has been disposed.
  20972. */
  20973. Mesh.prototype.isDisposed = function () {
  20974. return this._isDisposed;
  20975. };
  20976. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20977. get: function () {
  20978. return this._sideOrientation;
  20979. },
  20980. /**
  20981. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20982. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20983. */
  20984. set: function (sideO) {
  20985. this._sideOrientation = sideO;
  20986. },
  20987. enumerable: true,
  20988. configurable: true
  20989. });
  20990. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20991. /**
  20992. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20993. * This property is pertinent only for updatable parametric shapes.
  20994. */
  20995. get: function () {
  20996. return this._areNormalsFrozen;
  20997. },
  20998. enumerable: true,
  20999. configurable: true
  21000. });
  21001. /**
  21002. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21003. * It has no effect at all on other shapes.
  21004. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21005. */
  21006. Mesh.prototype.freezeNormals = function () {
  21007. this._areNormalsFrozen = true;
  21008. };
  21009. /**
  21010. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21011. * It has no effect at all on other shapes.
  21012. * It reactivates the mesh normals computation if it was previously frozen.
  21013. */
  21014. Mesh.prototype.unfreezeNormals = function () {
  21015. this._areNormalsFrozen = false;
  21016. };
  21017. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21018. /**
  21019. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21020. */
  21021. set: function (count) {
  21022. this._overridenInstanceCount = count;
  21023. },
  21024. enumerable: true,
  21025. configurable: true
  21026. });
  21027. // Methods
  21028. Mesh.prototype._preActivate = function () {
  21029. var sceneRenderId = this.getScene().getRenderId();
  21030. if (this._preActivateId === sceneRenderId) {
  21031. return;
  21032. }
  21033. this._preActivateId = sceneRenderId;
  21034. this._visibleInstances = null;
  21035. };
  21036. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21037. if (this._visibleInstances) {
  21038. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21039. }
  21040. };
  21041. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21042. if (!this._visibleInstances) {
  21043. this._visibleInstances = {};
  21044. this._visibleInstances.defaultRenderId = renderId;
  21045. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21046. }
  21047. if (!this._visibleInstances[renderId]) {
  21048. this._visibleInstances[renderId] = new Array();
  21049. }
  21050. this._visibleInstances[renderId].push(instance);
  21051. };
  21052. /**
  21053. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21054. * This means the mesh underlying bounding box and sphere are recomputed.
  21055. */
  21056. Mesh.prototype.refreshBoundingInfo = function () {
  21057. if (this._boundingInfo.isLocked) {
  21058. return;
  21059. }
  21060. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21061. if (data) {
  21062. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21063. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21064. }
  21065. if (this.subMeshes) {
  21066. for (var index = 0; index < this.subMeshes.length; index++) {
  21067. this.subMeshes[index].refreshBoundingInfo();
  21068. }
  21069. }
  21070. this._updateBoundingInfo();
  21071. };
  21072. Mesh.prototype._createGlobalSubMesh = function () {
  21073. var totalVertices = this.getTotalVertices();
  21074. if (!totalVertices || !this.getIndices()) {
  21075. return null;
  21076. }
  21077. this.releaseSubMeshes();
  21078. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21079. };
  21080. Mesh.prototype.subdivide = function (count) {
  21081. if (count < 1) {
  21082. return;
  21083. }
  21084. var totalIndices = this.getTotalIndices();
  21085. var subdivisionSize = (totalIndices / count) | 0;
  21086. var offset = 0;
  21087. // Ensure that subdivisionSize is a multiple of 3
  21088. while (subdivisionSize % 3 !== 0) {
  21089. subdivisionSize++;
  21090. }
  21091. this.releaseSubMeshes();
  21092. for (var index = 0; index < count; index++) {
  21093. if (offset >= totalIndices) {
  21094. break;
  21095. }
  21096. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21097. offset += subdivisionSize;
  21098. }
  21099. this.synchronizeInstances();
  21100. };
  21101. /**
  21102. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21103. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21104. * The `data` are either a numeric array either a Float32Array.
  21105. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21106. * 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).
  21107. * Note that a new underlying VertexBuffer object is created each call.
  21108. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21109. *
  21110. * Possible `kind` values :
  21111. * - BABYLON.VertexBuffer.PositionKind
  21112. * - BABYLON.VertexBuffer.UVKind
  21113. * - BABYLON.VertexBuffer.UV2Kind
  21114. * - BABYLON.VertexBuffer.UV3Kind
  21115. * - BABYLON.VertexBuffer.UV4Kind
  21116. * - BABYLON.VertexBuffer.UV5Kind
  21117. * - BABYLON.VertexBuffer.UV6Kind
  21118. * - BABYLON.VertexBuffer.ColorKind
  21119. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21120. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21121. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21122. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21123. */
  21124. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21125. if (!this._geometry) {
  21126. var vertexData = new BABYLON.VertexData();
  21127. vertexData.set(data, kind);
  21128. var scene = this.getScene();
  21129. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21130. }
  21131. else {
  21132. this._geometry.setVerticesData(kind, data, updatable, stride);
  21133. }
  21134. };
  21135. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21136. if (!this._geometry) {
  21137. var scene = this.getScene();
  21138. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21139. }
  21140. this._geometry.setVerticesBuffer(buffer);
  21141. };
  21142. /**
  21143. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21144. * If the mesh has no geometry, it is simply returned as it is.
  21145. * The `data` are either a numeric array either a Float32Array.
  21146. * No new underlying VertexBuffer object is created.
  21147. * 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.
  21148. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21149. *
  21150. * Possible `kind` values :
  21151. * - BABYLON.VertexBuffer.PositionKind
  21152. * - BABYLON.VertexBuffer.UVKind
  21153. * - BABYLON.VertexBuffer.UV2Kind
  21154. * - BABYLON.VertexBuffer.UV3Kind
  21155. * - BABYLON.VertexBuffer.UV4Kind
  21156. * - BABYLON.VertexBuffer.UV5Kind
  21157. * - BABYLON.VertexBuffer.UV6Kind
  21158. * - BABYLON.VertexBuffer.ColorKind
  21159. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21160. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21161. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21162. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21163. */
  21164. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21165. if (!this._geometry) {
  21166. return;
  21167. }
  21168. if (!makeItUnique) {
  21169. this._geometry.updateVerticesData(kind, data, updateExtends);
  21170. }
  21171. else {
  21172. this.makeGeometryUnique();
  21173. this.updateVerticesData(kind, data, updateExtends, false);
  21174. }
  21175. };
  21176. /**
  21177. * Deprecated since BabylonJS v2.3
  21178. */
  21179. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  21180. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  21181. if (!this._geometry) {
  21182. return;
  21183. }
  21184. if (!makeItUnique) {
  21185. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  21186. }
  21187. else {
  21188. this.makeGeometryUnique();
  21189. this.updateVerticesDataDirectly(kind, data, offset, false);
  21190. }
  21191. };
  21192. /**
  21193. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21194. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21195. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21196. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21197. */
  21198. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21199. if (computeNormals === void 0) { computeNormals = true; }
  21200. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21201. positionFunction(positions);
  21202. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21203. if (computeNormals) {
  21204. var indices = this.getIndices();
  21205. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21206. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21207. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21208. }
  21209. };
  21210. Mesh.prototype.makeGeometryUnique = function () {
  21211. if (!this._geometry) {
  21212. return;
  21213. }
  21214. var oldGeometry = this._geometry;
  21215. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21216. oldGeometry.releaseForMesh(this, true);
  21217. geometry.applyToMesh(this);
  21218. };
  21219. /**
  21220. * Sets the mesh indices.
  21221. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21222. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21223. * This method creates a new index buffer each call.
  21224. */
  21225. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21226. if (!this._geometry) {
  21227. var vertexData = new BABYLON.VertexData();
  21228. vertexData.indices = indices;
  21229. var scene = this.getScene();
  21230. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21231. }
  21232. else {
  21233. this._geometry.setIndices(indices, totalVertices);
  21234. }
  21235. };
  21236. /**
  21237. * Invert the geometry to move from a right handed system to a left handed one.
  21238. */
  21239. Mesh.prototype.toLeftHanded = function () {
  21240. if (!this._geometry) {
  21241. return;
  21242. }
  21243. this._geometry.toLeftHanded();
  21244. };
  21245. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21246. var engine = this.getScene().getEngine();
  21247. // Wireframe
  21248. var indexToBind;
  21249. if (this._unIndexed) {
  21250. indexToBind = null;
  21251. }
  21252. else {
  21253. switch (fillMode) {
  21254. case BABYLON.Material.PointFillMode:
  21255. indexToBind = null;
  21256. break;
  21257. case BABYLON.Material.WireFrameFillMode:
  21258. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21259. break;
  21260. default:
  21261. case BABYLON.Material.TriangleFillMode:
  21262. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21263. break;
  21264. }
  21265. }
  21266. // VBOs
  21267. this._geometry._bind(effect, indexToBind);
  21268. };
  21269. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21270. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21271. return;
  21272. }
  21273. this.onBeforeDrawObservable.notifyObservers(this);
  21274. var engine = this.getScene().getEngine();
  21275. // Draw order
  21276. switch (fillMode) {
  21277. case BABYLON.Material.PointFillMode:
  21278. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21279. break;
  21280. case BABYLON.Material.WireFrameFillMode:
  21281. if (this._unIndexed) {
  21282. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21283. }
  21284. else {
  21285. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  21286. }
  21287. break;
  21288. default:
  21289. if (this._unIndexed) {
  21290. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21291. }
  21292. else {
  21293. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21294. }
  21295. }
  21296. };
  21297. /**
  21298. * Registers for this mesh a javascript function called just before the rendering process.
  21299. * This function is passed the current mesh and doesn't return anything.
  21300. */
  21301. Mesh.prototype.registerBeforeRender = function (func) {
  21302. this.onBeforeRenderObservable.add(func);
  21303. };
  21304. /**
  21305. * Disposes a previously registered javascript function called before the rendering.
  21306. * This function is passed the current mesh and doesn't return anything.
  21307. */
  21308. Mesh.prototype.unregisterBeforeRender = function (func) {
  21309. this.onBeforeRenderObservable.removeCallback(func);
  21310. };
  21311. /**
  21312. * Registers for this mesh a javascript function called just after the rendering is complete.
  21313. * This function is passed the current mesh and doesn't return anything.
  21314. */
  21315. Mesh.prototype.registerAfterRender = function (func) {
  21316. this.onAfterRenderObservable.add(func);
  21317. };
  21318. /**
  21319. * Disposes a previously registered javascript function called after the rendering.
  21320. * This function is passed the current mesh and doesn't return anything.
  21321. */
  21322. Mesh.prototype.unregisterAfterRender = function (func) {
  21323. this.onAfterRenderObservable.removeCallback(func);
  21324. };
  21325. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21326. var scene = this.getScene();
  21327. this._batchCache.mustReturn = false;
  21328. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21329. this._batchCache.visibleInstances[subMeshId] = null;
  21330. if (this._visibleInstances) {
  21331. var currentRenderId = scene.getRenderId();
  21332. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21333. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21334. var selfRenderId = this._renderId;
  21335. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21336. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21337. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21338. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21339. }
  21340. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21341. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21342. this._batchCache.mustReturn = true;
  21343. return this._batchCache;
  21344. }
  21345. if (currentRenderId !== selfRenderId) {
  21346. this._batchCache.renderSelf[subMeshId] = false;
  21347. }
  21348. }
  21349. this._renderIdForInstances[subMeshId] = currentRenderId;
  21350. }
  21351. return this._batchCache;
  21352. };
  21353. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21354. var visibleInstances = batch.visibleInstances[subMesh._id];
  21355. var matricesCount = visibleInstances.length + 1;
  21356. var bufferSize = matricesCount * 16 * 4;
  21357. var currentInstancesBufferSize = this._instancesBufferSize;
  21358. var instancesBuffer = this._instancesBuffer;
  21359. while (this._instancesBufferSize < bufferSize) {
  21360. this._instancesBufferSize *= 2;
  21361. }
  21362. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21363. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21364. }
  21365. var offset = 0;
  21366. var instancesCount = 0;
  21367. var world = this.getWorldMatrix();
  21368. if (batch.renderSelf[subMesh._id]) {
  21369. world.copyToArray(this._instancesData, offset);
  21370. offset += 16;
  21371. instancesCount++;
  21372. }
  21373. if (visibleInstances) {
  21374. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21375. var instance = visibleInstances[instanceIndex];
  21376. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21377. offset += 16;
  21378. instancesCount++;
  21379. }
  21380. }
  21381. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21382. if (instancesBuffer) {
  21383. instancesBuffer.dispose();
  21384. }
  21385. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21386. this._instancesBuffer = instancesBuffer;
  21387. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21388. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21389. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21390. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21391. }
  21392. else {
  21393. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21394. }
  21395. this.geometry._bind(effect);
  21396. this._draw(subMesh, fillMode, instancesCount);
  21397. engine.unbindInstanceAttributes();
  21398. };
  21399. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21400. var scene = this.getScene();
  21401. var engine = scene.getEngine();
  21402. if (hardwareInstancedRendering) {
  21403. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21404. }
  21405. else {
  21406. if (batch.renderSelf[subMesh._id]) {
  21407. // Draw
  21408. if (onBeforeDraw) {
  21409. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21410. }
  21411. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21412. }
  21413. if (batch.visibleInstances[subMesh._id]) {
  21414. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21415. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21416. // World
  21417. var world = instance.getWorldMatrix();
  21418. if (onBeforeDraw) {
  21419. onBeforeDraw(true, world, effectiveMaterial);
  21420. }
  21421. // Draw
  21422. this._draw(subMesh, fillMode);
  21423. }
  21424. }
  21425. }
  21426. };
  21427. /**
  21428. * Triggers the draw call for the mesh.
  21429. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21430. */
  21431. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21432. var scene = this.getScene();
  21433. // Managing instances
  21434. var batch = this._getInstancesRenderList(subMesh._id);
  21435. if (batch.mustReturn) {
  21436. return;
  21437. }
  21438. // Checking geometry state
  21439. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21440. return;
  21441. }
  21442. var callbackIndex;
  21443. this.onBeforeRenderObservable.notifyObservers(this);
  21444. var engine = scene.getEngine();
  21445. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21446. // Material
  21447. var effectiveMaterial = subMesh.getMaterial();
  21448. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21449. return;
  21450. }
  21451. // Outline - step 1
  21452. var savedDepthWrite = engine.getDepthWrite();
  21453. if (this.renderOutline) {
  21454. engine.setDepthWrite(false);
  21455. scene.getOutlineRenderer().render(subMesh, batch);
  21456. engine.setDepthWrite(savedDepthWrite);
  21457. }
  21458. effectiveMaterial._preBind();
  21459. var effect = effectiveMaterial.getEffect();
  21460. // Bind
  21461. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21462. this._bind(subMesh, effect, fillMode);
  21463. var world = this.getWorldMatrix();
  21464. effectiveMaterial.bind(world, this);
  21465. // Alpha mode
  21466. if (enableAlphaMode) {
  21467. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21468. }
  21469. // Draw
  21470. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21471. // Unbind
  21472. effectiveMaterial.unbind();
  21473. // Outline - step 2
  21474. if (this.renderOutline && savedDepthWrite) {
  21475. engine.setDepthWrite(true);
  21476. engine.setColorWrite(false);
  21477. scene.getOutlineRenderer().render(subMesh, batch);
  21478. engine.setColorWrite(true);
  21479. }
  21480. // Overlay
  21481. if (this.renderOverlay) {
  21482. var currentMode = engine.getAlphaMode();
  21483. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21484. scene.getOutlineRenderer().render(subMesh, batch, true);
  21485. engine.setAlphaMode(currentMode);
  21486. }
  21487. this.onAfterRenderObservable.notifyObservers(this);
  21488. };
  21489. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21490. if (isInstance) {
  21491. effectiveMaterial.bindOnlyWorldMatrix(world);
  21492. }
  21493. };
  21494. /**
  21495. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21496. */
  21497. Mesh.prototype.getEmittedParticleSystems = function () {
  21498. var results = new Array();
  21499. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21500. var particleSystem = this.getScene().particleSystems[index];
  21501. if (particleSystem.emitter === this) {
  21502. results.push(particleSystem);
  21503. }
  21504. }
  21505. return results;
  21506. };
  21507. /**
  21508. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21509. */
  21510. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21511. var results = new Array();
  21512. var descendants = this.getDescendants();
  21513. descendants.push(this);
  21514. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21515. var particleSystem = this.getScene().particleSystems[index];
  21516. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  21517. results.push(particleSystem);
  21518. }
  21519. }
  21520. return results;
  21521. };
  21522. Mesh.prototype._checkDelayState = function () {
  21523. var scene = this.getScene();
  21524. if (this._geometry) {
  21525. this._geometry.load(scene);
  21526. }
  21527. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21528. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21529. this._queueLoad(this, scene);
  21530. }
  21531. };
  21532. Mesh.prototype._queueLoad = function (mesh, scene) {
  21533. var _this = this;
  21534. scene._addPendingData(mesh);
  21535. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21536. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21537. if (data instanceof ArrayBuffer) {
  21538. _this._delayLoadingFunction(data, _this);
  21539. }
  21540. else {
  21541. _this._delayLoadingFunction(JSON.parse(data), _this);
  21542. }
  21543. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21544. scene._removePendingData(_this);
  21545. }, function () { }, scene.database, getBinaryData);
  21546. };
  21547. /**
  21548. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21549. */
  21550. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  21551. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21552. return false;
  21553. }
  21554. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  21555. return false;
  21556. }
  21557. this._checkDelayState();
  21558. return true;
  21559. };
  21560. /**
  21561. * Sets the mesh material by the material or multiMaterial `id` property.
  21562. * The material `id` is a string identifying the material or the multiMaterial.
  21563. * This method returns nothing.
  21564. */
  21565. Mesh.prototype.setMaterialByID = function (id) {
  21566. var materials = this.getScene().materials;
  21567. var index;
  21568. for (index = 0; index < materials.length; index++) {
  21569. if (materials[index].id === id) {
  21570. this.material = materials[index];
  21571. return;
  21572. }
  21573. }
  21574. // Multi
  21575. var multiMaterials = this.getScene().multiMaterials;
  21576. for (index = 0; index < multiMaterials.length; index++) {
  21577. if (multiMaterials[index].id === id) {
  21578. this.material = multiMaterials[index];
  21579. return;
  21580. }
  21581. }
  21582. };
  21583. /**
  21584. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  21585. */
  21586. Mesh.prototype.getAnimatables = function () {
  21587. var results = [];
  21588. if (this.material) {
  21589. results.push(this.material);
  21590. }
  21591. if (this.skeleton) {
  21592. results.push(this.skeleton);
  21593. }
  21594. return results;
  21595. };
  21596. /**
  21597. * Modifies the mesh geometry according to the passed transformation matrix.
  21598. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  21599. * The mesh normals are modified accordingly the same transformation.
  21600. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21601. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21602. */
  21603. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  21604. // Position
  21605. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21606. return;
  21607. }
  21608. var submeshes = this.subMeshes.splice(0);
  21609. this._resetPointsArrayCache();
  21610. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21611. var temp = [];
  21612. var index;
  21613. for (index = 0; index < data.length; index += 3) {
  21614. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  21615. }
  21616. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  21617. // Normals
  21618. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21619. return;
  21620. }
  21621. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21622. temp = [];
  21623. for (index = 0; index < data.length; index += 3) {
  21624. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  21625. }
  21626. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  21627. // flip faces?
  21628. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  21629. this.flipFaces();
  21630. }
  21631. // Restore submeshes
  21632. this.releaseSubMeshes();
  21633. this.subMeshes = submeshes;
  21634. };
  21635. /**
  21636. * Modifies the mesh geometry according to its own current World Matrix.
  21637. * The mesh World Matrix is then reset.
  21638. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  21639. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  21640. * Note that, under the hood, this method sets a new VertexBuffer each call.
  21641. */
  21642. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  21643. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  21644. this.scaling.copyFromFloats(1, 1, 1);
  21645. this.position.copyFromFloats(0, 0, 0);
  21646. this.rotation.copyFromFloats(0, 0, 0);
  21647. //only if quaternion is already set
  21648. if (this.rotationQuaternion) {
  21649. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  21650. }
  21651. this._worldMatrix = BABYLON.Matrix.Identity();
  21652. };
  21653. // Cache
  21654. Mesh.prototype._resetPointsArrayCache = function () {
  21655. this._positions = null;
  21656. };
  21657. Mesh.prototype._generatePointsArray = function () {
  21658. if (this._positions)
  21659. return true;
  21660. this._positions = [];
  21661. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21662. if (!data) {
  21663. return false;
  21664. }
  21665. for (var index = 0; index < data.length; index += 3) {
  21666. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  21667. }
  21668. return true;
  21669. };
  21670. /**
  21671. * Returns a new Mesh object generated from the current mesh properties.
  21672. * This method must not get confused with createInstance().
  21673. * The parameter `name` is a string, the name given to the new mesh.
  21674. * The optional parameter `newParent` can be any Node object (default `null`).
  21675. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  21676. * 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.
  21677. */
  21678. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  21679. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  21680. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  21681. };
  21682. /**
  21683. * Disposes the mesh.
  21684. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  21685. */
  21686. Mesh.prototype.dispose = function (doNotRecurse) {
  21687. var _this = this;
  21688. if (this._geometry) {
  21689. this._geometry.releaseForMesh(this, true);
  21690. }
  21691. // Sources
  21692. var meshes = this.getScene().meshes;
  21693. meshes.forEach(function (mesh) {
  21694. if (mesh._source && mesh._source === _this) {
  21695. mesh._source = null;
  21696. }
  21697. });
  21698. this._source = null;
  21699. // Instances
  21700. if (this._instancesBuffer) {
  21701. this._instancesBuffer.dispose();
  21702. this._instancesBuffer = null;
  21703. }
  21704. while (this.instances.length) {
  21705. this.instances[0].dispose();
  21706. }
  21707. // Highlight layers.
  21708. var highlightLayers = this.getScene().highlightLayers;
  21709. for (var i = 0; i < highlightLayers.length; i++) {
  21710. var highlightLayer = highlightLayers[i];
  21711. if (highlightLayer) {
  21712. highlightLayer.removeMesh(this);
  21713. highlightLayer.removeExcludedMesh(this);
  21714. }
  21715. }
  21716. _super.prototype.dispose.call(this, doNotRecurse);
  21717. };
  21718. /**
  21719. * Modifies the mesh geometry according to a displacement map.
  21720. * 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.
  21721. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21722. * This method returns nothing.
  21723. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  21724. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21725. * 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.
  21726. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21727. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21728. */
  21729. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  21730. var _this = this;
  21731. var scene = this.getScene();
  21732. var onload = function (img) {
  21733. // Getting height map data
  21734. var canvas = document.createElement("canvas");
  21735. var context = canvas.getContext("2d");
  21736. var heightMapWidth = img.width;
  21737. var heightMapHeight = img.height;
  21738. canvas.width = heightMapWidth;
  21739. canvas.height = heightMapHeight;
  21740. context.drawImage(img, 0, 0);
  21741. // Create VertexData from map data
  21742. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  21743. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  21744. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  21745. //execute success callback, if set
  21746. if (onSuccess) {
  21747. onSuccess(_this);
  21748. }
  21749. };
  21750. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  21751. };
  21752. /**
  21753. * Modifies the mesh geometry according to a displacementMap buffer.
  21754. * 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.
  21755. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  21756. * This method returns nothing.
  21757. * 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.
  21758. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  21759. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  21760. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  21761. * The parameter `uvScale` is an optional vector2 used to scale UV.
  21762. */
  21763. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  21764. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  21765. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  21766. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  21767. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  21768. return;
  21769. }
  21770. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21771. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21772. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  21773. var position = BABYLON.Vector3.Zero();
  21774. var normal = BABYLON.Vector3.Zero();
  21775. var uv = BABYLON.Vector2.Zero();
  21776. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  21777. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  21778. for (var index = 0; index < positions.length; index += 3) {
  21779. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  21780. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  21781. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  21782. // Compute height
  21783. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  21784. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  21785. var pos = (u + v * heightMapWidth) * 4;
  21786. var r = buffer[pos] / 255.0;
  21787. var g = buffer[pos + 1] / 255.0;
  21788. var b = buffer[pos + 2] / 255.0;
  21789. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  21790. normal.normalize();
  21791. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  21792. position = position.add(normal);
  21793. position.toArray(positions, index);
  21794. }
  21795. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  21796. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  21797. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  21798. };
  21799. /**
  21800. * Modify the mesh to get a flat shading rendering.
  21801. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  21802. * This method returns nothing.
  21803. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  21804. */
  21805. Mesh.prototype.convertToFlatShadedMesh = function () {
  21806. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  21807. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21808. var kinds = this.getVerticesDataKinds();
  21809. var vbs = [];
  21810. var data = [];
  21811. var newdata = [];
  21812. var updatableNormals = false;
  21813. var kindIndex;
  21814. var kind;
  21815. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21816. kind = kinds[kindIndex];
  21817. var vertexBuffer = this.getVertexBuffer(kind);
  21818. if (kind === BABYLON.VertexBuffer.NormalKind) {
  21819. updatableNormals = vertexBuffer.isUpdatable();
  21820. kinds.splice(kindIndex, 1);
  21821. kindIndex--;
  21822. continue;
  21823. }
  21824. vbs[kind] = vertexBuffer;
  21825. data[kind] = vbs[kind].getData();
  21826. newdata[kind] = [];
  21827. }
  21828. // Save previous submeshes
  21829. var previousSubmeshes = this.subMeshes.slice(0);
  21830. var indices = this.getIndices();
  21831. var totalIndices = this.getTotalIndices();
  21832. // Generating unique vertices per face
  21833. var index;
  21834. for (index = 0; index < totalIndices; index++) {
  21835. var vertexIndex = indices[index];
  21836. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21837. kind = kinds[kindIndex];
  21838. var stride = vbs[kind].getStrideSize();
  21839. for (var offset = 0; offset < stride; offset++) {
  21840. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21841. }
  21842. }
  21843. }
  21844. // Updating faces & normal
  21845. var normals = [];
  21846. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  21847. for (index = 0; index < totalIndices; index += 3) {
  21848. indices[index] = index;
  21849. indices[index + 1] = index + 1;
  21850. indices[index + 2] = index + 2;
  21851. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  21852. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  21853. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  21854. var p1p2 = p1.subtract(p2);
  21855. var p3p2 = p3.subtract(p2);
  21856. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  21857. // Store same normals for every vertex
  21858. for (var localIndex = 0; localIndex < 3; localIndex++) {
  21859. normals.push(normal.x);
  21860. normals.push(normal.y);
  21861. normals.push(normal.z);
  21862. }
  21863. }
  21864. this.setIndices(indices);
  21865. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  21866. // Updating vertex buffers
  21867. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21868. kind = kinds[kindIndex];
  21869. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21870. }
  21871. // Updating submeshes
  21872. this.releaseSubMeshes();
  21873. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21874. var previousOne = previousSubmeshes[submeshIndex];
  21875. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21876. }
  21877. this.synchronizeInstances();
  21878. };
  21879. /**
  21880. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21881. * In other words, more vertices, no more indices and a single bigger VBO.
  21882. * This method returns nothing.
  21883. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21884. *
  21885. */
  21886. Mesh.prototype.convertToUnIndexedMesh = function () {
  21887. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21888. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21889. var kinds = this.getVerticesDataKinds();
  21890. var vbs = [];
  21891. var data = [];
  21892. var newdata = [];
  21893. var updatableNormals = false;
  21894. var kindIndex;
  21895. var kind;
  21896. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21897. kind = kinds[kindIndex];
  21898. var vertexBuffer = this.getVertexBuffer(kind);
  21899. vbs[kind] = vertexBuffer;
  21900. data[kind] = vbs[kind].getData();
  21901. newdata[kind] = [];
  21902. }
  21903. // Save previous submeshes
  21904. var previousSubmeshes = this.subMeshes.slice(0);
  21905. var indices = this.getIndices();
  21906. var totalIndices = this.getTotalIndices();
  21907. // Generating unique vertices per face
  21908. var index;
  21909. for (index = 0; index < totalIndices; index++) {
  21910. var vertexIndex = indices[index];
  21911. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21912. kind = kinds[kindIndex];
  21913. var stride = vbs[kind].getStrideSize();
  21914. for (var offset = 0; offset < stride; offset++) {
  21915. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21916. }
  21917. }
  21918. }
  21919. // Updating indices
  21920. for (index = 0; index < totalIndices; index += 3) {
  21921. indices[index] = index;
  21922. indices[index + 1] = index + 1;
  21923. indices[index + 2] = index + 2;
  21924. }
  21925. this.setIndices(indices);
  21926. // Updating vertex buffers
  21927. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21928. kind = kinds[kindIndex];
  21929. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21930. }
  21931. // Updating submeshes
  21932. this.releaseSubMeshes();
  21933. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21934. var previousOne = previousSubmeshes[submeshIndex];
  21935. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21936. }
  21937. this._unIndexed = true;
  21938. this.synchronizeInstances();
  21939. };
  21940. /**
  21941. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21942. * This method returns nothing.
  21943. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21944. */
  21945. Mesh.prototype.flipFaces = function (flipNormals) {
  21946. if (flipNormals === void 0) { flipNormals = false; }
  21947. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21948. var i;
  21949. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21950. for (i = 0; i < vertex_data.normals.length; i++) {
  21951. vertex_data.normals[i] *= -1;
  21952. }
  21953. }
  21954. var temp;
  21955. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21956. // reassign indices
  21957. temp = vertex_data.indices[i + 1];
  21958. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21959. vertex_data.indices[i + 2] = temp;
  21960. }
  21961. vertex_data.applyToMesh(this);
  21962. };
  21963. // Instances
  21964. /**
  21965. * Creates a new InstancedMesh object from the mesh model.
  21966. * An instance shares the same properties and the same material than its model.
  21967. * Only these properties of each instance can then be set individually :
  21968. * - position
  21969. * - rotation
  21970. * - rotationQuaternion
  21971. * - setPivotMatrix
  21972. * - scaling
  21973. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21974. * Warning : this method is not supported for Line mesh and LineSystem
  21975. */
  21976. Mesh.prototype.createInstance = function (name) {
  21977. return new BABYLON.InstancedMesh(name, this);
  21978. };
  21979. /**
  21980. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21981. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21982. * This method returns nothing.
  21983. */
  21984. Mesh.prototype.synchronizeInstances = function () {
  21985. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21986. var instance = this.instances[instanceIndex];
  21987. instance._syncSubMeshes();
  21988. }
  21989. };
  21990. /**
  21991. * Simplify the mesh according to the given array of settings.
  21992. * Function will return immediately and will simplify async. It returns nothing.
  21993. * @param settings a collection of simplification settings.
  21994. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21995. * @param type the type of simplification to run.
  21996. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21997. */
  21998. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21999. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22000. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22001. this.getScene().simplificationQueue.addTask({
  22002. settings: settings,
  22003. parallelProcessing: parallelProcessing,
  22004. mesh: this,
  22005. simplificationType: simplificationType,
  22006. successCallback: successCallback
  22007. });
  22008. };
  22009. /**
  22010. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22011. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22012. * This should be used together with the simplification to avoid disappearing triangles.
  22013. * @param successCallback an optional success callback to be called after the optimization finished.
  22014. */
  22015. Mesh.prototype.optimizeIndices = function (successCallback) {
  22016. var _this = this;
  22017. var indices = this.getIndices();
  22018. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22019. var vectorPositions = [];
  22020. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22021. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22022. }
  22023. var dupes = [];
  22024. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22025. var realPos = vectorPositions.length - 1 - iteration;
  22026. var testedPosition = vectorPositions[realPos];
  22027. for (var j = 0; j < realPos; ++j) {
  22028. var againstPosition = vectorPositions[j];
  22029. if (testedPosition.equals(againstPosition)) {
  22030. dupes[realPos] = j;
  22031. break;
  22032. }
  22033. }
  22034. }, function () {
  22035. for (var i = 0; i < indices.length; ++i) {
  22036. indices[i] = dupes[indices[i]] || indices[i];
  22037. }
  22038. //indices are now reordered
  22039. var originalSubMeshes = _this.subMeshes.slice(0);
  22040. _this.setIndices(indices);
  22041. _this.subMeshes = originalSubMeshes;
  22042. if (successCallback) {
  22043. successCallback(_this);
  22044. }
  22045. });
  22046. };
  22047. // Statics
  22048. /**
  22049. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22050. * The parameter `parsedMesh` is the mesh to be copied.
  22051. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22052. */
  22053. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22054. var mesh = new Mesh(parsedMesh.name, scene);
  22055. mesh.id = parsedMesh.id;
  22056. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22057. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22058. if (parsedMesh.metadata !== undefined) {
  22059. mesh.metadata = parsedMesh.metadata;
  22060. }
  22061. if (parsedMesh.rotationQuaternion) {
  22062. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22063. }
  22064. else if (parsedMesh.rotation) {
  22065. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22066. }
  22067. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22068. if (parsedMesh.localMatrix) {
  22069. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22070. }
  22071. else if (parsedMesh.pivotMatrix) {
  22072. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22073. }
  22074. mesh.setEnabled(parsedMesh.isEnabled);
  22075. mesh.isVisible = parsedMesh.isVisible;
  22076. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22077. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22078. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22079. if (parsedMesh.applyFog !== undefined) {
  22080. mesh.applyFog = parsedMesh.applyFog;
  22081. }
  22082. if (parsedMesh.pickable !== undefined) {
  22083. mesh.isPickable = parsedMesh.pickable;
  22084. }
  22085. if (parsedMesh.alphaIndex !== undefined) {
  22086. mesh.alphaIndex = parsedMesh.alphaIndex;
  22087. }
  22088. mesh.receiveShadows = parsedMesh.receiveShadows;
  22089. mesh.billboardMode = parsedMesh.billboardMode;
  22090. if (parsedMesh.visibility !== undefined) {
  22091. mesh.visibility = parsedMesh.visibility;
  22092. }
  22093. mesh.checkCollisions = parsedMesh.checkCollisions;
  22094. if (parsedMesh.isBlocker !== undefined) {
  22095. mesh.isBlocker = parsedMesh.isBlocker;
  22096. }
  22097. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22098. // freezeWorldMatrix
  22099. if (parsedMesh.freezeWorldMatrix) {
  22100. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22101. }
  22102. // Parent
  22103. if (parsedMesh.parentId) {
  22104. mesh._waitingParentId = parsedMesh.parentId;
  22105. }
  22106. // Actions
  22107. if (parsedMesh.actions !== undefined) {
  22108. mesh._waitingActions = parsedMesh.actions;
  22109. }
  22110. // Overlay
  22111. if (parsedMesh.overlayAlpha !== undefined) {
  22112. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22113. }
  22114. if (parsedMesh.overlayColor !== undefined) {
  22115. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22116. }
  22117. if (parsedMesh.renderOverlay !== undefined) {
  22118. mesh.renderOverlay = parsedMesh.renderOverlay;
  22119. }
  22120. // Geometry
  22121. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22122. if (parsedMesh.delayLoadingFile) {
  22123. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22124. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22125. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22126. if (parsedMesh._binaryInfo) {
  22127. mesh._binaryInfo = parsedMesh._binaryInfo;
  22128. }
  22129. mesh._delayInfo = [];
  22130. if (parsedMesh.hasUVs) {
  22131. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22132. }
  22133. if (parsedMesh.hasUVs2) {
  22134. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22135. }
  22136. if (parsedMesh.hasUVs3) {
  22137. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22138. }
  22139. if (parsedMesh.hasUVs4) {
  22140. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22141. }
  22142. if (parsedMesh.hasUVs5) {
  22143. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22144. }
  22145. if (parsedMesh.hasUVs6) {
  22146. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22147. }
  22148. if (parsedMesh.hasColors) {
  22149. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22150. }
  22151. if (parsedMesh.hasMatricesIndices) {
  22152. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22153. }
  22154. if (parsedMesh.hasMatricesWeights) {
  22155. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22156. }
  22157. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22158. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22159. mesh._checkDelayState();
  22160. }
  22161. }
  22162. else {
  22163. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22164. }
  22165. // Material
  22166. if (parsedMesh.materialId) {
  22167. mesh.setMaterialByID(parsedMesh.materialId);
  22168. }
  22169. else {
  22170. mesh.material = null;
  22171. }
  22172. // Skeleton
  22173. if (parsedMesh.skeletonId > -1) {
  22174. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22175. if (parsedMesh.numBoneInfluencers) {
  22176. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22177. }
  22178. }
  22179. // Animations
  22180. if (parsedMesh.animations) {
  22181. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22182. var parsedAnimation = parsedMesh.animations[animationIndex];
  22183. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22184. }
  22185. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22186. }
  22187. if (parsedMesh.autoAnimate) {
  22188. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  22189. }
  22190. // Layer Mask
  22191. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  22192. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  22193. }
  22194. else {
  22195. mesh.layerMask = 0x0FFFFFFF;
  22196. }
  22197. //(Deprecated) physics
  22198. if (parsedMesh.physicsImpostor) {
  22199. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  22200. mass: parsedMesh.physicsMass,
  22201. friction: parsedMesh.physicsFriction,
  22202. restitution: parsedMesh.physicsRestitution
  22203. }, scene);
  22204. }
  22205. // Instances
  22206. if (parsedMesh.instances) {
  22207. for (var index = 0; index < parsedMesh.instances.length; index++) {
  22208. var parsedInstance = parsedMesh.instances[index];
  22209. var instance = mesh.createInstance(parsedInstance.name);
  22210. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  22211. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  22212. if (parsedInstance.parentId) {
  22213. instance._waitingParentId = parsedInstance.parentId;
  22214. }
  22215. if (parsedInstance.rotationQuaternion) {
  22216. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  22217. }
  22218. else if (parsedInstance.rotation) {
  22219. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  22220. }
  22221. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  22222. instance.checkCollisions = mesh.checkCollisions;
  22223. if (parsedMesh.animations) {
  22224. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22225. parsedAnimation = parsedMesh.animations[animationIndex];
  22226. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22227. }
  22228. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  22229. }
  22230. }
  22231. }
  22232. return mesh;
  22233. };
  22234. /**
  22235. * Creates a ribbon mesh.
  22236. * Please consider using the same method from the MeshBuilder class instead.
  22237. * 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.
  22238. *
  22239. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22240. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22241. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22242. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22243. * 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.
  22244. * 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.
  22245. * 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
  22246. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22247. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22248. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22249. */
  22250. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  22251. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22252. pathArray: pathArray,
  22253. closeArray: closeArray,
  22254. closePath: closePath,
  22255. offset: offset,
  22256. updatable: updatable,
  22257. sideOrientation: sideOrientation,
  22258. instance: instance
  22259. }, scene);
  22260. };
  22261. /**
  22262. * Creates a plane polygonal mesh. By default, this is a disc.
  22263. * Please consider using the same method from the MeshBuilder class instead.
  22264. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22265. * 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.
  22266. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22267. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22268. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22269. */
  22270. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22271. var options = {
  22272. radius: radius,
  22273. tessellation: tessellation,
  22274. sideOrientation: sideOrientation,
  22275. updatable: updatable
  22276. };
  22277. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22278. };
  22279. /**
  22280. * Creates a box mesh.
  22281. * Please consider using the same method from the MeshBuilder class instead.
  22282. * The parameter `size` sets the size (float) of each box side (default 1).
  22283. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22284. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22285. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22286. */
  22287. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22288. var options = {
  22289. size: size,
  22290. sideOrientation: sideOrientation,
  22291. updatable: updatable
  22292. };
  22293. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22294. };
  22295. /**
  22296. * Creates a sphere mesh.
  22297. * Please consider using the same method from the MeshBuilder class instead.
  22298. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22299. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22300. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22301. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22303. */
  22304. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22305. var options = {
  22306. segments: segments,
  22307. diameterX: diameter,
  22308. diameterY: diameter,
  22309. diameterZ: diameter,
  22310. sideOrientation: sideOrientation,
  22311. updatable: updatable
  22312. };
  22313. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22314. };
  22315. /**
  22316. * Creates a cylinder or a cone mesh.
  22317. * Please consider using the same method from the MeshBuilder class instead.
  22318. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22319. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22320. * 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.
  22321. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22322. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22323. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22324. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22325. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22326. */
  22327. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  22328. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  22329. if (scene !== undefined) {
  22330. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22331. updatable = scene;
  22332. }
  22333. scene = subdivisions;
  22334. subdivisions = 1;
  22335. }
  22336. var options = {
  22337. height: height,
  22338. diameterTop: diameterTop,
  22339. diameterBottom: diameterBottom,
  22340. tessellation: tessellation,
  22341. subdivisions: subdivisions,
  22342. sideOrientation: sideOrientation,
  22343. updatable: updatable
  22344. };
  22345. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22346. };
  22347. // Torus (Code from SharpDX.org)
  22348. /**
  22349. * Creates a torus mesh.
  22350. * Please consider using the same method from the MeshBuilder class instead.
  22351. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22352. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22353. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22354. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22355. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22356. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22357. */
  22358. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22359. var options = {
  22360. diameter: diameter,
  22361. thickness: thickness,
  22362. tessellation: tessellation,
  22363. sideOrientation: sideOrientation,
  22364. updatable: updatable
  22365. };
  22366. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  22367. };
  22368. /**
  22369. * Creates a torus knot mesh.
  22370. * Please consider using the same method from the MeshBuilder class instead.
  22371. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22372. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22373. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22374. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22375. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22376. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22377. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22378. */
  22379. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  22380. var options = {
  22381. radius: radius,
  22382. tube: tube,
  22383. radialSegments: radialSegments,
  22384. tubularSegments: tubularSegments,
  22385. p: p,
  22386. q: q,
  22387. sideOrientation: sideOrientation,
  22388. updatable: updatable
  22389. };
  22390. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  22391. };
  22392. /**
  22393. * Creates a line mesh.
  22394. * Please consider using the same method from the MeshBuilder class instead.
  22395. * 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.
  22396. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22397. * The parameter `points` is an array successive Vector3.
  22398. * 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
  22399. * When updating an instance, remember that only point positions can change, not the number of points.
  22400. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22401. */
  22402. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  22403. var options = {
  22404. points: points,
  22405. updatable: updatable,
  22406. instance: instance
  22407. };
  22408. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  22409. };
  22410. /**
  22411. * Creates a dashed line mesh.
  22412. * Please consider using the same method from the MeshBuilder class instead.
  22413. * 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.
  22414. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22415. * The parameter `points` is an array successive Vector3.
  22416. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22417. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22418. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22419. * 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
  22420. * When updating an instance, remember that only point positions can change, not the number of points.
  22421. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22422. */
  22423. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  22424. var options = {
  22425. points: points,
  22426. dashSize: dashSize,
  22427. gapSize: gapSize,
  22428. dashNb: dashNb,
  22429. updatable: updatable,
  22430. instance: instance
  22431. };
  22432. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  22433. };
  22434. /**
  22435. * Creates an extruded shape mesh.
  22436. * 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.
  22437. * Please consider using the same method from the MeshBuilder class instead.
  22438. *
  22439. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22440. * 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
  22441. * extruded along the Z axis.
  22442. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22443. * 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.
  22444. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22445. * 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
  22446. * 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
  22447. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22448. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22449. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22450. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22451. */
  22452. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  22453. var options = {
  22454. shape: shape,
  22455. path: path,
  22456. scale: scale,
  22457. rotation: rotation,
  22458. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22459. sideOrientation: sideOrientation,
  22460. instance: instance,
  22461. updatable: updatable
  22462. };
  22463. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  22464. };
  22465. /**
  22466. * Creates an custom extruded shape mesh.
  22467. * 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.
  22468. * Please consider using the same method from the MeshBuilder class instead.
  22469. *
  22470. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22471. * 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
  22472. * extruded along the Z axis.
  22473. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22474. * 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
  22475. * and the distance of this point from the begining of the path :
  22476. * ```javascript
  22477. * var rotationFunction = function(i, distance) {
  22478. * // do things
  22479. * return rotationValue; }
  22480. * ```
  22481. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22482. * 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
  22483. * and the distance of this point from the begining of the path :
  22484. * ```javascript
  22485. * var scaleFunction = function(i, distance) {
  22486. * // do things
  22487. * return scaleValue;}
  22488. * ```
  22489. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22490. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22491. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22492. * 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
  22493. * 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
  22494. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22495. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22496. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22497. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22498. */
  22499. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  22500. var options = {
  22501. shape: shape,
  22502. path: path,
  22503. scaleFunction: scaleFunction,
  22504. rotationFunction: rotationFunction,
  22505. ribbonCloseArray: ribbonCloseArray,
  22506. ribbonClosePath: ribbonClosePath,
  22507. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  22508. sideOrientation: sideOrientation,
  22509. instance: instance,
  22510. updatable: updatable
  22511. };
  22512. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  22513. };
  22514. /**
  22515. * Creates lathe mesh.
  22516. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22517. * Please consider using the same method from the MeshBuilder class instead.
  22518. * 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
  22519. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22520. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22521. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22522. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22523. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22524. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22525. */
  22526. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  22527. var options = {
  22528. shape: shape,
  22529. radius: radius,
  22530. tessellation: tessellation,
  22531. sideOrientation: sideOrientation,
  22532. updatable: updatable
  22533. };
  22534. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  22535. };
  22536. /**
  22537. * Creates a plane mesh.
  22538. * Please consider using the same method from the MeshBuilder class instead.
  22539. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22540. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22541. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22542. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22543. */
  22544. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  22545. var options = {
  22546. size: size,
  22547. width: size,
  22548. height: size,
  22549. sideOrientation: sideOrientation,
  22550. updatable: updatable
  22551. };
  22552. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  22553. };
  22554. /**
  22555. * Creates a ground mesh.
  22556. * Please consider using the same method from the MeshBuilder class instead.
  22557. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22558. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22559. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22560. */
  22561. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  22562. var options = {
  22563. width: width,
  22564. height: height,
  22565. subdivisions: subdivisions,
  22566. updatable: updatable
  22567. };
  22568. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  22569. };
  22570. /**
  22571. * Creates a tiled ground mesh.
  22572. * Please consider using the same method from the MeshBuilder class instead.
  22573. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22574. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22575. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22576. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22577. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22578. * numbers of subdivisions on the ground width and height of each tile.
  22579. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22580. */
  22581. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  22582. var options = {
  22583. xmin: xmin,
  22584. zmin: zmin,
  22585. xmax: xmax,
  22586. zmax: zmax,
  22587. subdivisions: subdivisions,
  22588. precision: precision,
  22589. updatable: updatable
  22590. };
  22591. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  22592. };
  22593. /**
  22594. * Creates a ground mesh from a height map.
  22595. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22596. * Please consider using the same method from the MeshBuilder class instead.
  22597. * The parameter `url` sets the URL of the height map image resource.
  22598. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22599. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22600. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22601. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22602. * 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).
  22603. * This function is passed the newly built mesh :
  22604. * ```javascript
  22605. * function(mesh) { // do things
  22606. * return; }
  22607. * ```
  22608. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22609. */
  22610. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  22611. var options = {
  22612. width: width,
  22613. height: height,
  22614. subdivisions: subdivisions,
  22615. minHeight: minHeight,
  22616. maxHeight: maxHeight,
  22617. updatable: updatable,
  22618. onReady: onReady
  22619. };
  22620. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  22621. };
  22622. /**
  22623. * Creates a tube mesh.
  22624. * 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.
  22625. * Please consider using the same method from the MeshBuilder class instead.
  22626. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22627. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22628. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22629. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22630. * 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.
  22631. * It must return a radius value (positive float) :
  22632. * ```javascript
  22633. * var radiusFunction = function(i, distance) {
  22634. * // do things
  22635. * return radius; }
  22636. * ```
  22637. * 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
  22638. * 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
  22639. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22640. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22641. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22642. */
  22643. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  22644. var options = {
  22645. path: path,
  22646. radius: radius,
  22647. tessellation: tessellation,
  22648. radiusFunction: radiusFunction,
  22649. arc: 1,
  22650. cap: cap,
  22651. updatable: updatable,
  22652. sideOrientation: sideOrientation,
  22653. instance: instance
  22654. };
  22655. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  22656. };
  22657. /**
  22658. * Creates a polyhedron mesh.
  22659. * Please consider using the same method from the MeshBuilder class instead.
  22660. * 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
  22661. * to choose the wanted type.
  22662. * The parameter `size` (positive float, default 1) sets the polygon size.
  22663. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  22664. * 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`.
  22665. * 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
  22666. * 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)`).
  22667. * 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
  22668. * 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.
  22669. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22670. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22671. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22672. */
  22673. Mesh.CreatePolyhedron = function (name, options, scene) {
  22674. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  22675. };
  22676. /**
  22677. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22678. * Please consider using the same method from the MeshBuilder class instead.
  22679. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22680. * 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`).
  22681. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22682. * 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.
  22683. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22684. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22685. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22686. */
  22687. Mesh.CreateIcoSphere = function (name, options, scene) {
  22688. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  22689. };
  22690. /**
  22691. * Creates a decal mesh.
  22692. * Please consider using the same method from the MeshBuilder class instead.
  22693. * 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.
  22694. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  22695. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  22696. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  22697. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  22698. */
  22699. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  22700. var options = {
  22701. position: position,
  22702. normal: normal,
  22703. size: size,
  22704. angle: angle
  22705. };
  22706. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  22707. };
  22708. // Skeletons
  22709. /**
  22710. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22711. */
  22712. Mesh.prototype.setPositionsForCPUSkinning = function () {
  22713. var source;
  22714. if (!this._sourcePositions) {
  22715. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22716. this._sourcePositions = new Float32Array(source);
  22717. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  22718. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  22719. }
  22720. }
  22721. return this._sourcePositions;
  22722. };
  22723. /**
  22724. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  22725. */
  22726. Mesh.prototype.setNormalsForCPUSkinning = function () {
  22727. var source;
  22728. if (!this._sourceNormals) {
  22729. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22730. this._sourceNormals = new Float32Array(source);
  22731. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  22732. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  22733. }
  22734. }
  22735. return this._sourceNormals;
  22736. };
  22737. /**
  22738. * Update the vertex buffers by applying transformation from the bones
  22739. * @param {skeleton} skeleton to apply
  22740. */
  22741. Mesh.prototype.applySkeleton = function (skeleton) {
  22742. if (!this.geometry) {
  22743. return;
  22744. }
  22745. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  22746. return;
  22747. }
  22748. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  22749. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22750. return this;
  22751. }
  22752. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22753. return this;
  22754. }
  22755. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  22756. return this;
  22757. }
  22758. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  22759. return this;
  22760. }
  22761. if (!this._sourcePositions) {
  22762. var submeshes = this.subMeshes.slice();
  22763. this.setPositionsForCPUSkinning();
  22764. this.subMeshes = submeshes;
  22765. }
  22766. if (!this._sourceNormals) {
  22767. this.setNormalsForCPUSkinning();
  22768. }
  22769. // positionsData checks for not being Float32Array will only pass at most once
  22770. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22771. if (!(positionsData instanceof Float32Array)) {
  22772. positionsData = new Float32Array(positionsData);
  22773. }
  22774. // normalsData checks for not being Float32Array will only pass at most once
  22775. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22776. if (!(normalsData instanceof Float32Array)) {
  22777. normalsData = new Float32Array(normalsData);
  22778. }
  22779. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  22780. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  22781. var needExtras = this.numBoneInfluencers > 4;
  22782. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  22783. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  22784. var skeletonMatrices = skeleton.getTransformMatrices(this);
  22785. var tempVector3 = BABYLON.Vector3.Zero();
  22786. var finalMatrix = new BABYLON.Matrix();
  22787. var tempMatrix = new BABYLON.Matrix();
  22788. var matWeightIdx = 0;
  22789. var inf;
  22790. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  22791. var weight;
  22792. for (inf = 0; inf < 4; inf++) {
  22793. weight = matricesWeightsData[matWeightIdx + inf];
  22794. if (weight > 0) {
  22795. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22796. finalMatrix.addToSelf(tempMatrix);
  22797. }
  22798. else
  22799. break;
  22800. }
  22801. if (needExtras) {
  22802. for (inf = 0; inf < 4; inf++) {
  22803. weight = matricesWeightsExtraData[matWeightIdx + inf];
  22804. if (weight > 0) {
  22805. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  22806. finalMatrix.addToSelf(tempMatrix);
  22807. }
  22808. else
  22809. break;
  22810. }
  22811. }
  22812. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  22813. tempVector3.toArray(positionsData, index);
  22814. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  22815. tempVector3.toArray(normalsData, index);
  22816. finalMatrix.reset();
  22817. }
  22818. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  22819. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  22820. return this;
  22821. };
  22822. // Tools
  22823. /**
  22824. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  22825. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  22826. */
  22827. Mesh.MinMax = function (meshes) {
  22828. var minVector = null;
  22829. var maxVector = null;
  22830. meshes.forEach(function (mesh, index, array) {
  22831. var boundingBox = mesh.getBoundingInfo().boundingBox;
  22832. if (!minVector) {
  22833. minVector = boundingBox.minimumWorld;
  22834. maxVector = boundingBox.maximumWorld;
  22835. }
  22836. else {
  22837. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  22838. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  22839. }
  22840. });
  22841. return {
  22842. min: minVector,
  22843. max: maxVector
  22844. };
  22845. };
  22846. /**
  22847. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  22848. */
  22849. Mesh.Center = function (meshesOrMinMaxVector) {
  22850. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  22851. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  22852. };
  22853. /**
  22854. * Merge the array of meshes into a single mesh for performance reasons.
  22855. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  22856. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  22857. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  22858. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  22859. */
  22860. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  22861. if (disposeSource === void 0) { disposeSource = true; }
  22862. var index;
  22863. if (!allow32BitsIndices) {
  22864. var totalVertices = 0;
  22865. // Counting vertices
  22866. for (index = 0; index < meshes.length; index++) {
  22867. if (meshes[index]) {
  22868. totalVertices += meshes[index].getTotalVertices();
  22869. if (totalVertices > 65536) {
  22870. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  22871. return null;
  22872. }
  22873. }
  22874. }
  22875. }
  22876. // Merge
  22877. var vertexData;
  22878. var otherVertexData;
  22879. var source;
  22880. for (index = 0; index < meshes.length; index++) {
  22881. if (meshes[index]) {
  22882. meshes[index].computeWorldMatrix(true);
  22883. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22884. otherVertexData.transform(meshes[index].getWorldMatrix());
  22885. if (vertexData) {
  22886. vertexData.merge(otherVertexData);
  22887. }
  22888. else {
  22889. vertexData = otherVertexData;
  22890. source = meshes[index];
  22891. }
  22892. }
  22893. }
  22894. if (!meshSubclass) {
  22895. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22896. }
  22897. vertexData.applyToMesh(meshSubclass);
  22898. // Setting properties
  22899. meshSubclass.material = source.material;
  22900. meshSubclass.checkCollisions = source.checkCollisions;
  22901. // Cleaning
  22902. if (disposeSource) {
  22903. for (index = 0; index < meshes.length; index++) {
  22904. if (meshes[index]) {
  22905. meshes[index].dispose();
  22906. }
  22907. }
  22908. }
  22909. return meshSubclass;
  22910. };
  22911. return Mesh;
  22912. }(BABYLON.AbstractMesh));
  22913. // Consts
  22914. Mesh._FRONTSIDE = 0;
  22915. Mesh._BACKSIDE = 1;
  22916. Mesh._DOUBLESIDE = 2;
  22917. Mesh._DEFAULTSIDE = 0;
  22918. Mesh._NO_CAP = 0;
  22919. Mesh._CAP_START = 1;
  22920. Mesh._CAP_END = 2;
  22921. Mesh._CAP_ALL = 3;
  22922. BABYLON.Mesh = Mesh;
  22923. })(BABYLON || (BABYLON = {}));
  22924. //# sourceMappingURL=babylon.mesh.js.map
  22925. var BABYLON;
  22926. (function (BABYLON) {
  22927. var SubMesh = (function () {
  22928. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22929. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22930. this.materialIndex = materialIndex;
  22931. this.verticesStart = verticesStart;
  22932. this.verticesCount = verticesCount;
  22933. this.indexStart = indexStart;
  22934. this.indexCount = indexCount;
  22935. this._renderId = 0;
  22936. this._mesh = mesh;
  22937. this._renderingMesh = renderingMesh || mesh;
  22938. mesh.subMeshes.push(this);
  22939. this._trianglePlanes = [];
  22940. this._id = mesh.subMeshes.length - 1;
  22941. if (createBoundingBox) {
  22942. this.refreshBoundingInfo();
  22943. mesh.computeWorldMatrix(true);
  22944. }
  22945. }
  22946. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22947. get: function () {
  22948. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22949. },
  22950. enumerable: true,
  22951. configurable: true
  22952. });
  22953. SubMesh.prototype.getBoundingInfo = function () {
  22954. if (this.IsGlobal) {
  22955. return this._mesh.getBoundingInfo();
  22956. }
  22957. return this._boundingInfo;
  22958. };
  22959. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22960. this._boundingInfo = boundingInfo;
  22961. };
  22962. SubMesh.prototype.getMesh = function () {
  22963. return this._mesh;
  22964. };
  22965. SubMesh.prototype.getRenderingMesh = function () {
  22966. return this._renderingMesh;
  22967. };
  22968. SubMesh.prototype.getMaterial = function () {
  22969. var rootMaterial = this._renderingMesh.material;
  22970. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  22971. var multiMaterial = rootMaterial;
  22972. return multiMaterial.getSubMaterial(this.materialIndex);
  22973. }
  22974. if (!rootMaterial) {
  22975. return this._mesh.getScene().defaultMaterial;
  22976. }
  22977. return rootMaterial;
  22978. };
  22979. // Methods
  22980. SubMesh.prototype.refreshBoundingInfo = function () {
  22981. this._lastColliderWorldVertices = null;
  22982. if (this.IsGlobal) {
  22983. return;
  22984. }
  22985. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22986. if (!data) {
  22987. this._boundingInfo = this._mesh._boundingInfo;
  22988. return;
  22989. }
  22990. var indices = this._renderingMesh.getIndices();
  22991. var extend;
  22992. //is this the only submesh?
  22993. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22994. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22995. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22996. }
  22997. else {
  22998. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22999. }
  23000. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23001. };
  23002. SubMesh.prototype._checkCollision = function (collider) {
  23003. return this.getBoundingInfo()._checkCollision(collider);
  23004. };
  23005. SubMesh.prototype.updateBoundingInfo = function (world) {
  23006. if (!this.getBoundingInfo()) {
  23007. this.refreshBoundingInfo();
  23008. }
  23009. this.getBoundingInfo().update(world);
  23010. };
  23011. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23012. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23013. };
  23014. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23015. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23016. };
  23017. SubMesh.prototype.render = function (enableAlphaMode) {
  23018. this._renderingMesh.render(this, enableAlphaMode);
  23019. };
  23020. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23021. if (!this._linesIndexBuffer) {
  23022. var linesIndices = [];
  23023. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23024. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23025. }
  23026. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23027. this.linesIndexCount = linesIndices.length;
  23028. }
  23029. return this._linesIndexBuffer;
  23030. };
  23031. SubMesh.prototype.canIntersects = function (ray) {
  23032. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23033. };
  23034. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23035. var intersectInfo = null;
  23036. // LineMesh first as it's also a Mesh...
  23037. if (this._mesh instanceof BABYLON.LinesMesh) {
  23038. var lineMesh = this._mesh;
  23039. // Line test
  23040. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23041. var p0 = positions[indices[index]];
  23042. var p1 = positions[indices[index + 1]];
  23043. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23044. if (length < 0) {
  23045. continue;
  23046. }
  23047. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23048. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23049. if (fastCheck) {
  23050. break;
  23051. }
  23052. }
  23053. }
  23054. }
  23055. else {
  23056. // Triangles test
  23057. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23058. var p0 = positions[indices[index]];
  23059. var p1 = positions[indices[index + 1]];
  23060. var p2 = positions[indices[index + 2]];
  23061. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  23062. if (currentIntersectInfo) {
  23063. if (currentIntersectInfo.distance < 0) {
  23064. continue;
  23065. }
  23066. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  23067. intersectInfo = currentIntersectInfo;
  23068. intersectInfo.faceId = index / 3;
  23069. if (fastCheck) {
  23070. break;
  23071. }
  23072. }
  23073. }
  23074. }
  23075. }
  23076. return intersectInfo;
  23077. };
  23078. // Clone
  23079. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  23080. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  23081. if (!this.IsGlobal) {
  23082. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  23083. }
  23084. return result;
  23085. };
  23086. // Dispose
  23087. SubMesh.prototype.dispose = function () {
  23088. if (this._linesIndexBuffer) {
  23089. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  23090. this._linesIndexBuffer = null;
  23091. }
  23092. // Remove from mesh
  23093. var index = this._mesh.subMeshes.indexOf(this);
  23094. this._mesh.subMeshes.splice(index, 1);
  23095. };
  23096. // Statics
  23097. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  23098. var minVertexIndex = Number.MAX_VALUE;
  23099. var maxVertexIndex = -Number.MAX_VALUE;
  23100. renderingMesh = renderingMesh || mesh;
  23101. var indices = renderingMesh.getIndices();
  23102. for (var index = startIndex; index < startIndex + indexCount; index++) {
  23103. var vertexIndex = indices[index];
  23104. if (vertexIndex < minVertexIndex)
  23105. minVertexIndex = vertexIndex;
  23106. if (vertexIndex > maxVertexIndex)
  23107. maxVertexIndex = vertexIndex;
  23108. }
  23109. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  23110. };
  23111. return SubMesh;
  23112. }());
  23113. BABYLON.SubMesh = SubMesh;
  23114. })(BABYLON || (BABYLON = {}));
  23115. //# sourceMappingURL=babylon.subMesh.js.map
  23116. var BABYLON;
  23117. (function (BABYLON) {
  23118. var MeshBuilder = (function () {
  23119. function MeshBuilder() {
  23120. }
  23121. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  23122. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  23123. return BABYLON.Mesh.DOUBLESIDE;
  23124. }
  23125. if (orientation === undefined || orientation === null) {
  23126. return BABYLON.Mesh.FRONTSIDE;
  23127. }
  23128. return orientation;
  23129. };
  23130. /**
  23131. * Creates a box mesh.
  23132. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  23133. * The parameter `size` sets the size (float) of each box side (default 1).
  23134. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  23135. * 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).
  23136. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  23137. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23138. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23139. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23140. */
  23141. MeshBuilder.CreateBox = function (name, options, scene) {
  23142. var box = new BABYLON.Mesh(name, scene);
  23143. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23144. box.sideOrientation = options.sideOrientation;
  23145. var vertexData = BABYLON.VertexData.CreateBox(options);
  23146. vertexData.applyToMesh(box, options.updatable);
  23147. return box;
  23148. };
  23149. /**
  23150. * Creates a sphere mesh.
  23151. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  23152. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  23153. * 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`).
  23154. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  23155. * 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
  23156. * 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).
  23157. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23158. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23159. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23160. */
  23161. MeshBuilder.CreateSphere = function (name, options, scene) {
  23162. var sphere = new BABYLON.Mesh(name, scene);
  23163. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23164. sphere.sideOrientation = options.sideOrientation;
  23165. var vertexData = BABYLON.VertexData.CreateSphere(options);
  23166. vertexData.applyToMesh(sphere, options.updatable);
  23167. return sphere;
  23168. };
  23169. /**
  23170. * Creates a plane polygonal mesh. By default, this is a disc.
  23171. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  23172. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  23173. * 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.
  23174. * 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
  23175. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23176. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23177. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23178. */
  23179. MeshBuilder.CreateDisc = function (name, options, scene) {
  23180. var disc = new BABYLON.Mesh(name, scene);
  23181. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23182. disc.sideOrientation = options.sideOrientation;
  23183. var vertexData = BABYLON.VertexData.CreateDisc(options);
  23184. vertexData.applyToMesh(disc, options.updatable);
  23185. return disc;
  23186. };
  23187. /**
  23188. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23189. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  23190. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23191. * 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`).
  23192. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23193. * 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.
  23194. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23195. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23196. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23197. */
  23198. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  23199. var sphere = new BABYLON.Mesh(name, scene);
  23200. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23201. sphere.sideOrientation = options.sideOrientation;
  23202. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  23203. vertexData.applyToMesh(sphere, options.updatable);
  23204. return sphere;
  23205. };
  23206. ;
  23207. /**
  23208. * Creates a ribbon mesh.
  23209. * 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.
  23210. *
  23211. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  23212. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  23213. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  23214. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  23215. * 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.
  23216. * 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.
  23217. * 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
  23218. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23219. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23220. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23221. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23222. */
  23223. MeshBuilder.CreateRibbon = function (name, options, scene) {
  23224. var pathArray = options.pathArray;
  23225. var closeArray = options.closeArray;
  23226. var closePath = options.closePath;
  23227. var offset = options.offset;
  23228. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23229. var instance = options.instance;
  23230. var updatable = options.updatable;
  23231. if (instance) {
  23232. // positionFunction : ribbon case
  23233. // only pathArray and sideOrientation parameters are taken into account for positions update
  23234. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  23235. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  23236. var positionFunction = function (positions) {
  23237. var minlg = pathArray[0].length;
  23238. var i = 0;
  23239. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  23240. for (var si = 1; si <= ns; si++) {
  23241. for (var p = 0; p < pathArray.length; p++) {
  23242. var path = pathArray[p];
  23243. var l = path.length;
  23244. minlg = (minlg < l) ? minlg : l;
  23245. var j = 0;
  23246. while (j < minlg) {
  23247. positions[i] = path[j].x;
  23248. positions[i + 1] = path[j].y;
  23249. positions[i + 2] = path[j].z;
  23250. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  23251. BABYLON.Tmp.Vector3[0].x = path[j].x;
  23252. }
  23253. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  23254. BABYLON.Tmp.Vector3[1].x = path[j].x;
  23255. }
  23256. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  23257. BABYLON.Tmp.Vector3[0].y = path[j].y;
  23258. }
  23259. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  23260. BABYLON.Tmp.Vector3[1].y = path[j].y;
  23261. }
  23262. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  23263. BABYLON.Tmp.Vector3[0].z = path[j].z;
  23264. }
  23265. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  23266. BABYLON.Tmp.Vector3[1].z = path[j].z;
  23267. }
  23268. j++;
  23269. i += 3;
  23270. }
  23271. if (instance._closePath) {
  23272. positions[i] = path[0].x;
  23273. positions[i + 1] = path[0].y;
  23274. positions[i + 2] = path[0].z;
  23275. i += 3;
  23276. }
  23277. }
  23278. }
  23279. };
  23280. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23281. positionFunction(positions);
  23282. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  23283. instance._boundingInfo.update(instance._worldMatrix);
  23284. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  23285. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  23286. var indices = instance.getIndices();
  23287. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23288. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  23289. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  23290. if (instance._closePath) {
  23291. var indexFirst = 0;
  23292. var indexLast = 0;
  23293. for (var p = 0; p < pathArray.length; p++) {
  23294. indexFirst = instance._idx[p] * 3;
  23295. if (p + 1 < pathArray.length) {
  23296. indexLast = (instance._idx[p + 1] - 1) * 3;
  23297. }
  23298. else {
  23299. indexLast = normals.length - 3;
  23300. }
  23301. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  23302. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  23303. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  23304. normals[indexLast] = normals[indexFirst];
  23305. normals[indexLast + 1] = normals[indexFirst + 1];
  23306. normals[indexLast + 2] = normals[indexFirst + 2];
  23307. }
  23308. }
  23309. if (!(instance.areNormalsFrozen)) {
  23310. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  23311. }
  23312. }
  23313. return instance;
  23314. }
  23315. else {
  23316. var ribbon = new BABYLON.Mesh(name, scene);
  23317. ribbon.sideOrientation = sideOrientation;
  23318. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  23319. if (closePath) {
  23320. ribbon._idx = vertexData._idx;
  23321. }
  23322. ribbon._closePath = closePath;
  23323. ribbon._closeArray = closeArray;
  23324. vertexData.applyToMesh(ribbon, updatable);
  23325. return ribbon;
  23326. }
  23327. };
  23328. /**
  23329. * Creates a cylinder or a cone mesh.
  23330. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  23331. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  23332. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  23333. * 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.
  23334. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  23335. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  23336. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  23337. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  23338. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  23339. * 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).
  23340. * 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
  23341. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  23342. * 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
  23343. * 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.
  23344. * If `enclose` is false, a ring surface is one element.
  23345. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  23346. * 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
  23347. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23348. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23349. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23350. */
  23351. MeshBuilder.CreateCylinder = function (name, options, scene) {
  23352. var cylinder = new BABYLON.Mesh(name, scene);
  23353. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23354. cylinder.sideOrientation = options.sideOrientation;
  23355. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  23356. vertexData.applyToMesh(cylinder, options.updatable);
  23357. return cylinder;
  23358. };
  23359. /**
  23360. * Creates a torus mesh.
  23361. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  23362. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  23363. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  23364. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  23365. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23366. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23368. */
  23369. MeshBuilder.CreateTorus = function (name, options, scene) {
  23370. var torus = new BABYLON.Mesh(name, scene);
  23371. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23372. torus.sideOrientation = options.sideOrientation;
  23373. var vertexData = BABYLON.VertexData.CreateTorus(options);
  23374. vertexData.applyToMesh(torus, options.updatable);
  23375. return torus;
  23376. };
  23377. /**
  23378. * Creates a torus knot mesh.
  23379. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  23380. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23381. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23382. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23383. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23384. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23385. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23386. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23387. */
  23388. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  23389. var torusKnot = new BABYLON.Mesh(name, scene);
  23390. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23391. torusKnot.sideOrientation = options.sideOrientation;
  23392. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  23393. vertexData.applyToMesh(torusKnot, options.updatable);
  23394. return torusKnot;
  23395. };
  23396. /**
  23397. * Creates a line system mesh.
  23398. * A line system is a pool of many lines gathered in a single mesh.
  23399. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  23400. * 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.
  23401. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  23402. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  23403. * 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
  23404. * 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
  23405. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  23406. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23407. */
  23408. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  23409. var instance = options.instance;
  23410. var lines = options.lines;
  23411. if (instance) {
  23412. var positionFunction = function (positions) {
  23413. var i = 0;
  23414. for (var l = 0; l < lines.length; l++) {
  23415. var points = lines[l];
  23416. for (var p = 0; p < points.length; p++) {
  23417. positions[i] = points[p].x;
  23418. positions[i + 1] = points[p].y;
  23419. positions[i + 2] = points[p].z;
  23420. i += 3;
  23421. }
  23422. }
  23423. };
  23424. instance.updateMeshPositions(positionFunction, false);
  23425. return instance;
  23426. }
  23427. // line system creation
  23428. var lineSystem = new BABYLON.LinesMesh(name, scene);
  23429. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  23430. vertexData.applyToMesh(lineSystem, options.updatable);
  23431. return lineSystem;
  23432. };
  23433. /**
  23434. * Creates a line mesh.
  23435. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  23436. * 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.
  23437. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23438. * The parameter `points` is an array successive Vector3.
  23439. * 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
  23440. * When updating an instance, remember that only point positions can change, not the number of points.
  23441. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23442. */
  23443. MeshBuilder.CreateLines = function (name, options, scene) {
  23444. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  23445. return lines;
  23446. };
  23447. /**
  23448. * Creates a dashed line mesh.
  23449. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  23450. * 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.
  23451. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23452. * The parameter `points` is an array successive Vector3.
  23453. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23454. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23455. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23456. * 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
  23457. * When updating an instance, remember that only point positions can change, not the number of points.
  23458. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23459. */
  23460. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  23461. var points = options.points;
  23462. var instance = options.instance;
  23463. var gapSize = options.gapSize;
  23464. var dashNb = options.dashNb;
  23465. var dashSize = options.dashSize;
  23466. if (instance) {
  23467. var positionFunction = function (positions) {
  23468. var curvect = BABYLON.Vector3.Zero();
  23469. var nbSeg = positions.length / 6;
  23470. var lg = 0;
  23471. var nb = 0;
  23472. var shft = 0;
  23473. var dashshft = 0;
  23474. var curshft = 0;
  23475. var p = 0;
  23476. var i = 0;
  23477. var j = 0;
  23478. for (i = 0; i < points.length - 1; i++) {
  23479. points[i + 1].subtractToRef(points[i], curvect);
  23480. lg += curvect.length();
  23481. }
  23482. shft = lg / nbSeg;
  23483. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  23484. for (i = 0; i < points.length - 1; i++) {
  23485. points[i + 1].subtractToRef(points[i], curvect);
  23486. nb = Math.floor(curvect.length() / shft);
  23487. curvect.normalize();
  23488. j = 0;
  23489. while (j < nb && p < positions.length) {
  23490. curshft = shft * j;
  23491. positions[p] = points[i].x + curshft * curvect.x;
  23492. positions[p + 1] = points[i].y + curshft * curvect.y;
  23493. positions[p + 2] = points[i].z + curshft * curvect.z;
  23494. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  23495. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  23496. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  23497. p += 6;
  23498. j++;
  23499. }
  23500. }
  23501. while (p < positions.length) {
  23502. positions[p] = points[i].x;
  23503. positions[p + 1] = points[i].y;
  23504. positions[p + 2] = points[i].z;
  23505. p += 3;
  23506. }
  23507. };
  23508. instance.updateMeshPositions(positionFunction, false);
  23509. return instance;
  23510. }
  23511. // dashed lines creation
  23512. var dashedLines = new BABYLON.LinesMesh(name, scene);
  23513. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  23514. vertexData.applyToMesh(dashedLines, options.updatable);
  23515. dashedLines.dashSize = dashSize;
  23516. dashedLines.gapSize = gapSize;
  23517. return dashedLines;
  23518. };
  23519. /**
  23520. * Creates an extruded shape mesh.
  23521. * 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.
  23522. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  23523. *
  23524. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23525. * 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
  23526. * extruded along the Z axis.
  23527. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23528. * 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.
  23529. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23530. * 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
  23531. * 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
  23532. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23533. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23534. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23535. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23536. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23537. */
  23538. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  23539. var path = options.path;
  23540. var shape = options.shape;
  23541. var scale = options.scale || 1;
  23542. var rotation = options.rotation || 0;
  23543. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  23544. var updatable = options.updatable;
  23545. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23546. var instance = options.instance;
  23547. var invertUV = options.invertUV || false;
  23548. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  23549. };
  23550. /**
  23551. * Creates an custom extruded shape mesh.
  23552. * 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.
  23553. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  23554. *
  23555. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23556. * 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
  23557. * extruded along the Z axis.
  23558. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23559. * 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
  23560. * and the distance of this point from the begining of the path :
  23561. * ```javascript
  23562. * var rotationFunction = function(i, distance) {
  23563. * // do things
  23564. * return rotationValue; }
  23565. * ```
  23566. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23567. * 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
  23568. * and the distance of this point from the begining of the path :
  23569. * ```javascript
  23570. * var scaleFunction = function(i, distance) {
  23571. * // do things
  23572. * return scaleValue;}
  23573. * ```
  23574. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23575. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23576. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23577. * 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
  23578. * 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
  23579. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23580. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23581. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23582. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23583. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23584. */
  23585. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  23586. var path = options.path;
  23587. var shape = options.shape;
  23588. var scaleFunction = options.scaleFunction || (function () { return 1; });
  23589. var rotationFunction = options.rotationFunction || (function () { return 0; });
  23590. var ribbonCloseArray = options.ribbonCloseArray || false;
  23591. var ribbonClosePath = options.ribbonClosePath || false;
  23592. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  23593. var updatable = options.updatable;
  23594. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23595. var instance = options.instance;
  23596. var invertUV = options.invertUV || false;
  23597. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  23598. };
  23599. /**
  23600. * Creates lathe mesh.
  23601. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23602. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  23603. *
  23604. * 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
  23605. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23606. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23607. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23608. * 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.
  23609. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  23610. * 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
  23611. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23612. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23613. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23614. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23615. */
  23616. MeshBuilder.CreateLathe = function (name, options, scene) {
  23617. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  23618. var closed = (options.closed === undefined) ? true : options.closed;
  23619. var shape = options.shape;
  23620. var radius = options.radius || 1;
  23621. var tessellation = options.tessellation || 64;
  23622. var updatable = options.updatable;
  23623. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23624. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  23625. var pi2 = Math.PI * 2;
  23626. var paths = new Array();
  23627. var invertUV = options.invertUV || false;
  23628. var i = 0;
  23629. var p = 0;
  23630. var step = pi2 / tessellation * arc;
  23631. var rotated;
  23632. var path = new Array();
  23633. ;
  23634. for (i = 0; i <= tessellation; i++) {
  23635. var path = [];
  23636. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  23637. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  23638. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  23639. }
  23640. for (p = 0; p < shape.length; p++) {
  23641. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  23642. path.push(rotated);
  23643. }
  23644. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  23645. 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));
  23646. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  23647. }
  23648. paths.push(path);
  23649. }
  23650. // lathe ribbon
  23651. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  23652. return lathe;
  23653. };
  23654. /**
  23655. * Creates a plane mesh.
  23656. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  23657. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23658. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  23659. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  23660. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23661. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23662. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23663. */
  23664. MeshBuilder.CreatePlane = function (name, options, scene) {
  23665. var plane = new BABYLON.Mesh(name, scene);
  23666. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23667. plane.sideOrientation = options.sideOrientation;
  23668. var vertexData = BABYLON.VertexData.CreatePlane(options);
  23669. vertexData.applyToMesh(plane, options.updatable);
  23670. if (options.sourcePlane) {
  23671. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  23672. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  23673. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  23674. plane.rotate(vectorProduct, product);
  23675. }
  23676. return plane;
  23677. };
  23678. /**
  23679. * Creates a ground mesh.
  23680. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  23681. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23682. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23683. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23684. */
  23685. MeshBuilder.CreateGround = function (name, options, scene) {
  23686. var ground = new BABYLON.GroundMesh(name, scene);
  23687. ground._setReady(false);
  23688. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  23689. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  23690. ground._width = options.width || 1;
  23691. ground._height = options.height || 1;
  23692. ground._maxX = ground._width / 2;
  23693. ground._maxZ = ground._height / 2;
  23694. ground._minX = -ground._maxX;
  23695. ground._minZ = -ground._maxZ;
  23696. var vertexData = BABYLON.VertexData.CreateGround(options);
  23697. vertexData.applyToMesh(ground, options.updatable);
  23698. ground._setReady(true);
  23699. return ground;
  23700. };
  23701. /**
  23702. * Creates a tiled ground mesh.
  23703. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  23704. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23705. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23706. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23707. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23708. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23709. * numbers of subdivisions on the ground width and height of each tile.
  23710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23711. */
  23712. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  23713. var tiledGround = new BABYLON.Mesh(name, scene);
  23714. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  23715. vertexData.applyToMesh(tiledGround, options.updatable);
  23716. return tiledGround;
  23717. };
  23718. /**
  23719. * Creates a ground mesh from a height map.
  23720. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23721. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  23722. * The parameter `url` sets the URL of the height map image resource.
  23723. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23724. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23725. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23726. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23727. * 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).
  23728. * This function is passed the newly built mesh :
  23729. * ```javascript
  23730. * function(mesh) { // do things
  23731. * return; }
  23732. * ```
  23733. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23734. */
  23735. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  23736. var width = options.width || 10.0;
  23737. var height = options.height || 10.0;
  23738. var subdivisions = options.subdivisions || 1 | 0;
  23739. var minHeight = options.minHeight || 0.0;
  23740. var maxHeight = options.maxHeight || 10.0;
  23741. var updatable = options.updatable;
  23742. var onReady = options.onReady;
  23743. var ground = new BABYLON.GroundMesh(name, scene);
  23744. ground._subdivisionsX = subdivisions;
  23745. ground._subdivisionsY = subdivisions;
  23746. ground._width = width;
  23747. ground._height = height;
  23748. ground._maxX = ground._width / 2.0;
  23749. ground._maxZ = ground._height / 2.0;
  23750. ground._minX = -ground._maxX;
  23751. ground._minZ = -ground._maxZ;
  23752. ground._setReady(false);
  23753. var onload = function (img) {
  23754. // Getting height map data
  23755. var canvas = document.createElement("canvas");
  23756. var context = canvas.getContext("2d");
  23757. var bufferWidth = img.width;
  23758. var bufferHeight = img.height;
  23759. canvas.width = bufferWidth;
  23760. canvas.height = bufferHeight;
  23761. context.drawImage(img, 0, 0);
  23762. // Create VertexData from map data
  23763. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  23764. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  23765. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  23766. width: width, height: height,
  23767. subdivisions: subdivisions,
  23768. minHeight: minHeight, maxHeight: maxHeight,
  23769. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  23770. });
  23771. vertexData.applyToMesh(ground, updatable);
  23772. ground._setReady(true);
  23773. //execute ready callback, if set
  23774. if (onReady) {
  23775. onReady(ground);
  23776. }
  23777. };
  23778. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  23779. return ground;
  23780. };
  23781. /**
  23782. * Creates a tube mesh.
  23783. * 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.
  23784. *
  23785. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  23786. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23787. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23788. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23789. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23790. * 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.
  23791. * It must return a radius value (positive float) :
  23792. * ```javascript
  23793. * var radiusFunction = function(i, distance) {
  23794. * // do things
  23795. * return radius; }
  23796. * ```
  23797. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  23798. * 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
  23799. * 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
  23800. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23801. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23802. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  23803. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23804. */
  23805. MeshBuilder.CreateTube = function (name, options, scene) {
  23806. var path = options.path;
  23807. var radius = options.radius || 1.0;
  23808. var tessellation = options.tessellation || 64 | 0;
  23809. var radiusFunction = options.radiusFunction;
  23810. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  23811. var invertUV = options.invertUV || false;
  23812. var updatable = options.updatable;
  23813. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23814. var instance = options.instance;
  23815. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  23816. // tube geometry
  23817. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  23818. var tangents = path3D.getTangents();
  23819. var normals = path3D.getNormals();
  23820. var distances = path3D.getDistances();
  23821. var pi2 = Math.PI * 2;
  23822. var step = pi2 / tessellation * arc;
  23823. var returnRadius = function () { return radius; };
  23824. var radiusFunctionFinal = radiusFunction || returnRadius;
  23825. var circlePath;
  23826. var rad;
  23827. var normal;
  23828. var rotated;
  23829. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23830. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23831. for (var i = 0; i < path.length; i++) {
  23832. rad = radiusFunctionFinal(i, distances[i]); // current radius
  23833. circlePath = Array(); // current circle array
  23834. normal = normals[i]; // current normal
  23835. for (var t = 0; t < tessellation; t++) {
  23836. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  23837. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  23838. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  23839. rotated.scaleInPlace(rad).addInPlace(path[i]);
  23840. circlePath[t] = rotated;
  23841. }
  23842. circlePaths[index] = circlePath;
  23843. index++;
  23844. }
  23845. // cap
  23846. var capPath = function (nbPoints, pathIndex) {
  23847. var pointCap = Array();
  23848. for (var i = 0; i < nbPoints; i++) {
  23849. pointCap.push(path[pathIndex]);
  23850. }
  23851. return pointCap;
  23852. };
  23853. switch (cap) {
  23854. case BABYLON.Mesh.NO_CAP:
  23855. break;
  23856. case BABYLON.Mesh.CAP_START:
  23857. circlePaths[0] = capPath(tessellation, 0);
  23858. circlePaths[1] = circlePaths[2].slice(0);
  23859. break;
  23860. case BABYLON.Mesh.CAP_END:
  23861. circlePaths[index] = circlePaths[index - 1].slice(0);
  23862. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  23863. break;
  23864. case BABYLON.Mesh.CAP_ALL:
  23865. circlePaths[0] = capPath(tessellation, 0);
  23866. circlePaths[1] = circlePaths[2].slice(0);
  23867. circlePaths[index] = circlePaths[index - 1].slice(0);
  23868. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  23869. break;
  23870. default:
  23871. break;
  23872. }
  23873. return circlePaths;
  23874. };
  23875. var path3D;
  23876. var pathArray;
  23877. if (instance) {
  23878. var arc = options.arc || instance.arc;
  23879. path3D = (instance.path3D).update(path);
  23880. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  23881. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  23882. instance.path3D = path3D;
  23883. instance.pathArray = pathArray;
  23884. instance.arc = arc;
  23885. return instance;
  23886. }
  23887. // tube creation
  23888. path3D = new BABYLON.Path3D(path);
  23889. var newPathArray = new Array();
  23890. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23891. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  23892. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  23893. tube.pathArray = pathArray;
  23894. tube.path3D = path3D;
  23895. tube.tessellation = tessellation;
  23896. tube.cap = cap;
  23897. tube.arc = options.arc;
  23898. return tube;
  23899. };
  23900. /**
  23901. * Creates a polyhedron mesh.
  23902. *
  23903. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  23904. * 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
  23905. * to choose the wanted type.
  23906. * The parameter `size` (positive float, default 1) sets the polygon size.
  23907. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23908. * 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`.
  23909. * 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
  23910. * 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)`).
  23911. * 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
  23912. * 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.
  23913. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23914. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23915. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23916. */
  23917. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  23918. var polyhedron = new BABYLON.Mesh(name, scene);
  23919. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  23920. polyhedron.sideOrientation = options.sideOrientation;
  23921. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  23922. vertexData.applyToMesh(polyhedron, options.updatable);
  23923. return polyhedron;
  23924. };
  23925. /**
  23926. * Creates a decal mesh.
  23927. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  23928. * 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.
  23929. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23930. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23931. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23932. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23933. */
  23934. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  23935. var indices = sourceMesh.getIndices();
  23936. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23937. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23938. var position = options.position || BABYLON.Vector3.Zero();
  23939. var normal = options.normal || BABYLON.Vector3.Up();
  23940. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  23941. var angle = options.angle || 0;
  23942. // Getting correct rotation
  23943. if (!normal) {
  23944. var target = new BABYLON.Vector3(0, 0, 1);
  23945. var camera = sourceMesh.getScene().activeCamera;
  23946. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  23947. normal = camera.globalPosition.subtract(cameraWorldTarget);
  23948. }
  23949. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  23950. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  23951. var pitch = Math.atan2(normal.y, len);
  23952. // Matrix
  23953. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  23954. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  23955. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  23956. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  23957. var vertexData = new BABYLON.VertexData();
  23958. vertexData.indices = [];
  23959. vertexData.positions = [];
  23960. vertexData.normals = [];
  23961. vertexData.uvs = [];
  23962. var currentVertexDataIndex = 0;
  23963. var extractDecalVector3 = function (indexId) {
  23964. var vertexId = indices[indexId];
  23965. var result = new BABYLON.PositionNormalVertex();
  23966. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  23967. // Send vector to decal local world
  23968. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  23969. // Get normal
  23970. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  23971. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  23972. return result;
  23973. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  23974. var clip = function (vertices, axis) {
  23975. if (vertices.length === 0) {
  23976. return vertices;
  23977. }
  23978. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  23979. var clipVertices = function (v0, v1) {
  23980. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  23981. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  23982. };
  23983. var result = new Array();
  23984. for (var index = 0; index < vertices.length; index += 3) {
  23985. var v1Out;
  23986. var v2Out;
  23987. var v3Out;
  23988. var total = 0;
  23989. var nV1, nV2, nV3, nV4;
  23990. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  23991. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  23992. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  23993. v1Out = d1 > 0;
  23994. v2Out = d2 > 0;
  23995. v3Out = d3 > 0;
  23996. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  23997. switch (total) {
  23998. case 0:
  23999. result.push(vertices[index]);
  24000. result.push(vertices[index + 1]);
  24001. result.push(vertices[index + 2]);
  24002. break;
  24003. case 1:
  24004. if (v1Out) {
  24005. nV1 = vertices[index + 1];
  24006. nV2 = vertices[index + 2];
  24007. nV3 = clipVertices(vertices[index], nV1);
  24008. nV4 = clipVertices(vertices[index], nV2);
  24009. }
  24010. if (v2Out) {
  24011. nV1 = vertices[index];
  24012. nV2 = vertices[index + 2];
  24013. nV3 = clipVertices(vertices[index + 1], nV1);
  24014. nV4 = clipVertices(vertices[index + 1], nV2);
  24015. result.push(nV3);
  24016. result.push(nV2.clone());
  24017. result.push(nV1.clone());
  24018. result.push(nV2.clone());
  24019. result.push(nV3.clone());
  24020. result.push(nV4);
  24021. break;
  24022. }
  24023. if (v3Out) {
  24024. nV1 = vertices[index];
  24025. nV2 = vertices[index + 1];
  24026. nV3 = clipVertices(vertices[index + 2], nV1);
  24027. nV4 = clipVertices(vertices[index + 2], nV2);
  24028. }
  24029. result.push(nV1.clone());
  24030. result.push(nV2.clone());
  24031. result.push(nV3);
  24032. result.push(nV4);
  24033. result.push(nV3.clone());
  24034. result.push(nV2.clone());
  24035. break;
  24036. case 2:
  24037. if (!v1Out) {
  24038. nV1 = vertices[index].clone();
  24039. nV2 = clipVertices(nV1, vertices[index + 1]);
  24040. nV3 = clipVertices(nV1, vertices[index + 2]);
  24041. result.push(nV1);
  24042. result.push(nV2);
  24043. result.push(nV3);
  24044. }
  24045. if (!v2Out) {
  24046. nV1 = vertices[index + 1].clone();
  24047. nV2 = clipVertices(nV1, vertices[index + 2]);
  24048. nV3 = clipVertices(nV1, vertices[index]);
  24049. result.push(nV1);
  24050. result.push(nV2);
  24051. result.push(nV3);
  24052. }
  24053. if (!v3Out) {
  24054. nV1 = vertices[index + 2].clone();
  24055. nV2 = clipVertices(nV1, vertices[index]);
  24056. nV3 = clipVertices(nV1, vertices[index + 1]);
  24057. result.push(nV1);
  24058. result.push(nV2);
  24059. result.push(nV3);
  24060. }
  24061. break;
  24062. case 3:
  24063. break;
  24064. }
  24065. }
  24066. return result;
  24067. };
  24068. for (var index = 0; index < indices.length; index += 3) {
  24069. var faceVertices = new Array();
  24070. faceVertices.push(extractDecalVector3(index));
  24071. faceVertices.push(extractDecalVector3(index + 1));
  24072. faceVertices.push(extractDecalVector3(index + 2));
  24073. // Clip
  24074. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  24075. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  24076. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  24077. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  24078. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  24079. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  24080. if (faceVertices.length === 0) {
  24081. continue;
  24082. }
  24083. // Add UVs and get back to world
  24084. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  24085. var vertex = faceVertices[vIndex];
  24086. //TODO check for Int32Array | Uint32Array | Uint16Array
  24087. vertexData.indices.push(currentVertexDataIndex);
  24088. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  24089. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  24090. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  24091. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  24092. currentVertexDataIndex++;
  24093. }
  24094. }
  24095. // Return mesh
  24096. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  24097. vertexData.applyToMesh(decal);
  24098. decal.position = position.clone();
  24099. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  24100. return decal;
  24101. };
  24102. // Privates
  24103. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  24104. // extrusion geometry
  24105. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  24106. var tangents = path3D.getTangents();
  24107. var normals = path3D.getNormals();
  24108. var binormals = path3D.getBinormals();
  24109. var distances = path3D.getDistances();
  24110. var angle = 0;
  24111. var returnScale = function () { return scale; };
  24112. var returnRotation = function () { return rotation; };
  24113. var rotate = custom ? rotateFunction : returnRotation;
  24114. var scl = custom ? scaleFunction : returnScale;
  24115. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  24116. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  24117. for (var i = 0; i < curve.length; i++) {
  24118. var shapePath = new Array();
  24119. var angleStep = rotate(i, distances[i]);
  24120. var scaleRatio = scl(i, distances[i]);
  24121. for (var p = 0; p < shape.length; p++) {
  24122. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  24123. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  24124. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  24125. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  24126. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  24127. shapePath[p] = rotated;
  24128. }
  24129. shapePaths[index] = shapePath;
  24130. angle += angleStep;
  24131. index++;
  24132. }
  24133. // cap
  24134. var capPath = function (shapePath) {
  24135. var pointCap = Array();
  24136. var barycenter = BABYLON.Vector3.Zero();
  24137. var i;
  24138. for (i = 0; i < shapePath.length; i++) {
  24139. barycenter.addInPlace(shapePath[i]);
  24140. }
  24141. barycenter.scaleInPlace(1.0 / shapePath.length);
  24142. for (i = 0; i < shapePath.length; i++) {
  24143. pointCap.push(barycenter);
  24144. }
  24145. return pointCap;
  24146. };
  24147. switch (cap) {
  24148. case BABYLON.Mesh.NO_CAP:
  24149. break;
  24150. case BABYLON.Mesh.CAP_START:
  24151. shapePaths[0] = capPath(shapePaths[2]);
  24152. shapePaths[1] = shapePaths[2];
  24153. break;
  24154. case BABYLON.Mesh.CAP_END:
  24155. shapePaths[index] = shapePaths[index - 1];
  24156. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  24157. break;
  24158. case BABYLON.Mesh.CAP_ALL:
  24159. shapePaths[0] = capPath(shapePaths[2]);
  24160. shapePaths[1] = shapePaths[2];
  24161. shapePaths[index] = shapePaths[index - 1];
  24162. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  24163. break;
  24164. default:
  24165. break;
  24166. }
  24167. return shapePaths;
  24168. };
  24169. var path3D;
  24170. var pathArray;
  24171. if (instance) {
  24172. path3D = (instance.path3D).update(curve);
  24173. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  24174. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  24175. return instance;
  24176. }
  24177. // extruded shape creation
  24178. path3D = new BABYLON.Path3D(curve);
  24179. var newShapePaths = new Array();
  24180. cap = (cap < 0 || cap > 3) ? 0 : cap;
  24181. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  24182. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  24183. extrudedGeneric.pathArray = pathArray;
  24184. extrudedGeneric.path3D = path3D;
  24185. extrudedGeneric.cap = cap;
  24186. return extrudedGeneric;
  24187. };
  24188. return MeshBuilder;
  24189. }());
  24190. BABYLON.MeshBuilder = MeshBuilder;
  24191. })(BABYLON || (BABYLON = {}));
  24192. //# sourceMappingURL=babylon.meshBuilder.js.map
  24193. var BABYLON;
  24194. (function (BABYLON) {
  24195. var BaseTexture = (function () {
  24196. function BaseTexture(scene) {
  24197. this.hasAlpha = false;
  24198. this.getAlphaFromRGB = false;
  24199. this.level = 1;
  24200. this.coordinatesIndex = 0;
  24201. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  24202. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24203. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24204. this.anisotropicFilteringLevel = 4;
  24205. this.isCube = false;
  24206. this.isRenderTarget = false;
  24207. this.animations = new Array();
  24208. /**
  24209. * An event triggered when the texture is disposed.
  24210. * @type {BABYLON.Observable}
  24211. */
  24212. this.onDisposeObservable = new BABYLON.Observable();
  24213. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  24214. this._scene = scene;
  24215. this._scene.textures.push(this);
  24216. this._uid = null;
  24217. }
  24218. Object.defineProperty(BaseTexture.prototype, "uid", {
  24219. get: function () {
  24220. if (!this._uid) {
  24221. this._uid = BABYLON.Tools.RandomId();
  24222. }
  24223. return this._uid;
  24224. },
  24225. enumerable: true,
  24226. configurable: true
  24227. });
  24228. BaseTexture.prototype.toString = function () {
  24229. return this.name;
  24230. };
  24231. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  24232. set: function (callback) {
  24233. if (this._onDisposeObserver) {
  24234. this.onDisposeObservable.remove(this._onDisposeObserver);
  24235. }
  24236. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24237. },
  24238. enumerable: true,
  24239. configurable: true
  24240. });
  24241. BaseTexture.prototype.getScene = function () {
  24242. return this._scene;
  24243. };
  24244. BaseTexture.prototype.getTextureMatrix = function () {
  24245. return null;
  24246. };
  24247. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  24248. return null;
  24249. };
  24250. BaseTexture.prototype.getInternalTexture = function () {
  24251. return this._texture;
  24252. };
  24253. BaseTexture.prototype.isReady = function () {
  24254. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24255. return true;
  24256. }
  24257. if (this._texture) {
  24258. return this._texture.isReady;
  24259. }
  24260. return false;
  24261. };
  24262. BaseTexture.prototype.getSize = function () {
  24263. if (this._texture._width) {
  24264. return new BABYLON.Size(this._texture._width, this._texture._height);
  24265. }
  24266. if (this._texture._size) {
  24267. return new BABYLON.Size(this._texture._size, this._texture._size);
  24268. }
  24269. return BABYLON.Size.Zero();
  24270. };
  24271. BaseTexture.prototype.getBaseSize = function () {
  24272. if (!this.isReady() || !this._texture)
  24273. return BABYLON.Size.Zero();
  24274. if (this._texture._size) {
  24275. return new BABYLON.Size(this._texture._size, this._texture._size);
  24276. }
  24277. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  24278. };
  24279. BaseTexture.prototype.scale = function (ratio) {
  24280. };
  24281. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  24282. get: function () {
  24283. return false;
  24284. },
  24285. enumerable: true,
  24286. configurable: true
  24287. });
  24288. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  24289. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24290. for (var index = 0; index < texturesCache.length; index++) {
  24291. var texturesCacheEntry = texturesCache[index];
  24292. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  24293. texturesCache.splice(index, 1);
  24294. return;
  24295. }
  24296. }
  24297. };
  24298. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  24299. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  24300. for (var index = 0; index < texturesCache.length; index++) {
  24301. var texturesCacheEntry = texturesCache[index];
  24302. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  24303. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  24304. texturesCacheEntry.references++;
  24305. return texturesCacheEntry;
  24306. }
  24307. }
  24308. }
  24309. return null;
  24310. };
  24311. BaseTexture.prototype.delayLoad = function () {
  24312. };
  24313. BaseTexture.prototype.clone = function () {
  24314. return null;
  24315. };
  24316. BaseTexture.prototype.releaseInternalTexture = function () {
  24317. if (this._texture) {
  24318. this._scene.getEngine().releaseInternalTexture(this._texture);
  24319. delete this._texture;
  24320. }
  24321. };
  24322. BaseTexture.prototype.dispose = function () {
  24323. // Animations
  24324. this.getScene().stopAnimation(this);
  24325. // Remove from scene
  24326. var index = this._scene.textures.indexOf(this);
  24327. if (index >= 0) {
  24328. this._scene.textures.splice(index, 1);
  24329. }
  24330. if (this._texture === undefined) {
  24331. return;
  24332. }
  24333. // Release
  24334. this.releaseInternalTexture();
  24335. // Callback
  24336. this.onDisposeObservable.notifyObservers(this);
  24337. this.onDisposeObservable.clear();
  24338. };
  24339. BaseTexture.prototype.serialize = function () {
  24340. if (!this.name) {
  24341. return null;
  24342. }
  24343. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  24344. // Animations
  24345. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  24346. return serializationObject;
  24347. };
  24348. return BaseTexture;
  24349. }());
  24350. __decorate([
  24351. BABYLON.serialize()
  24352. ], BaseTexture.prototype, "name", void 0);
  24353. __decorate([
  24354. BABYLON.serialize()
  24355. ], BaseTexture.prototype, "hasAlpha", void 0);
  24356. __decorate([
  24357. BABYLON.serialize()
  24358. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  24359. __decorate([
  24360. BABYLON.serialize()
  24361. ], BaseTexture.prototype, "level", void 0);
  24362. __decorate([
  24363. BABYLON.serialize()
  24364. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  24365. __decorate([
  24366. BABYLON.serialize()
  24367. ], BaseTexture.prototype, "coordinatesMode", void 0);
  24368. __decorate([
  24369. BABYLON.serialize()
  24370. ], BaseTexture.prototype, "wrapU", void 0);
  24371. __decorate([
  24372. BABYLON.serialize()
  24373. ], BaseTexture.prototype, "wrapV", void 0);
  24374. __decorate([
  24375. BABYLON.serialize()
  24376. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  24377. __decorate([
  24378. BABYLON.serialize()
  24379. ], BaseTexture.prototype, "isCube", void 0);
  24380. __decorate([
  24381. BABYLON.serialize()
  24382. ], BaseTexture.prototype, "isRenderTarget", void 0);
  24383. BABYLON.BaseTexture = BaseTexture;
  24384. })(BABYLON || (BABYLON = {}));
  24385. //# sourceMappingURL=babylon.baseTexture.js.map
  24386. var BABYLON;
  24387. (function (BABYLON) {
  24388. var Texture = (function (_super) {
  24389. __extends(Texture, _super);
  24390. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  24391. if (noMipmap === void 0) { noMipmap = false; }
  24392. if (invertY === void 0) { invertY = true; }
  24393. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24394. if (onLoad === void 0) { onLoad = null; }
  24395. if (onError === void 0) { onError = null; }
  24396. if (buffer === void 0) { buffer = null; }
  24397. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24398. var _this = _super.call(this, scene) || this;
  24399. _this.uOffset = 0;
  24400. _this.vOffset = 0;
  24401. _this.uScale = 1.0;
  24402. _this.vScale = 1.0;
  24403. _this.uAng = 0;
  24404. _this.vAng = 0;
  24405. _this.wAng = 0;
  24406. _this.name = url;
  24407. _this.url = url;
  24408. _this._noMipmap = noMipmap;
  24409. _this._invertY = invertY;
  24410. _this._samplingMode = samplingMode;
  24411. _this._buffer = buffer;
  24412. _this._deleteBuffer = deleteBuffer;
  24413. if (!url) {
  24414. return _this;
  24415. }
  24416. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  24417. var load = function () {
  24418. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  24419. _this.onLoadObservable.notifyObservers(true);
  24420. }
  24421. if (onLoad) {
  24422. onLoad();
  24423. }
  24424. };
  24425. if (!_this._texture) {
  24426. if (!scene.useDelayedTextureLoading) {
  24427. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer);
  24428. if (deleteBuffer) {
  24429. delete _this._buffer;
  24430. }
  24431. }
  24432. else {
  24433. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24434. _this._delayedOnLoad = load;
  24435. _this._delayedOnError = onError;
  24436. }
  24437. }
  24438. else {
  24439. if (_this._texture.isReady) {
  24440. BABYLON.Tools.SetImmediate(function () { return load(); });
  24441. }
  24442. else {
  24443. _this._texture.onLoadedCallbacks.push(load);
  24444. }
  24445. }
  24446. return _this;
  24447. }
  24448. Object.defineProperty(Texture.prototype, "noMipmap", {
  24449. get: function () {
  24450. return this._noMipmap;
  24451. },
  24452. enumerable: true,
  24453. configurable: true
  24454. });
  24455. Texture.prototype.delayLoad = function () {
  24456. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24457. return;
  24458. }
  24459. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24460. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  24461. if (!this._texture) {
  24462. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  24463. if (this._deleteBuffer) {
  24464. delete this._buffer;
  24465. }
  24466. }
  24467. };
  24468. Texture.prototype.updateSamplingMode = function (samplingMode) {
  24469. if (!this._texture) {
  24470. return;
  24471. }
  24472. this._samplingMode = samplingMode;
  24473. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  24474. };
  24475. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  24476. x *= this.uScale;
  24477. y *= this.vScale;
  24478. x -= 0.5 * this.uScale;
  24479. y -= 0.5 * this.vScale;
  24480. z -= 0.5;
  24481. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  24482. t.x += 0.5 * this.uScale + this.uOffset;
  24483. t.y += 0.5 * this.vScale + this.vOffset;
  24484. t.z += 0.5;
  24485. };
  24486. Texture.prototype.getTextureMatrix = function () {
  24487. if (this.uOffset === this._cachedUOffset &&
  24488. this.vOffset === this._cachedVOffset &&
  24489. this.uScale === this._cachedUScale &&
  24490. this.vScale === this._cachedVScale &&
  24491. this.uAng === this._cachedUAng &&
  24492. this.vAng === this._cachedVAng &&
  24493. this.wAng === this._cachedWAng) {
  24494. return this._cachedTextureMatrix;
  24495. }
  24496. this._cachedUOffset = this.uOffset;
  24497. this._cachedVOffset = this.vOffset;
  24498. this._cachedUScale = this.uScale;
  24499. this._cachedVScale = this.vScale;
  24500. this._cachedUAng = this.uAng;
  24501. this._cachedVAng = this.vAng;
  24502. this._cachedWAng = this.wAng;
  24503. if (!this._cachedTextureMatrix) {
  24504. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24505. this._rowGenerationMatrix = new BABYLON.Matrix();
  24506. this._t0 = BABYLON.Vector3.Zero();
  24507. this._t1 = BABYLON.Vector3.Zero();
  24508. this._t2 = BABYLON.Vector3.Zero();
  24509. }
  24510. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  24511. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  24512. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  24513. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  24514. this._t1.subtractInPlace(this._t0);
  24515. this._t2.subtractInPlace(this._t0);
  24516. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24517. this._cachedTextureMatrix.m[0] = this._t1.x;
  24518. this._cachedTextureMatrix.m[1] = this._t1.y;
  24519. this._cachedTextureMatrix.m[2] = this._t1.z;
  24520. this._cachedTextureMatrix.m[4] = this._t2.x;
  24521. this._cachedTextureMatrix.m[5] = this._t2.y;
  24522. this._cachedTextureMatrix.m[6] = this._t2.z;
  24523. this._cachedTextureMatrix.m[8] = this._t0.x;
  24524. this._cachedTextureMatrix.m[9] = this._t0.y;
  24525. this._cachedTextureMatrix.m[10] = this._t0.z;
  24526. return this._cachedTextureMatrix;
  24527. };
  24528. Texture.prototype.getReflectionTextureMatrix = function () {
  24529. if (this.uOffset === this._cachedUOffset &&
  24530. this.vOffset === this._cachedVOffset &&
  24531. this.uScale === this._cachedUScale &&
  24532. this.vScale === this._cachedVScale &&
  24533. this.coordinatesMode === this._cachedCoordinatesMode) {
  24534. return this._cachedTextureMatrix;
  24535. }
  24536. if (!this._cachedTextureMatrix) {
  24537. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  24538. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  24539. }
  24540. this._cachedCoordinatesMode = this.coordinatesMode;
  24541. switch (this.coordinatesMode) {
  24542. case Texture.PLANAR_MODE:
  24543. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24544. this._cachedTextureMatrix[0] = this.uScale;
  24545. this._cachedTextureMatrix[5] = this.vScale;
  24546. this._cachedTextureMatrix[12] = this.uOffset;
  24547. this._cachedTextureMatrix[13] = this.vOffset;
  24548. break;
  24549. case Texture.PROJECTION_MODE:
  24550. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  24551. this._projectionModeMatrix.m[0] = 0.5;
  24552. this._projectionModeMatrix.m[5] = -0.5;
  24553. this._projectionModeMatrix.m[10] = 0.0;
  24554. this._projectionModeMatrix.m[12] = 0.5;
  24555. this._projectionModeMatrix.m[13] = 0.5;
  24556. this._projectionModeMatrix.m[14] = 1.0;
  24557. this._projectionModeMatrix.m[15] = 1.0;
  24558. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  24559. break;
  24560. default:
  24561. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  24562. break;
  24563. }
  24564. return this._cachedTextureMatrix;
  24565. };
  24566. Texture.prototype.clone = function () {
  24567. var _this = this;
  24568. return BABYLON.SerializationHelper.Clone(function () {
  24569. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  24570. }, this);
  24571. };
  24572. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  24573. get: function () {
  24574. if (!this._onLoadObservarble) {
  24575. this._onLoadObservarble = new BABYLON.Observable();
  24576. }
  24577. return this._onLoadObservarble;
  24578. },
  24579. enumerable: true,
  24580. configurable: true
  24581. });
  24582. // Statics
  24583. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  24584. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24585. if (onLoad === void 0) { onLoad = null; }
  24586. if (onError === void 0) { onError = null; }
  24587. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  24588. };
  24589. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  24590. if (parsedTexture.customType) {
  24591. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  24592. return customTexture.Parse(parsedTexture, scene, rootUrl);
  24593. }
  24594. if (parsedTexture.isCube) {
  24595. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  24596. }
  24597. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  24598. return null;
  24599. }
  24600. var texture = BABYLON.SerializationHelper.Parse(function () {
  24601. if (parsedTexture.mirrorPlane) {
  24602. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  24603. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  24604. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  24605. return mirrorTexture;
  24606. }
  24607. else if (parsedTexture.isRenderTarget) {
  24608. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  24609. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  24610. return renderTargetTexture;
  24611. }
  24612. else {
  24613. var texture;
  24614. if (parsedTexture.base64String) {
  24615. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  24616. }
  24617. else {
  24618. texture = new Texture(rootUrl + parsedTexture.name, scene);
  24619. }
  24620. return texture;
  24621. }
  24622. }, parsedTexture, scene);
  24623. // Animations
  24624. if (parsedTexture.animations) {
  24625. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24626. var parsedAnimation = parsedTexture.animations[animationIndex];
  24627. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24628. }
  24629. }
  24630. return texture;
  24631. };
  24632. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  24633. if (deleteBuffer === void 0) { deleteBuffer = false; }
  24634. if (noMipmap === void 0) { noMipmap = false; }
  24635. if (invertY === void 0) { invertY = true; }
  24636. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  24637. if (onLoad === void 0) { onLoad = null; }
  24638. if (onError === void 0) { onError = null; }
  24639. if (name.substr(0, 5) !== "data:") {
  24640. name = "data:" + name;
  24641. }
  24642. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  24643. };
  24644. return Texture;
  24645. }(BABYLON.BaseTexture));
  24646. // Constants
  24647. Texture.NEAREST_SAMPLINGMODE = 1;
  24648. Texture.BILINEAR_SAMPLINGMODE = 2;
  24649. Texture.TRILINEAR_SAMPLINGMODE = 3;
  24650. Texture.EXPLICIT_MODE = 0;
  24651. Texture.SPHERICAL_MODE = 1;
  24652. Texture.PLANAR_MODE = 2;
  24653. Texture.CUBIC_MODE = 3;
  24654. Texture.PROJECTION_MODE = 4;
  24655. Texture.SKYBOX_MODE = 5;
  24656. Texture.INVCUBIC_MODE = 6;
  24657. Texture.EQUIRECTANGULAR_MODE = 7;
  24658. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  24659. Texture.CLAMP_ADDRESSMODE = 0;
  24660. Texture.WRAP_ADDRESSMODE = 1;
  24661. Texture.MIRROR_ADDRESSMODE = 2;
  24662. __decorate([
  24663. BABYLON.serialize()
  24664. ], Texture.prototype, "url", void 0);
  24665. __decorate([
  24666. BABYLON.serialize()
  24667. ], Texture.prototype, "uOffset", void 0);
  24668. __decorate([
  24669. BABYLON.serialize()
  24670. ], Texture.prototype, "vOffset", void 0);
  24671. __decorate([
  24672. BABYLON.serialize()
  24673. ], Texture.prototype, "uScale", void 0);
  24674. __decorate([
  24675. BABYLON.serialize()
  24676. ], Texture.prototype, "vScale", void 0);
  24677. __decorate([
  24678. BABYLON.serialize()
  24679. ], Texture.prototype, "uAng", void 0);
  24680. __decorate([
  24681. BABYLON.serialize()
  24682. ], Texture.prototype, "vAng", void 0);
  24683. __decorate([
  24684. BABYLON.serialize()
  24685. ], Texture.prototype, "wAng", void 0);
  24686. BABYLON.Texture = Texture;
  24687. })(BABYLON || (BABYLON = {}));
  24688. //# sourceMappingURL=babylon.texture.js.map
  24689. var BABYLON;
  24690. (function (BABYLON) {
  24691. var CubeTexture = (function (_super) {
  24692. __extends(CubeTexture, _super);
  24693. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  24694. if (onLoad === void 0) { onLoad = null; }
  24695. if (onError === void 0) { onError = null; }
  24696. var _this = _super.call(this, scene) || this;
  24697. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  24698. _this.name = rootUrl;
  24699. _this.url = rootUrl;
  24700. _this._noMipmap = noMipmap;
  24701. _this.hasAlpha = false;
  24702. if (!rootUrl && !files) {
  24703. return _this;
  24704. }
  24705. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  24706. if (!files) {
  24707. if (!extensions) {
  24708. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  24709. }
  24710. files = [];
  24711. for (var index = 0; index < extensions.length; index++) {
  24712. files.push(rootUrl + extensions[index]);
  24713. }
  24714. _this._extensions = extensions;
  24715. }
  24716. _this._files = files;
  24717. if (!_this._texture) {
  24718. if (!scene.useDelayedTextureLoading) {
  24719. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  24720. }
  24721. else {
  24722. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  24723. }
  24724. }
  24725. else if (onLoad) {
  24726. if (_this._texture.isReady) {
  24727. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  24728. }
  24729. else {
  24730. _this._texture.onLoadedCallbacks.push(onLoad);
  24731. }
  24732. }
  24733. _this.isCube = true;
  24734. _this._textureMatrix = BABYLON.Matrix.Identity();
  24735. return _this;
  24736. }
  24737. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  24738. return new CubeTexture("", scene, null, noMipmap, files);
  24739. };
  24740. // Methods
  24741. CubeTexture.prototype.delayLoad = function () {
  24742. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  24743. return;
  24744. }
  24745. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  24746. this._texture = this._getFromCache(this.url, this._noMipmap);
  24747. if (!this._texture) {
  24748. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  24749. }
  24750. };
  24751. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  24752. return this._textureMatrix;
  24753. };
  24754. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  24755. var texture = BABYLON.SerializationHelper.Parse(function () {
  24756. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  24757. }, parsedTexture, scene);
  24758. // Animations
  24759. if (parsedTexture.animations) {
  24760. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  24761. var parsedAnimation = parsedTexture.animations[animationIndex];
  24762. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24763. }
  24764. }
  24765. return texture;
  24766. };
  24767. CubeTexture.prototype.clone = function () {
  24768. var _this = this;
  24769. return BABYLON.SerializationHelper.Clone(function () {
  24770. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  24771. }, this);
  24772. };
  24773. return CubeTexture;
  24774. }(BABYLON.BaseTexture));
  24775. BABYLON.CubeTexture = CubeTexture;
  24776. })(BABYLON || (BABYLON = {}));
  24777. //# sourceMappingURL=babylon.cubeTexture.js.map
  24778. var BABYLON;
  24779. (function (BABYLON) {
  24780. var RenderTargetTexture = (function (_super) {
  24781. __extends(RenderTargetTexture, _super);
  24782. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  24783. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  24784. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  24785. if (isCube === void 0) { isCube = false; }
  24786. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24787. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  24788. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  24789. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24790. _this.isCube = isCube;
  24791. /**
  24792. * Use this list to define the list of mesh you want to render.
  24793. */
  24794. _this.renderList = new Array();
  24795. _this.renderParticles = true;
  24796. _this.renderSprites = false;
  24797. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  24798. // Events
  24799. /**
  24800. * An event triggered when the texture is unbind.
  24801. * @type {BABYLON.Observable}
  24802. */
  24803. _this.onAfterUnbindObservable = new BABYLON.Observable();
  24804. /**
  24805. * An event triggered before rendering the texture
  24806. * @type {BABYLON.Observable}
  24807. */
  24808. _this.onBeforeRenderObservable = new BABYLON.Observable();
  24809. /**
  24810. * An event triggered after rendering the texture
  24811. * @type {BABYLON.Observable}
  24812. */
  24813. _this.onAfterRenderObservable = new BABYLON.Observable();
  24814. /**
  24815. * An event triggered after the texture clear
  24816. * @type {BABYLON.Observable}
  24817. */
  24818. _this.onClearObservable = new BABYLON.Observable();
  24819. _this._currentRefreshId = -1;
  24820. _this._refreshRate = 1;
  24821. _this.name = name;
  24822. _this.isRenderTarget = true;
  24823. _this._size = size;
  24824. _this._generateMipMaps = generateMipMaps;
  24825. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  24826. _this._renderTargetOptions = {
  24827. generateMipMaps: generateMipMaps,
  24828. type: type,
  24829. samplingMode: samplingMode,
  24830. generateDepthBuffer: generateDepthBuffer,
  24831. generateStencilBuffer: generateStencilBuffer
  24832. };
  24833. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  24834. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24835. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24836. }
  24837. if (isCube) {
  24838. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  24839. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  24840. _this._textureMatrix = BABYLON.Matrix.Identity();
  24841. }
  24842. else {
  24843. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  24844. }
  24845. // Rendering groups
  24846. _this._renderingManager = new BABYLON.RenderingManager(scene);
  24847. return _this;
  24848. }
  24849. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  24850. get: function () {
  24851. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  24852. },
  24853. enumerable: true,
  24854. configurable: true
  24855. });
  24856. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  24857. get: function () {
  24858. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  24859. },
  24860. enumerable: true,
  24861. configurable: true
  24862. });
  24863. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  24864. get: function () {
  24865. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  24866. },
  24867. enumerable: true,
  24868. configurable: true
  24869. });
  24870. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  24871. set: function (callback) {
  24872. if (this._onAfterUnbindObserver) {
  24873. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  24874. }
  24875. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  24876. },
  24877. enumerable: true,
  24878. configurable: true
  24879. });
  24880. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  24881. set: function (callback) {
  24882. if (this._onBeforeRenderObserver) {
  24883. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24884. }
  24885. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24886. },
  24887. enumerable: true,
  24888. configurable: true
  24889. });
  24890. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  24891. set: function (callback) {
  24892. if (this._onAfterRenderObserver) {
  24893. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24894. }
  24895. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24896. },
  24897. enumerable: true,
  24898. configurable: true
  24899. });
  24900. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  24901. set: function (callback) {
  24902. if (this._onClearObserver) {
  24903. this.onClearObservable.remove(this._onClearObserver);
  24904. }
  24905. this._onClearObserver = this.onClearObservable.add(callback);
  24906. },
  24907. enumerable: true,
  24908. configurable: true
  24909. });
  24910. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  24911. this._currentRefreshId = -1;
  24912. };
  24913. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  24914. get: function () {
  24915. return this._refreshRate;
  24916. },
  24917. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24918. set: function (value) {
  24919. this._refreshRate = value;
  24920. this.resetRefreshCounter();
  24921. },
  24922. enumerable: true,
  24923. configurable: true
  24924. });
  24925. RenderTargetTexture.prototype._shouldRender = function () {
  24926. if (this._currentRefreshId === -1) {
  24927. this._currentRefreshId = 1;
  24928. return true;
  24929. }
  24930. if (this.refreshRate === this._currentRefreshId) {
  24931. this._currentRefreshId = 1;
  24932. return true;
  24933. }
  24934. this._currentRefreshId++;
  24935. return false;
  24936. };
  24937. RenderTargetTexture.prototype.isReady = function () {
  24938. if (!this.getScene().renderTargetsEnabled) {
  24939. return false;
  24940. }
  24941. return _super.prototype.isReady.call(this);
  24942. };
  24943. RenderTargetTexture.prototype.getRenderSize = function () {
  24944. return this._size;
  24945. };
  24946. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  24947. get: function () {
  24948. return true;
  24949. },
  24950. enumerable: true,
  24951. configurable: true
  24952. });
  24953. RenderTargetTexture.prototype.scale = function (ratio) {
  24954. var newSize = this._size * ratio;
  24955. this.resize(newSize);
  24956. };
  24957. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  24958. if (this.isCube) {
  24959. return this._textureMatrix;
  24960. }
  24961. return _super.prototype.getReflectionTextureMatrix.call(this);
  24962. };
  24963. RenderTargetTexture.prototype.resize = function (size) {
  24964. this.releaseInternalTexture();
  24965. if (this.isCube) {
  24966. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  24967. }
  24968. else {
  24969. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  24970. }
  24971. };
  24972. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  24973. var scene = this.getScene();
  24974. var engine = scene.getEngine();
  24975. if (this.useCameraPostProcesses !== undefined) {
  24976. useCameraPostProcess = this.useCameraPostProcesses;
  24977. }
  24978. if (this._waitingRenderList) {
  24979. this.renderList = [];
  24980. for (var index = 0; index < this._waitingRenderList.length; index++) {
  24981. var id = this._waitingRenderList[index];
  24982. this.renderList.push(scene.getMeshByID(id));
  24983. }
  24984. delete this._waitingRenderList;
  24985. }
  24986. // Is predicate defined?
  24987. if (this.renderListPredicate) {
  24988. this.renderList.splice(0); // Clear previous renderList
  24989. var sceneMeshes = this.getScene().meshes;
  24990. for (var index = 0; index < sceneMeshes.length; index++) {
  24991. var mesh = sceneMeshes[index];
  24992. if (this.renderListPredicate(mesh)) {
  24993. this.renderList.push(mesh);
  24994. }
  24995. }
  24996. }
  24997. if (this.renderList && this.renderList.length === 0) {
  24998. return;
  24999. }
  25000. // Set custom projection.
  25001. // Needs to be before binding to prevent changing the aspect ratio.
  25002. if (this.activeCamera) {
  25003. engine.setViewport(this.activeCamera.viewport);
  25004. if (this.activeCamera !== scene.activeCamera) {
  25005. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  25006. }
  25007. }
  25008. else {
  25009. engine.setViewport(scene.activeCamera.viewport);
  25010. }
  25011. // Prepare renderingManager
  25012. this._renderingManager.reset();
  25013. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  25014. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  25015. var sceneRenderId = scene.getRenderId();
  25016. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  25017. var mesh = currentRenderList[meshIndex];
  25018. if (mesh) {
  25019. if (!mesh.isReady()) {
  25020. // Reset _currentRefreshId
  25021. this.resetRefreshCounter();
  25022. continue;
  25023. }
  25024. mesh._preActivateForIntermediateRendering(sceneRenderId);
  25025. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  25026. mesh._activate(sceneRenderId);
  25027. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  25028. var subMesh = mesh.subMeshes[subIndex];
  25029. scene._activeIndices.addCount(subMesh.indexCount, false);
  25030. this._renderingManager.dispatch(subMesh);
  25031. }
  25032. }
  25033. }
  25034. }
  25035. if (this.isCube) {
  25036. for (var face = 0; face < 6; face++) {
  25037. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  25038. scene.incrementRenderId();
  25039. scene.resetCachedMaterial();
  25040. }
  25041. }
  25042. else {
  25043. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  25044. }
  25045. this.onAfterUnbindObservable.notifyObservers(this);
  25046. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  25047. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  25048. }
  25049. engine.setViewport(scene.activeCamera.viewport);
  25050. scene.resetCachedMaterial();
  25051. };
  25052. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  25053. var scene = this.getScene();
  25054. var engine = scene.getEngine();
  25055. // Bind
  25056. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  25057. if (this.isCube) {
  25058. engine.bindFramebuffer(this._texture, faceIndex);
  25059. }
  25060. else {
  25061. engine.bindFramebuffer(this._texture);
  25062. }
  25063. }
  25064. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  25065. // Clear
  25066. if (this.onClearObservable.hasObservers()) {
  25067. this.onClearObservable.notifyObservers(engine);
  25068. }
  25069. else {
  25070. engine.clear(scene.clearColor, true, true, true);
  25071. }
  25072. if (!this._doNotChangeAspectRatio) {
  25073. scene.updateTransformMatrix(true);
  25074. }
  25075. // Render
  25076. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  25077. if (useCameraPostProcess) {
  25078. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  25079. }
  25080. if (!this._doNotChangeAspectRatio) {
  25081. scene.updateTransformMatrix(true);
  25082. }
  25083. this.onAfterRenderObservable.notifyObservers(faceIndex);
  25084. // Dump ?
  25085. if (dumpForDebug) {
  25086. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  25087. }
  25088. // Unbind
  25089. if (!this.isCube || faceIndex === 5) {
  25090. if (this.isCube) {
  25091. if (faceIndex === 5) {
  25092. engine.generateMipMapsForCubemap(this._texture);
  25093. }
  25094. }
  25095. engine.unBindFramebuffer(this._texture, this.isCube);
  25096. }
  25097. };
  25098. /**
  25099. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  25100. * This allowed control for front to back rendering or reversly depending of the special needs.
  25101. *
  25102. * @param renderingGroupId The rendering group id corresponding to its index
  25103. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  25104. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  25105. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  25106. */
  25107. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  25108. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  25109. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  25110. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  25111. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  25112. };
  25113. /**
  25114. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  25115. *
  25116. * @param renderingGroupId The rendering group id corresponding to its index
  25117. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  25118. */
  25119. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  25120. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  25121. };
  25122. RenderTargetTexture.prototype.clone = function () {
  25123. var textureSize = this.getSize();
  25124. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  25125. // Base texture
  25126. newTexture.hasAlpha = this.hasAlpha;
  25127. newTexture.level = this.level;
  25128. // RenderTarget Texture
  25129. newTexture.coordinatesMode = this.coordinatesMode;
  25130. newTexture.renderList = this.renderList.slice(0);
  25131. return newTexture;
  25132. };
  25133. RenderTargetTexture.prototype.serialize = function () {
  25134. if (!this.name) {
  25135. return null;
  25136. }
  25137. var serializationObject = _super.prototype.serialize.call(this);
  25138. serializationObject.renderTargetSize = this.getRenderSize();
  25139. serializationObject.renderList = [];
  25140. for (var index = 0; index < this.renderList.length; index++) {
  25141. serializationObject.renderList.push(this.renderList[index].id);
  25142. }
  25143. return serializationObject;
  25144. };
  25145. return RenderTargetTexture;
  25146. }(BABYLON.Texture));
  25147. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  25148. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  25149. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  25150. BABYLON.RenderTargetTexture = RenderTargetTexture;
  25151. })(BABYLON || (BABYLON = {}));
  25152. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  25153. var BABYLON;
  25154. (function (BABYLON) {
  25155. var ProceduralTexture = (function (_super) {
  25156. __extends(ProceduralTexture, _super);
  25157. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  25158. if (generateMipMaps === void 0) { generateMipMaps = true; }
  25159. if (isCube === void 0) { isCube = false; }
  25160. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  25161. _this.isCube = isCube;
  25162. _this.isEnabled = true;
  25163. _this._currentRefreshId = -1;
  25164. _this._refreshRate = 1;
  25165. _this._vertexBuffers = {};
  25166. _this._uniforms = new Array();
  25167. _this._samplers = new Array();
  25168. _this._textures = new Array();
  25169. _this._floats = new Array();
  25170. _this._floatsArrays = {};
  25171. _this._colors3 = new Array();
  25172. _this._colors4 = new Array();
  25173. _this._vectors2 = new Array();
  25174. _this._vectors3 = new Array();
  25175. _this._matrices = new Array();
  25176. _this._fallbackTextureUsed = false;
  25177. scene._proceduralTextures.push(_this);
  25178. _this.name = name;
  25179. _this.isRenderTarget = true;
  25180. _this._size = size;
  25181. _this._generateMipMaps = generateMipMaps;
  25182. _this.setFragment(fragment);
  25183. _this._fallbackTexture = fallbackTexture;
  25184. var engine = scene.getEngine();
  25185. if (isCube) {
  25186. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  25187. _this.setFloat("face", 0);
  25188. }
  25189. else {
  25190. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  25191. }
  25192. // VBO
  25193. var vertices = [];
  25194. vertices.push(1, 1);
  25195. vertices.push(-1, 1);
  25196. vertices.push(-1, -1);
  25197. vertices.push(1, -1);
  25198. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  25199. // Indices
  25200. var indices = [];
  25201. indices.push(0);
  25202. indices.push(1);
  25203. indices.push(2);
  25204. indices.push(0);
  25205. indices.push(2);
  25206. indices.push(3);
  25207. _this._indexBuffer = engine.createIndexBuffer(indices);
  25208. return _this;
  25209. }
  25210. ProceduralTexture.prototype.reset = function () {
  25211. if (this._effect === undefined) {
  25212. return;
  25213. }
  25214. var engine = this.getScene().getEngine();
  25215. engine._releaseEffect(this._effect);
  25216. };
  25217. ProceduralTexture.prototype.isReady = function () {
  25218. var _this = this;
  25219. var engine = this.getScene().getEngine();
  25220. var shaders;
  25221. if (!this._fragment) {
  25222. return false;
  25223. }
  25224. if (this._fallbackTextureUsed) {
  25225. return true;
  25226. }
  25227. if (this._fragment.fragmentElement !== undefined) {
  25228. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  25229. }
  25230. else {
  25231. shaders = { vertex: "procedural", fragment: this._fragment };
  25232. }
  25233. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  25234. _this.releaseInternalTexture();
  25235. if (_this._fallbackTexture) {
  25236. _this._texture = _this._fallbackTexture._texture;
  25237. _this._texture.references++;
  25238. }
  25239. _this._fallbackTextureUsed = true;
  25240. });
  25241. return this._effect.isReady();
  25242. };
  25243. ProceduralTexture.prototype.resetRefreshCounter = function () {
  25244. this._currentRefreshId = -1;
  25245. };
  25246. ProceduralTexture.prototype.setFragment = function (fragment) {
  25247. this._fragment = fragment;
  25248. };
  25249. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  25250. get: function () {
  25251. return this._refreshRate;
  25252. },
  25253. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  25254. set: function (value) {
  25255. this._refreshRate = value;
  25256. this.resetRefreshCounter();
  25257. },
  25258. enumerable: true,
  25259. configurable: true
  25260. });
  25261. ProceduralTexture.prototype._shouldRender = function () {
  25262. if (!this.isEnabled || !this.isReady() || !this._texture) {
  25263. return false;
  25264. }
  25265. if (this._fallbackTextureUsed) {
  25266. return false;
  25267. }
  25268. if (this._currentRefreshId === -1) {
  25269. this._currentRefreshId = 1;
  25270. return true;
  25271. }
  25272. if (this.refreshRate === this._currentRefreshId) {
  25273. this._currentRefreshId = 1;
  25274. return true;
  25275. }
  25276. this._currentRefreshId++;
  25277. return false;
  25278. };
  25279. ProceduralTexture.prototype.getRenderSize = function () {
  25280. return this._size;
  25281. };
  25282. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  25283. if (this._fallbackTextureUsed) {
  25284. return;
  25285. }
  25286. this.releaseInternalTexture();
  25287. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  25288. };
  25289. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  25290. if (this._uniforms.indexOf(uniformName) === -1) {
  25291. this._uniforms.push(uniformName);
  25292. }
  25293. };
  25294. ProceduralTexture.prototype.setTexture = function (name, texture) {
  25295. if (this._samplers.indexOf(name) === -1) {
  25296. this._samplers.push(name);
  25297. }
  25298. this._textures[name] = texture;
  25299. return this;
  25300. };
  25301. ProceduralTexture.prototype.setFloat = function (name, value) {
  25302. this._checkUniform(name);
  25303. this._floats[name] = value;
  25304. return this;
  25305. };
  25306. ProceduralTexture.prototype.setFloats = function (name, value) {
  25307. this._checkUniform(name);
  25308. this._floatsArrays[name] = value;
  25309. return this;
  25310. };
  25311. ProceduralTexture.prototype.setColor3 = function (name, value) {
  25312. this._checkUniform(name);
  25313. this._colors3[name] = value;
  25314. return this;
  25315. };
  25316. ProceduralTexture.prototype.setColor4 = function (name, value) {
  25317. this._checkUniform(name);
  25318. this._colors4[name] = value;
  25319. return this;
  25320. };
  25321. ProceduralTexture.prototype.setVector2 = function (name, value) {
  25322. this._checkUniform(name);
  25323. this._vectors2[name] = value;
  25324. return this;
  25325. };
  25326. ProceduralTexture.prototype.setVector3 = function (name, value) {
  25327. this._checkUniform(name);
  25328. this._vectors3[name] = value;
  25329. return this;
  25330. };
  25331. ProceduralTexture.prototype.setMatrix = function (name, value) {
  25332. this._checkUniform(name);
  25333. this._matrices[name] = value;
  25334. return this;
  25335. };
  25336. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  25337. var scene = this.getScene();
  25338. var engine = scene.getEngine();
  25339. // Render
  25340. engine.enableEffect(this._effect);
  25341. engine.setState(false);
  25342. // Texture
  25343. for (var name in this._textures) {
  25344. this._effect.setTexture(name, this._textures[name]);
  25345. }
  25346. // Float
  25347. for (name in this._floats) {
  25348. this._effect.setFloat(name, this._floats[name]);
  25349. }
  25350. // Floats
  25351. for (name in this._floatsArrays) {
  25352. this._effect.setArray(name, this._floatsArrays[name]);
  25353. }
  25354. // Color3
  25355. for (name in this._colors3) {
  25356. this._effect.setColor3(name, this._colors3[name]);
  25357. }
  25358. // Color4
  25359. for (name in this._colors4) {
  25360. var color = this._colors4[name];
  25361. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  25362. }
  25363. // Vector2
  25364. for (name in this._vectors2) {
  25365. this._effect.setVector2(name, this._vectors2[name]);
  25366. }
  25367. // Vector3
  25368. for (name in this._vectors3) {
  25369. this._effect.setVector3(name, this._vectors3[name]);
  25370. }
  25371. // Matrix
  25372. for (name in this._matrices) {
  25373. this._effect.setMatrix(name, this._matrices[name]);
  25374. }
  25375. if (this.isCube) {
  25376. for (var face = 0; face < 6; face++) {
  25377. engine.bindFramebuffer(this._texture, face);
  25378. // VBOs
  25379. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  25380. this._effect.setFloat("face", face);
  25381. // Clear
  25382. engine.clear(scene.clearColor, true, true, true);
  25383. // Draw order
  25384. engine.draw(true, 0, 6);
  25385. // Mipmaps
  25386. if (face === 5) {
  25387. engine.generateMipMapsForCubemap(this._texture);
  25388. }
  25389. }
  25390. }
  25391. else {
  25392. engine.bindFramebuffer(this._texture);
  25393. // VBOs
  25394. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  25395. // Clear
  25396. engine.clear(scene.clearColor, true, true, true);
  25397. // Draw order
  25398. engine.draw(true, 0, 6);
  25399. }
  25400. // Unbind
  25401. engine.unBindFramebuffer(this._texture, this.isCube);
  25402. if (this.onGenerated) {
  25403. this.onGenerated();
  25404. }
  25405. };
  25406. ProceduralTexture.prototype.clone = function () {
  25407. var textureSize = this.getSize();
  25408. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  25409. // Base texture
  25410. newTexture.hasAlpha = this.hasAlpha;
  25411. newTexture.level = this.level;
  25412. // RenderTarget Texture
  25413. newTexture.coordinatesMode = this.coordinatesMode;
  25414. return newTexture;
  25415. };
  25416. ProceduralTexture.prototype.dispose = function () {
  25417. var index = this.getScene()._proceduralTextures.indexOf(this);
  25418. if (index >= 0) {
  25419. this.getScene()._proceduralTextures.splice(index, 1);
  25420. }
  25421. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  25422. if (vertexBuffer) {
  25423. vertexBuffer.dispose();
  25424. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  25425. }
  25426. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  25427. this._indexBuffer = null;
  25428. }
  25429. _super.prototype.dispose.call(this);
  25430. };
  25431. return ProceduralTexture;
  25432. }(BABYLON.Texture));
  25433. BABYLON.ProceduralTexture = ProceduralTexture;
  25434. })(BABYLON || (BABYLON = {}));
  25435. //# sourceMappingURL=babylon.proceduralTexture.js.map
  25436. var BABYLON;
  25437. (function (BABYLON) {
  25438. var MirrorTexture = (function (_super) {
  25439. __extends(MirrorTexture, _super);
  25440. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  25441. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  25442. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  25443. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  25444. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  25445. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  25446. _this._transformMatrix = BABYLON.Matrix.Zero();
  25447. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  25448. _this.onBeforeRenderObservable.add(function () {
  25449. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  25450. _this._savedViewMatrix = scene.getViewMatrix();
  25451. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  25452. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  25453. scene.clipPlane = _this.mirrorPlane;
  25454. scene.getEngine().cullBackFaces = false;
  25455. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  25456. });
  25457. _this.onAfterRenderObservable.add(function () {
  25458. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  25459. scene.getEngine().cullBackFaces = true;
  25460. scene._mirroredCameraPosition = null;
  25461. delete scene.clipPlane;
  25462. });
  25463. return _this;
  25464. }
  25465. MirrorTexture.prototype.clone = function () {
  25466. var textureSize = this.getSize();
  25467. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  25468. // Base texture
  25469. newTexture.hasAlpha = this.hasAlpha;
  25470. newTexture.level = this.level;
  25471. // Mirror Texture
  25472. newTexture.mirrorPlane = this.mirrorPlane.clone();
  25473. newTexture.renderList = this.renderList.slice(0);
  25474. return newTexture;
  25475. };
  25476. MirrorTexture.prototype.serialize = function () {
  25477. if (!this.name) {
  25478. return null;
  25479. }
  25480. var serializationObject = _super.prototype.serialize.call(this);
  25481. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  25482. return serializationObject;
  25483. };
  25484. return MirrorTexture;
  25485. }(BABYLON.RenderTargetTexture));
  25486. BABYLON.MirrorTexture = MirrorTexture;
  25487. })(BABYLON || (BABYLON = {}));
  25488. //# sourceMappingURL=babylon.mirrorTexture.js.map
  25489. var BABYLON;
  25490. (function (BABYLON) {
  25491. /**
  25492. * Creates a refraction texture used by refraction channel of the standard material.
  25493. * @param name the texture name
  25494. * @param size size of the underlying texture
  25495. * @param scene root scene
  25496. */
  25497. var RefractionTexture = (function (_super) {
  25498. __extends(RefractionTexture, _super);
  25499. function RefractionTexture(name, size, scene, generateMipMaps) {
  25500. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  25501. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  25502. _this.depth = 2.0;
  25503. _this.onBeforeRenderObservable.add(function () {
  25504. scene.clipPlane = _this.refractionPlane;
  25505. });
  25506. _this.onAfterRenderObservable.add(function () {
  25507. delete scene.clipPlane;
  25508. });
  25509. return _this;
  25510. }
  25511. RefractionTexture.prototype.clone = function () {
  25512. var textureSize = this.getSize();
  25513. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  25514. // Base texture
  25515. newTexture.hasAlpha = this.hasAlpha;
  25516. newTexture.level = this.level;
  25517. // Refraction Texture
  25518. newTexture.refractionPlane = this.refractionPlane.clone();
  25519. newTexture.renderList = this.renderList.slice(0);
  25520. newTexture.depth = this.depth;
  25521. return newTexture;
  25522. };
  25523. RefractionTexture.prototype.serialize = function () {
  25524. if (!this.name) {
  25525. return null;
  25526. }
  25527. var serializationObject = _super.prototype.serialize.call(this);
  25528. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  25529. serializationObject.depth = this.depth;
  25530. return serializationObject;
  25531. };
  25532. return RefractionTexture;
  25533. }(BABYLON.RenderTargetTexture));
  25534. BABYLON.RefractionTexture = RefractionTexture;
  25535. })(BABYLON || (BABYLON = {}));
  25536. //# sourceMappingURL=babylon.refractionTexture.js.map
  25537. var BABYLON;
  25538. (function (BABYLON) {
  25539. var DynamicTexture = (function (_super) {
  25540. __extends(DynamicTexture, _super);
  25541. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  25542. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25543. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  25544. _this.name = name;
  25545. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25546. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25547. _this._generateMipMaps = generateMipMaps;
  25548. if (options.getContext) {
  25549. _this._canvas = options;
  25550. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  25551. }
  25552. else {
  25553. _this._canvas = document.createElement("canvas");
  25554. if (options.width) {
  25555. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  25556. }
  25557. else {
  25558. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  25559. }
  25560. }
  25561. var textureSize = _this.getSize();
  25562. _this._canvas.width = textureSize.width;
  25563. _this._canvas.height = textureSize.height;
  25564. _this._context = _this._canvas.getContext("2d");
  25565. return _this;
  25566. }
  25567. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  25568. get: function () {
  25569. return true;
  25570. },
  25571. enumerable: true,
  25572. configurable: true
  25573. });
  25574. DynamicTexture.prototype.scale = function (ratio) {
  25575. var textureSize = this.getSize();
  25576. textureSize.width *= ratio;
  25577. textureSize.height *= ratio;
  25578. this._canvas.width = textureSize.width;
  25579. this._canvas.height = textureSize.height;
  25580. this.releaseInternalTexture();
  25581. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  25582. };
  25583. DynamicTexture.prototype.getContext = function () {
  25584. return this._context;
  25585. };
  25586. DynamicTexture.prototype.clear = function () {
  25587. var size = this.getSize();
  25588. this._context.fillRect(0, 0, size.width, size.height);
  25589. };
  25590. DynamicTexture.prototype.update = function (invertY) {
  25591. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  25592. };
  25593. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  25594. if (update === void 0) { update = true; }
  25595. var size = this.getSize();
  25596. if (clearColor) {
  25597. this._context.fillStyle = clearColor;
  25598. this._context.fillRect(0, 0, size.width, size.height);
  25599. }
  25600. this._context.font = font;
  25601. if (x === null) {
  25602. var textSize = this._context.measureText(text);
  25603. x = (size.width - textSize.width) / 2;
  25604. }
  25605. this._context.fillStyle = color;
  25606. this._context.fillText(text, x, y);
  25607. if (update) {
  25608. this.update(invertY);
  25609. }
  25610. };
  25611. DynamicTexture.prototype.clone = function () {
  25612. var textureSize = this.getSize();
  25613. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  25614. // Base texture
  25615. newTexture.hasAlpha = this.hasAlpha;
  25616. newTexture.level = this.level;
  25617. // Dynamic Texture
  25618. newTexture.wrapU = this.wrapU;
  25619. newTexture.wrapV = this.wrapV;
  25620. return newTexture;
  25621. };
  25622. return DynamicTexture;
  25623. }(BABYLON.Texture));
  25624. BABYLON.DynamicTexture = DynamicTexture;
  25625. })(BABYLON || (BABYLON = {}));
  25626. //# sourceMappingURL=babylon.dynamicTexture.js.map
  25627. var BABYLON;
  25628. (function (BABYLON) {
  25629. var VideoTexture = (function (_super) {
  25630. __extends(VideoTexture, _super);
  25631. /**
  25632. * Creates a video texture.
  25633. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  25634. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  25635. * @param {BABYLON.Scene} scene is obviously the current scene.
  25636. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  25637. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  25638. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  25639. */
  25640. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  25641. if (generateMipMaps === void 0) { generateMipMaps = false; }
  25642. if (invertY === void 0) { invertY = false; }
  25643. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  25644. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  25645. _this._autoLaunch = true;
  25646. var urls;
  25647. _this.name = name;
  25648. if (urlsOrVideo instanceof HTMLVideoElement) {
  25649. _this.video = urlsOrVideo;
  25650. }
  25651. else {
  25652. urls = urlsOrVideo;
  25653. _this.video = document.createElement("video");
  25654. _this.video.autoplay = false;
  25655. _this.video.loop = true;
  25656. }
  25657. _this._generateMipMaps = generateMipMaps;
  25658. _this._samplingMode = samplingMode;
  25659. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  25660. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  25661. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  25662. }
  25663. else {
  25664. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25665. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  25666. _this._generateMipMaps = false;
  25667. }
  25668. if (urls) {
  25669. _this.video.addEventListener("canplaythrough", function () {
  25670. _this._createTexture();
  25671. });
  25672. urls.forEach(function (url) {
  25673. var source = document.createElement("source");
  25674. source.src = url;
  25675. _this.video.appendChild(source);
  25676. });
  25677. }
  25678. else {
  25679. _this._createTexture();
  25680. }
  25681. _this._lastUpdate = BABYLON.Tools.Now;
  25682. return _this;
  25683. }
  25684. VideoTexture.prototype._createTexture = function () {
  25685. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  25686. this._texture.isReady = true;
  25687. };
  25688. VideoTexture.prototype.update = function () {
  25689. if (this._autoLaunch) {
  25690. this._autoLaunch = false;
  25691. this.video.play();
  25692. }
  25693. var now = BABYLON.Tools.Now;
  25694. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  25695. return false;
  25696. }
  25697. this._lastUpdate = now;
  25698. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  25699. return true;
  25700. };
  25701. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  25702. var video = document.createElement("video");
  25703. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  25704. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  25705. if (navigator.getUserMedia) {
  25706. navigator.getUserMedia({
  25707. video: {
  25708. width: {
  25709. min: (constraints && constraints.minWidth) || 256,
  25710. max: (constraints && constraints.maxWidth) || 640
  25711. },
  25712. height: {
  25713. min: (constraints && constraints.minHeight) || 256,
  25714. max: (constraints && constraints.maxHeight) || 480
  25715. }
  25716. }
  25717. }, function (stream) {
  25718. if (video.mozSrcObject !== undefined) {
  25719. video.mozSrcObject = stream;
  25720. }
  25721. else {
  25722. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  25723. }
  25724. video.play();
  25725. if (onReady) {
  25726. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  25727. }
  25728. }, function (e) {
  25729. BABYLON.Tools.Error(e.name);
  25730. });
  25731. }
  25732. };
  25733. return VideoTexture;
  25734. }(BABYLON.Texture));
  25735. BABYLON.VideoTexture = VideoTexture;
  25736. })(BABYLON || (BABYLON = {}));
  25737. //# sourceMappingURL=babylon.videoTexture.js.map
  25738. var BABYLON;
  25739. (function (BABYLON) {
  25740. var CustomProceduralTexture = (function (_super) {
  25741. __extends(CustomProceduralTexture, _super);
  25742. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  25743. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  25744. _this._animate = true;
  25745. _this._time = 0;
  25746. _this._texturePath = texturePath;
  25747. //Try to load json
  25748. _this.loadJson(texturePath);
  25749. _this.refreshRate = 1;
  25750. return _this;
  25751. }
  25752. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  25753. var _this = this;
  25754. var that = this;
  25755. function noConfigFile() {
  25756. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  25757. try {
  25758. that.setFragment(that._texturePath);
  25759. }
  25760. catch (ex) {
  25761. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  25762. }
  25763. }
  25764. var configFileUrl = jsonUrl + "/config.json";
  25765. var xhr = new XMLHttpRequest();
  25766. xhr.open("GET", configFileUrl, true);
  25767. xhr.addEventListener("load", function () {
  25768. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  25769. try {
  25770. _this._config = JSON.parse(xhr.response);
  25771. _this.updateShaderUniforms();
  25772. _this.updateTextures();
  25773. _this.setFragment(_this._texturePath + "/custom");
  25774. _this._animate = _this._config.animate;
  25775. _this.refreshRate = _this._config.refreshrate;
  25776. }
  25777. catch (ex) {
  25778. noConfigFile();
  25779. }
  25780. }
  25781. else {
  25782. noConfigFile();
  25783. }
  25784. }, false);
  25785. xhr.addEventListener("error", function () {
  25786. noConfigFile();
  25787. }, false);
  25788. try {
  25789. xhr.send();
  25790. }
  25791. catch (ex) {
  25792. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  25793. }
  25794. };
  25795. CustomProceduralTexture.prototype.isReady = function () {
  25796. if (!_super.prototype.isReady.call(this)) {
  25797. return false;
  25798. }
  25799. for (var name in this._textures) {
  25800. var texture = this._textures[name];
  25801. if (!texture.isReady()) {
  25802. return false;
  25803. }
  25804. }
  25805. return true;
  25806. };
  25807. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  25808. if (this._animate) {
  25809. this._time += this.getScene().getAnimationRatio() * 0.03;
  25810. this.updateShaderUniforms();
  25811. }
  25812. _super.prototype.render.call(this, useCameraPostProcess);
  25813. };
  25814. CustomProceduralTexture.prototype.updateTextures = function () {
  25815. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  25816. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  25817. }
  25818. };
  25819. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  25820. if (this._config) {
  25821. for (var j = 0; j < this._config.uniforms.length; j++) {
  25822. var uniform = this._config.uniforms[j];
  25823. switch (uniform.type) {
  25824. case "float":
  25825. this.setFloat(uniform.name, uniform.value);
  25826. break;
  25827. case "color3":
  25828. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  25829. break;
  25830. case "color4":
  25831. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  25832. break;
  25833. case "vector2":
  25834. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  25835. break;
  25836. case "vector3":
  25837. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  25838. break;
  25839. }
  25840. }
  25841. }
  25842. this.setFloat("time", this._time);
  25843. };
  25844. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  25845. get: function () {
  25846. return this._animate;
  25847. },
  25848. set: function (value) {
  25849. this._animate = value;
  25850. },
  25851. enumerable: true,
  25852. configurable: true
  25853. });
  25854. return CustomProceduralTexture;
  25855. }(BABYLON.ProceduralTexture));
  25856. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  25857. })(BABYLON || (BABYLON = {}));
  25858. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  25859. var BABYLON;
  25860. (function (BABYLON) {
  25861. var EffectFallbacks = (function () {
  25862. function EffectFallbacks() {
  25863. this._defines = {};
  25864. this._currentRank = 32;
  25865. this._maxRank = -1;
  25866. }
  25867. EffectFallbacks.prototype.addFallback = function (rank, define) {
  25868. if (!this._defines[rank]) {
  25869. if (rank < this._currentRank) {
  25870. this._currentRank = rank;
  25871. }
  25872. if (rank > this._maxRank) {
  25873. this._maxRank = rank;
  25874. }
  25875. this._defines[rank] = new Array();
  25876. }
  25877. this._defines[rank].push(define);
  25878. };
  25879. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25880. this._meshRank = rank;
  25881. this._mesh = mesh;
  25882. if (rank > this._maxRank) {
  25883. this._maxRank = rank;
  25884. }
  25885. };
  25886. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25887. get: function () {
  25888. return this._currentRank <= this._maxRank;
  25889. },
  25890. enumerable: true,
  25891. configurable: true
  25892. });
  25893. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25894. var currentFallbacks = this._defines[this._currentRank];
  25895. for (var index = 0; index < currentFallbacks.length; index++) {
  25896. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25897. }
  25898. if (this._mesh && this._currentRank === this._meshRank) {
  25899. this._mesh.computeBonesUsingShaders = false;
  25900. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25901. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25902. }
  25903. this._currentRank++;
  25904. return currentDefines;
  25905. };
  25906. return EffectFallbacks;
  25907. }());
  25908. BABYLON.EffectFallbacks = EffectFallbacks;
  25909. var Effect = (function () {
  25910. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25911. var _this = this;
  25912. this.uniqueId = 0;
  25913. this._isReady = false;
  25914. this._compilationError = "";
  25915. this._valueCache = {};
  25916. this._engine = engine;
  25917. this.name = baseName;
  25918. this.defines = defines;
  25919. this._uniformsNames = uniformsNames.concat(samplers);
  25920. this._samplers = samplers;
  25921. this._attributesNames = attributesNames;
  25922. this.onError = onError;
  25923. this.onCompiled = onCompiled;
  25924. this._indexParameters = indexParameters;
  25925. this.uniqueId = Effect._uniqueIdSeed++;
  25926. var vertexSource;
  25927. var fragmentSource;
  25928. if (baseName.vertexElement) {
  25929. vertexSource = document.getElementById(baseName.vertexElement);
  25930. if (!vertexSource) {
  25931. vertexSource = baseName.vertexElement;
  25932. }
  25933. }
  25934. else {
  25935. vertexSource = baseName.vertex || baseName;
  25936. }
  25937. if (baseName.fragmentElement) {
  25938. fragmentSource = document.getElementById(baseName.fragmentElement);
  25939. if (!fragmentSource) {
  25940. fragmentSource = baseName.fragmentElement;
  25941. }
  25942. }
  25943. else {
  25944. fragmentSource = baseName.fragment || baseName;
  25945. }
  25946. this._loadVertexShader(vertexSource, function (vertexCode) {
  25947. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25948. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  25949. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25950. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25951. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  25952. _this._prepareEffect(migratedVertexCode, migratedFragmentCode, attributesNames, defines, fallbacks);
  25953. });
  25954. });
  25955. });
  25956. });
  25957. });
  25958. });
  25959. }
  25960. Object.defineProperty(Effect.prototype, "key", {
  25961. get: function () {
  25962. return this._key;
  25963. },
  25964. enumerable: true,
  25965. configurable: true
  25966. });
  25967. // Properties
  25968. Effect.prototype.isReady = function () {
  25969. return this._isReady;
  25970. };
  25971. Effect.prototype.getProgram = function () {
  25972. return this._program;
  25973. };
  25974. Effect.prototype.getAttributesNames = function () {
  25975. return this._attributesNames;
  25976. };
  25977. Effect.prototype.getAttributeLocation = function (index) {
  25978. return this._attributes[index];
  25979. };
  25980. Effect.prototype.getAttributeLocationByName = function (name) {
  25981. var index = this._attributesNames.indexOf(name);
  25982. return this._attributes[index];
  25983. };
  25984. Effect.prototype.getAttributesCount = function () {
  25985. return this._attributes.length;
  25986. };
  25987. Effect.prototype.getUniformIndex = function (uniformName) {
  25988. return this._uniformsNames.indexOf(uniformName);
  25989. };
  25990. Effect.prototype.getUniform = function (uniformName) {
  25991. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25992. };
  25993. Effect.prototype.getSamplers = function () {
  25994. return this._samplers;
  25995. };
  25996. Effect.prototype.getCompilationError = function () {
  25997. return this._compilationError;
  25998. };
  25999. Effect.prototype.getVertexShaderSource = function () {
  26000. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  26001. };
  26002. Effect.prototype.getFragmentShaderSource = function () {
  26003. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  26004. };
  26005. // Methods
  26006. Effect.prototype._loadVertexShader = function (vertex, callback) {
  26007. // DOM element ?
  26008. if (vertex instanceof HTMLElement) {
  26009. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  26010. callback(vertexCode);
  26011. return;
  26012. }
  26013. // Base64 encoded ?
  26014. if (vertex.substr(0, 7) === "base64:") {
  26015. var vertexBinary = window.atob(vertex.substr(7));
  26016. callback(vertexBinary);
  26017. return;
  26018. }
  26019. // Is in local store ?
  26020. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  26021. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  26022. return;
  26023. }
  26024. var vertexShaderUrl;
  26025. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  26026. vertexShaderUrl = vertex;
  26027. }
  26028. else {
  26029. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  26030. }
  26031. // Vertex shader
  26032. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  26033. };
  26034. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  26035. // DOM element ?
  26036. if (fragment instanceof HTMLElement) {
  26037. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  26038. callback(fragmentCode);
  26039. return;
  26040. }
  26041. // Base64 encoded ?
  26042. if (fragment.substr(0, 7) === "base64:") {
  26043. var fragmentBinary = window.atob(fragment.substr(7));
  26044. callback(fragmentBinary);
  26045. return;
  26046. }
  26047. // Is in local store ?
  26048. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  26049. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  26050. return;
  26051. }
  26052. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  26053. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  26054. return;
  26055. }
  26056. var fragmentShaderUrl;
  26057. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  26058. fragmentShaderUrl = fragment;
  26059. }
  26060. else {
  26061. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  26062. }
  26063. // Fragment shader
  26064. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  26065. };
  26066. Effect.prototype._dumpShadersName = function () {
  26067. if (this.name.vertexElement) {
  26068. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  26069. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  26070. }
  26071. else if (this.name.vertex) {
  26072. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  26073. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  26074. }
  26075. else {
  26076. BABYLON.Tools.Error("Vertex shader:" + this.name);
  26077. BABYLON.Tools.Error("Fragment shader:" + this.name);
  26078. }
  26079. };
  26080. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  26081. var preparedSourceCode = this._processPrecision(sourceCode);
  26082. if (this._engine.webGLVersion == 1) {
  26083. callback(preparedSourceCode);
  26084. return;
  26085. }
  26086. // Already converted
  26087. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  26088. callback(preparedSourceCode);
  26089. return;
  26090. }
  26091. // Remove extensions
  26092. // #extension GL_OES_standard_derivatives : enable
  26093. // #extension GL_EXT_shader_texture_lod : enable
  26094. // #extension GL_EXT_frag_depth : enable
  26095. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  26096. var result = preparedSourceCode.replace(regex, "");
  26097. // Migrate to GLSL v300
  26098. result = result.replace(/varying\s/g, isFragment ? "in " : "out ");
  26099. result = result.replace(/attribute[ \t]/g, "in ");
  26100. result = result.replace(/[ \t]attribute/g, " in");
  26101. if (isFragment) {
  26102. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  26103. result = result.replace(/texture2D\(/g, "texture(");
  26104. result = result.replace(/textureCube\(/g, "texture(");
  26105. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  26106. result = result.replace(/gl_FragColor/g, "glFragColor");
  26107. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  26108. }
  26109. callback(result);
  26110. };
  26111. Effect.prototype._processIncludes = function (sourceCode, callback) {
  26112. var _this = this;
  26113. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  26114. var match = regex.exec(sourceCode);
  26115. var returnValue = new String(sourceCode);
  26116. while (match != null) {
  26117. var includeFile = match[1];
  26118. if (Effect.IncludesShadersStore[includeFile]) {
  26119. // Substitution
  26120. var includeContent = Effect.IncludesShadersStore[includeFile];
  26121. if (match[2]) {
  26122. var splits = match[3].split(",");
  26123. for (var index = 0; index < splits.length; index += 2) {
  26124. var source = new RegExp(splits[index], "g");
  26125. var dest = splits[index + 1];
  26126. includeContent = includeContent.replace(source, dest);
  26127. }
  26128. }
  26129. if (match[4]) {
  26130. var indexString = match[5];
  26131. if (indexString.indexOf("..") !== -1) {
  26132. var indexSplits = indexString.split("..");
  26133. var minIndex = parseInt(indexSplits[0]);
  26134. var maxIndex = parseInt(indexSplits[1]);
  26135. var sourceIncludeContent = includeContent.slice(0);
  26136. includeContent = "";
  26137. if (isNaN(maxIndex)) {
  26138. maxIndex = this._indexParameters[indexSplits[1]];
  26139. }
  26140. for (var i = minIndex; i <= maxIndex; i++) {
  26141. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  26142. }
  26143. }
  26144. else {
  26145. includeContent = includeContent.replace(/\{X\}/g, indexString);
  26146. }
  26147. }
  26148. // Replace
  26149. returnValue = returnValue.replace(match[0], includeContent);
  26150. }
  26151. else {
  26152. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  26153. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  26154. Effect.IncludesShadersStore[includeFile] = fileContent;
  26155. _this._processIncludes(returnValue, callback);
  26156. });
  26157. return;
  26158. }
  26159. match = regex.exec(sourceCode);
  26160. }
  26161. callback(returnValue);
  26162. };
  26163. Effect.prototype._processPrecision = function (source) {
  26164. if (source.indexOf("precision highp float") === -1) {
  26165. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26166. source = "precision mediump float;\n" + source;
  26167. }
  26168. else {
  26169. source = "precision highp float;\n" + source;
  26170. }
  26171. }
  26172. else {
  26173. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  26174. source = source.replace("precision highp float", "precision mediump float");
  26175. }
  26176. }
  26177. return source;
  26178. };
  26179. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  26180. try {
  26181. var engine = this._engine;
  26182. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  26183. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  26184. this._attributes = engine.getAttributes(this._program, attributesNames);
  26185. var index;
  26186. for (index = 0; index < this._samplers.length; index++) {
  26187. var sampler = this.getUniform(this._samplers[index]);
  26188. if (sampler == null) {
  26189. this._samplers.splice(index, 1);
  26190. index--;
  26191. }
  26192. }
  26193. engine.bindSamplers(this);
  26194. this._compilationError = "";
  26195. this._isReady = true;
  26196. if (this.onCompiled) {
  26197. this.onCompiled(this);
  26198. }
  26199. }
  26200. catch (e) {
  26201. this._compilationError = e.message;
  26202. // Let's go through fallbacks then
  26203. BABYLON.Tools.Error("Unable to compile effect: ");
  26204. BABYLON.Tools.Error("Defines: " + defines);
  26205. BABYLON.Tools.Error("Error: " + this._compilationError);
  26206. this._dumpShadersName();
  26207. if (fallbacks && fallbacks.isMoreFallbacks) {
  26208. BABYLON.Tools.Error("Trying next fallback.");
  26209. defines = fallbacks.reduce(defines);
  26210. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  26211. }
  26212. else {
  26213. if (this.onError) {
  26214. this.onError(this, this._compilationError);
  26215. }
  26216. }
  26217. }
  26218. };
  26219. Object.defineProperty(Effect.prototype, "isSupported", {
  26220. get: function () {
  26221. return this._compilationError === "";
  26222. },
  26223. enumerable: true,
  26224. configurable: true
  26225. });
  26226. Effect.prototype._bindTexture = function (channel, texture) {
  26227. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  26228. };
  26229. Effect.prototype.setTexture = function (channel, texture) {
  26230. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  26231. };
  26232. Effect.prototype.setTextureArray = function (channel, textures) {
  26233. if (this._samplers.indexOf(channel + "Ex") === -1) {
  26234. var initialPos = this._samplers.indexOf(channel);
  26235. for (var index = 1; index < textures.length; index++) {
  26236. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  26237. }
  26238. }
  26239. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  26240. };
  26241. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  26242. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  26243. };
  26244. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  26245. var changed = false;
  26246. var cache = this._valueCache[uniformName];
  26247. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  26248. changed = true;
  26249. cache = new BABYLON.Matrix();
  26250. }
  26251. var tm = cache.m;
  26252. var om = matrix.m;
  26253. for (var index = 0; index < 16; index++) {
  26254. if (tm[index] !== om[index]) {
  26255. tm[index] = om[index];
  26256. changed = true;
  26257. }
  26258. }
  26259. this._valueCache[uniformName] = cache;
  26260. return changed;
  26261. };
  26262. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  26263. var cache = this._valueCache[uniformName];
  26264. if (!cache) {
  26265. cache = [x, y];
  26266. this._valueCache[uniformName] = cache;
  26267. return true;
  26268. }
  26269. var changed = false;
  26270. if (cache[0] !== x) {
  26271. cache[0] = x;
  26272. changed = true;
  26273. }
  26274. if (cache[1] !== y) {
  26275. cache[1] = y;
  26276. changed = true;
  26277. }
  26278. return changed;
  26279. };
  26280. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  26281. var cache = this._valueCache[uniformName];
  26282. if (!cache) {
  26283. cache = [x, y, z];
  26284. this._valueCache[uniformName] = cache;
  26285. return true;
  26286. }
  26287. var changed = false;
  26288. if (cache[0] !== x) {
  26289. cache[0] = x;
  26290. changed = true;
  26291. }
  26292. if (cache[1] !== y) {
  26293. cache[1] = y;
  26294. changed = true;
  26295. }
  26296. if (cache[2] !== z) {
  26297. cache[2] = z;
  26298. changed = true;
  26299. }
  26300. return changed;
  26301. };
  26302. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  26303. var cache = this._valueCache[uniformName];
  26304. if (!cache) {
  26305. cache = [x, y, z, w];
  26306. this._valueCache[uniformName] = cache;
  26307. return true;
  26308. }
  26309. var changed = false;
  26310. if (cache[0] !== x) {
  26311. cache[0] = x;
  26312. changed = true;
  26313. }
  26314. if (cache[1] !== y) {
  26315. cache[1] = y;
  26316. changed = true;
  26317. }
  26318. if (cache[2] !== z) {
  26319. cache[2] = z;
  26320. changed = true;
  26321. }
  26322. if (cache[3] !== w) {
  26323. cache[3] = w;
  26324. changed = true;
  26325. }
  26326. return changed;
  26327. };
  26328. Effect.prototype.setIntArray = function (uniformName, array) {
  26329. this._valueCache[uniformName] = null;
  26330. this._engine.setIntArray(this.getUniform(uniformName), array);
  26331. return this;
  26332. };
  26333. Effect.prototype.setIntArray2 = function (uniformName, array) {
  26334. this._valueCache[uniformName] = null;
  26335. this._engine.setIntArray2(this.getUniform(uniformName), array);
  26336. return this;
  26337. };
  26338. Effect.prototype.setIntArray3 = function (uniformName, array) {
  26339. this._valueCache[uniformName] = null;
  26340. this._engine.setIntArray3(this.getUniform(uniformName), array);
  26341. return this;
  26342. };
  26343. Effect.prototype.setIntArray4 = function (uniformName, array) {
  26344. this._valueCache[uniformName] = null;
  26345. this._engine.setIntArray4(this.getUniform(uniformName), array);
  26346. return this;
  26347. };
  26348. Effect.prototype.setFloatArray = function (uniformName, array) {
  26349. this._valueCache[uniformName] = null;
  26350. this._engine.setFloatArray(this.getUniform(uniformName), array);
  26351. return this;
  26352. };
  26353. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  26354. this._valueCache[uniformName] = null;
  26355. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  26356. return this;
  26357. };
  26358. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  26359. this._valueCache[uniformName] = null;
  26360. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  26361. return this;
  26362. };
  26363. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  26364. this._valueCache[uniformName] = null;
  26365. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  26366. return this;
  26367. };
  26368. Effect.prototype.setArray = function (uniformName, array) {
  26369. this._valueCache[uniformName] = null;
  26370. this._engine.setArray(this.getUniform(uniformName), array);
  26371. return this;
  26372. };
  26373. Effect.prototype.setArray2 = function (uniformName, array) {
  26374. this._valueCache[uniformName] = null;
  26375. this._engine.setArray2(this.getUniform(uniformName), array);
  26376. return this;
  26377. };
  26378. Effect.prototype.setArray3 = function (uniformName, array) {
  26379. this._valueCache[uniformName] = null;
  26380. this._engine.setArray3(this.getUniform(uniformName), array);
  26381. return this;
  26382. };
  26383. Effect.prototype.setArray4 = function (uniformName, array) {
  26384. this._valueCache[uniformName] = null;
  26385. this._engine.setArray4(this.getUniform(uniformName), array);
  26386. return this;
  26387. };
  26388. Effect.prototype.setMatrices = function (uniformName, matrices) {
  26389. this._valueCache[uniformName] = null;
  26390. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  26391. return this;
  26392. };
  26393. Effect.prototype.setMatrix = function (uniformName, matrix) {
  26394. if (this._cacheMatrix(uniformName, matrix)) {
  26395. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  26396. }
  26397. return this;
  26398. };
  26399. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  26400. this._valueCache[uniformName] = null;
  26401. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  26402. return this;
  26403. };
  26404. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  26405. this._valueCache[uniformName] = null;
  26406. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  26407. return this;
  26408. };
  26409. Effect.prototype.setFloat = function (uniformName, value) {
  26410. var cache = this._valueCache[uniformName];
  26411. if (cache !== undefined && cache === value)
  26412. return this;
  26413. this._valueCache[uniformName] = value;
  26414. this._engine.setFloat(this.getUniform(uniformName), value);
  26415. return this;
  26416. };
  26417. Effect.prototype.setBool = function (uniformName, bool) {
  26418. var cache = this._valueCache[uniformName];
  26419. if (cache !== undefined && cache === bool)
  26420. return this;
  26421. this._valueCache[uniformName] = bool;
  26422. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  26423. return this;
  26424. };
  26425. Effect.prototype.setVector2 = function (uniformName, vector2) {
  26426. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  26427. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  26428. }
  26429. return this;
  26430. };
  26431. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  26432. if (this._cacheFloat2(uniformName, x, y)) {
  26433. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  26434. }
  26435. return this;
  26436. };
  26437. Effect.prototype.setVector3 = function (uniformName, vector3) {
  26438. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  26439. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  26440. }
  26441. return this;
  26442. };
  26443. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  26444. if (this._cacheFloat3(uniformName, x, y, z)) {
  26445. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  26446. }
  26447. return this;
  26448. };
  26449. Effect.prototype.setVector4 = function (uniformName, vector4) {
  26450. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  26451. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  26452. }
  26453. return this;
  26454. };
  26455. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  26456. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  26457. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  26458. }
  26459. return this;
  26460. };
  26461. Effect.prototype.setColor3 = function (uniformName, color3) {
  26462. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  26463. this._engine.setColor3(this.getUniform(uniformName), color3);
  26464. }
  26465. return this;
  26466. };
  26467. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  26468. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  26469. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  26470. }
  26471. return this;
  26472. };
  26473. Effect.prototype._recombineShader = function (node) {
  26474. if (node.define) {
  26475. if (node.condition) {
  26476. var defineIndex = this.defines.indexOf("#define " + node.define);
  26477. if (defineIndex === -1) {
  26478. return null;
  26479. }
  26480. var nextComma = this.defines.indexOf("\n", defineIndex);
  26481. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  26482. var condition = defineValue + node.condition;
  26483. if (!eval(condition)) {
  26484. return null;
  26485. }
  26486. }
  26487. else if (node.ndef) {
  26488. if (this.defines.indexOf("#define " + node.define) !== -1) {
  26489. return null;
  26490. }
  26491. }
  26492. else if (this.defines.indexOf("#define " + node.define) === -1) {
  26493. return null;
  26494. }
  26495. }
  26496. var result = "";
  26497. for (var index = 0; index < node.children.length; index++) {
  26498. var line = node.children[index];
  26499. if (line.children) {
  26500. var combined = this._recombineShader(line);
  26501. if (combined !== null) {
  26502. result += combined + "\r\n";
  26503. }
  26504. continue;
  26505. }
  26506. if (line.length > 0) {
  26507. result += line + "\r\n";
  26508. }
  26509. }
  26510. return result;
  26511. };
  26512. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  26513. var root = {
  26514. children: []
  26515. };
  26516. var currentNode = root;
  26517. var lines = shaderString.split("\n");
  26518. for (var index = 0; index < lines.length; index++) {
  26519. var line = lines[index].trim();
  26520. // #ifdef
  26521. var pos = line.indexOf("#ifdef ");
  26522. if (pos !== -1) {
  26523. var define = line.substr(pos + 7);
  26524. var newNode = {
  26525. condition: null,
  26526. ndef: false,
  26527. define: define,
  26528. children: [],
  26529. parent: currentNode
  26530. };
  26531. currentNode.children.push(newNode);
  26532. currentNode = newNode;
  26533. continue;
  26534. }
  26535. // #ifndef
  26536. var pos = line.indexOf("#ifndef ");
  26537. if (pos !== -1) {
  26538. var define = line.substr(pos + 8);
  26539. newNode = {
  26540. condition: null,
  26541. define: define,
  26542. ndef: true,
  26543. children: [],
  26544. parent: currentNode
  26545. };
  26546. currentNode.children.push(newNode);
  26547. currentNode = newNode;
  26548. continue;
  26549. }
  26550. // #if
  26551. var pos = line.indexOf("#if ");
  26552. if (pos !== -1) {
  26553. var define = line.substr(pos + 4).trim();
  26554. var conditionPos = define.indexOf(" ");
  26555. newNode = {
  26556. condition: define.substr(conditionPos + 1),
  26557. define: define.substr(0, conditionPos),
  26558. ndef: false,
  26559. children: [],
  26560. parent: currentNode
  26561. };
  26562. currentNode.children.push(newNode);
  26563. currentNode = newNode;
  26564. continue;
  26565. }
  26566. // #endif
  26567. pos = line.indexOf("#endif");
  26568. if (pos !== -1) {
  26569. currentNode = currentNode.parent;
  26570. continue;
  26571. }
  26572. currentNode.children.push(line);
  26573. }
  26574. // Recombine
  26575. return this._recombineShader(root);
  26576. };
  26577. return Effect;
  26578. }());
  26579. Effect._uniqueIdSeed = 0;
  26580. // Statics
  26581. Effect.ShadersStore = {};
  26582. Effect.IncludesShadersStore = {};
  26583. BABYLON.Effect = Effect;
  26584. })(BABYLON || (BABYLON = {}));
  26585. //# sourceMappingURL=babylon.effect.js.map
  26586. var BABYLON;
  26587. (function (BABYLON) {
  26588. var MaterialHelper = (function () {
  26589. function MaterialHelper() {
  26590. }
  26591. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  26592. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26593. var lightIndex = 0;
  26594. var needNormals = false;
  26595. var needRebuild = false;
  26596. var needShadows = false;
  26597. var lightmapMode = false;
  26598. for (var index = 0; index < scene.lights.length; index++) {
  26599. var light = scene.lights[index];
  26600. if (!light.isEnabled()) {
  26601. continue;
  26602. }
  26603. // Excluded check
  26604. if (light._excludedMeshesIds.length > 0) {
  26605. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  26606. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  26607. if (excludedMesh) {
  26608. light.excludedMeshes.push(excludedMesh);
  26609. }
  26610. }
  26611. light._excludedMeshesIds = [];
  26612. }
  26613. // Included check
  26614. if (light._includedOnlyMeshesIds.length > 0) {
  26615. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  26616. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  26617. if (includedOnlyMesh) {
  26618. light.includedOnlyMeshes.push(includedOnlyMesh);
  26619. }
  26620. }
  26621. light._includedOnlyMeshesIds = [];
  26622. }
  26623. if (!light.canAffectMesh(mesh)) {
  26624. continue;
  26625. }
  26626. needNormals = true;
  26627. if (defines["LIGHT" + lightIndex] === undefined) {
  26628. needRebuild = true;
  26629. }
  26630. defines["LIGHT" + lightIndex] = true;
  26631. var type;
  26632. if (light instanceof BABYLON.SpotLight) {
  26633. type = "SPOTLIGHT" + lightIndex;
  26634. }
  26635. else if (light instanceof BABYLON.HemisphericLight) {
  26636. type = "HEMILIGHT" + lightIndex;
  26637. }
  26638. else if (light instanceof BABYLON.PointLight) {
  26639. type = "POINTLIGHT" + lightIndex;
  26640. }
  26641. else {
  26642. type = "DIRLIGHT" + lightIndex;
  26643. }
  26644. if (defines[type] === undefined) {
  26645. needRebuild = true;
  26646. }
  26647. defines[type] = true;
  26648. // Specular
  26649. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  26650. defines["SPECULARTERM"] = true;
  26651. }
  26652. // Shadows
  26653. if (scene.shadowsEnabled) {
  26654. var shadowGenerator = light.getShadowGenerator();
  26655. if (mesh && mesh.receiveShadows && shadowGenerator) {
  26656. if (defines["SHADOW" + lightIndex] === undefined) {
  26657. needRebuild = true;
  26658. }
  26659. defines["SHADOW" + lightIndex] = true;
  26660. defines["SHADOWS"] = true;
  26661. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  26662. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  26663. needRebuild = true;
  26664. }
  26665. defines["SHADOWVSM" + lightIndex] = true;
  26666. }
  26667. if (shadowGenerator.usePoissonSampling) {
  26668. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  26669. needRebuild = true;
  26670. }
  26671. defines["SHADOWPCF" + lightIndex] = true;
  26672. }
  26673. needShadows = true;
  26674. }
  26675. }
  26676. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  26677. lightmapMode = true;
  26678. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  26679. needRebuild = true;
  26680. }
  26681. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  26682. needRebuild = true;
  26683. }
  26684. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  26685. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  26686. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  26687. }
  26688. }
  26689. lightIndex++;
  26690. if (lightIndex === maxSimultaneousLights)
  26691. break;
  26692. }
  26693. var caps = scene.getEngine().getCaps();
  26694. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  26695. if (defines["SHADOWFULLFLOAT"] === undefined) {
  26696. needRebuild = true;
  26697. }
  26698. defines["SHADOWFULLFLOAT"] = true;
  26699. }
  26700. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  26701. needRebuild = true;
  26702. }
  26703. if (lightmapMode) {
  26704. defines["LIGHTMAPEXCLUDED"] = true;
  26705. }
  26706. if (needRebuild) {
  26707. defines.rebuild();
  26708. }
  26709. return needNormals;
  26710. };
  26711. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  26712. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26713. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26714. if (!defines["LIGHT" + lightIndex]) {
  26715. break;
  26716. }
  26717. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  26718. samplersList.push("shadowSampler" + lightIndex);
  26719. }
  26720. };
  26721. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  26722. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26723. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  26724. if (!defines["LIGHT" + lightIndex]) {
  26725. break;
  26726. }
  26727. if (lightIndex > 0) {
  26728. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  26729. }
  26730. if (defines["SHADOW" + lightIndex]) {
  26731. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  26732. }
  26733. if (defines["SHADOWPCF" + lightIndex]) {
  26734. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  26735. }
  26736. if (defines["SHADOWVSM" + lightIndex]) {
  26737. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  26738. }
  26739. }
  26740. };
  26741. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  26742. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  26743. fallbacks.addCPUSkinningFallback(0, mesh);
  26744. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  26745. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  26746. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  26747. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  26748. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  26749. }
  26750. }
  26751. };
  26752. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  26753. if (defines["INSTANCES"]) {
  26754. attribs.push("world0");
  26755. attribs.push("world1");
  26756. attribs.push("world2");
  26757. attribs.push("world3");
  26758. }
  26759. };
  26760. // Bindings
  26761. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  26762. var shadowGenerator = light.getShadowGenerator();
  26763. if (mesh.receiveShadows && shadowGenerator) {
  26764. if (!light.needCube()) {
  26765. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  26766. }
  26767. else {
  26768. if (!depthValuesAlreadySet) {
  26769. depthValuesAlreadySet = true;
  26770. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  26771. }
  26772. }
  26773. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  26774. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  26775. }
  26776. return depthValuesAlreadySet;
  26777. };
  26778. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  26779. if (light instanceof BABYLON.PointLight) {
  26780. // Point Light
  26781. light.transferToEffect(effect, "vLightData" + lightIndex);
  26782. }
  26783. else if (light instanceof BABYLON.DirectionalLight) {
  26784. // Directional Light
  26785. light.transferToEffect(effect, "vLightData" + lightIndex);
  26786. }
  26787. else if (light instanceof BABYLON.SpotLight) {
  26788. // Spot Light
  26789. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  26790. }
  26791. else if (light instanceof BABYLON.HemisphericLight) {
  26792. // Hemispheric Light
  26793. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  26794. }
  26795. };
  26796. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  26797. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  26798. var lightIndex = 0;
  26799. var depthValuesAlreadySet = false;
  26800. for (var index = 0; index < scene.lights.length; index++) {
  26801. var light = scene.lights[index];
  26802. if (!light.isEnabled()) {
  26803. continue;
  26804. }
  26805. if (!light.canAffectMesh(mesh)) {
  26806. continue;
  26807. }
  26808. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  26809. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  26810. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  26811. if (defines["SPECULARTERM"]) {
  26812. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  26813. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  26814. }
  26815. // Shadows
  26816. if (scene.shadowsEnabled) {
  26817. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  26818. }
  26819. lightIndex++;
  26820. if (lightIndex === maxSimultaneousLights)
  26821. break;
  26822. }
  26823. };
  26824. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  26825. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  26826. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  26827. effect.setColor3("vFogColor", scene.fogColor);
  26828. }
  26829. };
  26830. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  26831. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  26832. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  26833. if (matrices) {
  26834. effect.setMatrices("mBones", matrices);
  26835. }
  26836. }
  26837. };
  26838. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  26839. if (defines["LOGARITHMICDEPTH"]) {
  26840. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  26841. }
  26842. };
  26843. MaterialHelper.BindClipPlane = function (effect, scene) {
  26844. if (scene.clipPlane) {
  26845. var clipPlane = scene.clipPlane;
  26846. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  26847. }
  26848. };
  26849. return MaterialHelper;
  26850. }());
  26851. BABYLON.MaterialHelper = MaterialHelper;
  26852. })(BABYLON || (BABYLON = {}));
  26853. //# sourceMappingURL=babylon.materialHelper.js.map
  26854. var BABYLON;
  26855. (function (BABYLON) {
  26856. var FresnelParameters = (function () {
  26857. function FresnelParameters() {
  26858. this.isEnabled = true;
  26859. this.leftColor = BABYLON.Color3.White();
  26860. this.rightColor = BABYLON.Color3.Black();
  26861. this.bias = 0;
  26862. this.power = 1;
  26863. }
  26864. FresnelParameters.prototype.clone = function () {
  26865. var newFresnelParameters = new FresnelParameters();
  26866. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  26867. return newFresnelParameters;
  26868. };
  26869. FresnelParameters.prototype.serialize = function () {
  26870. var serializationObject = {};
  26871. serializationObject.isEnabled = this.isEnabled;
  26872. serializationObject.leftColor = this.leftColor;
  26873. serializationObject.rightColor = this.rightColor;
  26874. serializationObject.bias = this.bias;
  26875. serializationObject.power = this.power;
  26876. return serializationObject;
  26877. };
  26878. FresnelParameters.Parse = function (parsedFresnelParameters) {
  26879. var fresnelParameters = new FresnelParameters();
  26880. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  26881. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  26882. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  26883. fresnelParameters.bias = parsedFresnelParameters.bias;
  26884. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  26885. return fresnelParameters;
  26886. };
  26887. return FresnelParameters;
  26888. }());
  26889. BABYLON.FresnelParameters = FresnelParameters;
  26890. })(BABYLON || (BABYLON = {}));
  26891. //# sourceMappingURL=babylon.fresnelParameters.js.map
  26892. var BABYLON;
  26893. (function (BABYLON) {
  26894. var MaterialDefines = (function () {
  26895. function MaterialDefines() {
  26896. }
  26897. MaterialDefines.prototype.rebuild = function () {
  26898. if (this._keys) {
  26899. delete this._keys;
  26900. }
  26901. this._keys = Object.keys(this);
  26902. };
  26903. MaterialDefines.prototype.isEqual = function (other) {
  26904. if (this._keys.length !== other._keys.length) {
  26905. return false;
  26906. }
  26907. for (var index = 0; index < this._keys.length; index++) {
  26908. var prop = this._keys[index];
  26909. if (this[prop] !== other[prop]) {
  26910. return false;
  26911. }
  26912. }
  26913. return true;
  26914. };
  26915. MaterialDefines.prototype.cloneTo = function (other) {
  26916. if (this._keys.length !== other._keys.length) {
  26917. other._keys = this._keys.slice(0);
  26918. }
  26919. for (var index = 0; index < this._keys.length; index++) {
  26920. var prop = this._keys[index];
  26921. other[prop] = this[prop];
  26922. }
  26923. };
  26924. MaterialDefines.prototype.reset = function () {
  26925. for (var index = 0; index < this._keys.length; index++) {
  26926. var prop = this._keys[index];
  26927. if (typeof (this[prop]) === "number") {
  26928. this[prop] = 0;
  26929. }
  26930. else {
  26931. this[prop] = false;
  26932. }
  26933. }
  26934. };
  26935. MaterialDefines.prototype.toString = function () {
  26936. var result = "";
  26937. for (var index = 0; index < this._keys.length; index++) {
  26938. var prop = this._keys[index];
  26939. if (typeof (this[prop]) === "number") {
  26940. result += "#define " + prop + " " + this[prop] + "\n";
  26941. }
  26942. else if (this[prop]) {
  26943. result += "#define " + prop + "\n";
  26944. }
  26945. }
  26946. return result;
  26947. };
  26948. return MaterialDefines;
  26949. }());
  26950. BABYLON.MaterialDefines = MaterialDefines;
  26951. var Material = (function () {
  26952. function Material(name, scene, doNotAdd) {
  26953. this.checkReadyOnEveryCall = false;
  26954. this.checkReadyOnlyOnce = false;
  26955. this.state = "";
  26956. this.alpha = 1.0;
  26957. this.backFaceCulling = true;
  26958. this.doNotSerialize = false;
  26959. /**
  26960. * An event triggered when the material is disposed.
  26961. * @type {BABYLON.Observable}
  26962. */
  26963. this.onDisposeObservable = new BABYLON.Observable();
  26964. /**
  26965. * An event triggered when the material is bound.
  26966. * @type {BABYLON.Observable}
  26967. */
  26968. this.onBindObservable = new BABYLON.Observable();
  26969. /**
  26970. * An event triggered when the material is unbound.
  26971. * @type {BABYLON.Observable}
  26972. */
  26973. this.onUnBindObservable = new BABYLON.Observable();
  26974. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26975. this.disableDepthWrite = false;
  26976. this.fogEnabled = true;
  26977. this.pointSize = 1.0;
  26978. this.zOffset = 0;
  26979. this._wasPreviouslyReady = false;
  26980. this._fillMode = Material.TriangleFillMode;
  26981. this.name = name;
  26982. this.id = name;
  26983. this._scene = scene;
  26984. if (scene.useRightHandedSystem) {
  26985. this.sideOrientation = Material.ClockWiseSideOrientation;
  26986. }
  26987. else {
  26988. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26989. }
  26990. if (!doNotAdd) {
  26991. scene.materials.push(this);
  26992. }
  26993. }
  26994. Object.defineProperty(Material, "TriangleFillMode", {
  26995. get: function () {
  26996. return Material._TriangleFillMode;
  26997. },
  26998. enumerable: true,
  26999. configurable: true
  27000. });
  27001. Object.defineProperty(Material, "WireFrameFillMode", {
  27002. get: function () {
  27003. return Material._WireFrameFillMode;
  27004. },
  27005. enumerable: true,
  27006. configurable: true
  27007. });
  27008. Object.defineProperty(Material, "PointFillMode", {
  27009. get: function () {
  27010. return Material._PointFillMode;
  27011. },
  27012. enumerable: true,
  27013. configurable: true
  27014. });
  27015. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  27016. get: function () {
  27017. return Material._ClockWiseSideOrientation;
  27018. },
  27019. enumerable: true,
  27020. configurable: true
  27021. });
  27022. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  27023. get: function () {
  27024. return Material._CounterClockWiseSideOrientation;
  27025. },
  27026. enumerable: true,
  27027. configurable: true
  27028. });
  27029. Object.defineProperty(Material.prototype, "onDispose", {
  27030. set: function (callback) {
  27031. if (this._onDisposeObserver) {
  27032. this.onDisposeObservable.remove(this._onDisposeObserver);
  27033. }
  27034. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  27035. },
  27036. enumerable: true,
  27037. configurable: true
  27038. });
  27039. Object.defineProperty(Material.prototype, "onBind", {
  27040. set: function (callback) {
  27041. if (this._onBindObserver) {
  27042. this.onBindObservable.remove(this._onBindObserver);
  27043. }
  27044. this._onBindObserver = this.onBindObservable.add(callback);
  27045. },
  27046. enumerable: true,
  27047. configurable: true
  27048. });
  27049. Object.defineProperty(Material.prototype, "wireframe", {
  27050. get: function () {
  27051. return this._fillMode === Material.WireFrameFillMode;
  27052. },
  27053. set: function (value) {
  27054. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  27055. },
  27056. enumerable: true,
  27057. configurable: true
  27058. });
  27059. Object.defineProperty(Material.prototype, "pointsCloud", {
  27060. get: function () {
  27061. return this._fillMode === Material.PointFillMode;
  27062. },
  27063. set: function (value) {
  27064. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  27065. },
  27066. enumerable: true,
  27067. configurable: true
  27068. });
  27069. Object.defineProperty(Material.prototype, "fillMode", {
  27070. get: function () {
  27071. return this._fillMode;
  27072. },
  27073. set: function (value) {
  27074. this._fillMode = value;
  27075. },
  27076. enumerable: true,
  27077. configurable: true
  27078. });
  27079. /**
  27080. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  27081. * subclasses should override adding information pertainent to themselves
  27082. */
  27083. Material.prototype.toString = function (fullDetails) {
  27084. var ret = "Name: " + this.name;
  27085. if (fullDetails) {
  27086. }
  27087. return ret;
  27088. };
  27089. Material.prototype.getClassName = function () {
  27090. return "Material";
  27091. };
  27092. Object.defineProperty(Material.prototype, "isFrozen", {
  27093. get: function () {
  27094. return this.checkReadyOnlyOnce;
  27095. },
  27096. enumerable: true,
  27097. configurable: true
  27098. });
  27099. Material.prototype.freeze = function () {
  27100. this.checkReadyOnlyOnce = true;
  27101. };
  27102. Material.prototype.unfreeze = function () {
  27103. this.checkReadyOnlyOnce = false;
  27104. };
  27105. Material.prototype.isReady = function (mesh, useInstances) {
  27106. return true;
  27107. };
  27108. Material.prototype.getEffect = function () {
  27109. return this._effect;
  27110. };
  27111. Material.prototype.getScene = function () {
  27112. return this._scene;
  27113. };
  27114. Material.prototype.needAlphaBlending = function () {
  27115. return (this.alpha < 1.0);
  27116. };
  27117. Material.prototype.needAlphaTesting = function () {
  27118. return false;
  27119. };
  27120. Material.prototype.getAlphaTestTexture = function () {
  27121. return null;
  27122. };
  27123. Material.prototype.markDirty = function () {
  27124. this._wasPreviouslyReady = false;
  27125. };
  27126. Material.prototype._preBind = function () {
  27127. var engine = this._scene.getEngine();
  27128. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  27129. engine.enableEffect(this._effect);
  27130. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  27131. };
  27132. Material.prototype.bind = function (world, mesh) {
  27133. this._scene._cachedMaterial = this;
  27134. this.onBindObservable.notifyObservers(mesh);
  27135. if (this.disableDepthWrite) {
  27136. var engine = this._scene.getEngine();
  27137. this._cachedDepthWriteState = engine.getDepthWrite();
  27138. engine.setDepthWrite(false);
  27139. }
  27140. };
  27141. Material.prototype.bindOnlyWorldMatrix = function (world) {
  27142. };
  27143. Material.prototype.unbind = function () {
  27144. this.onUnBindObservable.notifyObservers(this);
  27145. if (this.disableDepthWrite) {
  27146. var engine = this._scene.getEngine();
  27147. engine.setDepthWrite(this._cachedDepthWriteState);
  27148. }
  27149. };
  27150. Material.prototype.clone = function (name) {
  27151. return null;
  27152. };
  27153. Material.prototype.getBindedMeshes = function () {
  27154. var result = new Array();
  27155. for (var index = 0; index < this._scene.meshes.length; index++) {
  27156. var mesh = this._scene.meshes[index];
  27157. if (mesh.material === this) {
  27158. result.push(mesh);
  27159. }
  27160. }
  27161. return result;
  27162. };
  27163. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27164. // Animations
  27165. this.getScene().stopAnimation(this);
  27166. // Remove from scene
  27167. var index = this._scene.materials.indexOf(this);
  27168. if (index >= 0) {
  27169. this._scene.materials.splice(index, 1);
  27170. }
  27171. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  27172. if (forceDisposeEffect && this._effect) {
  27173. this._scene.getEngine()._releaseEffect(this._effect);
  27174. this._effect = null;
  27175. }
  27176. // Remove from meshes
  27177. for (index = 0; index < this._scene.meshes.length; index++) {
  27178. var mesh = this._scene.meshes[index];
  27179. if (mesh.material === this) {
  27180. mesh.material = null;
  27181. }
  27182. }
  27183. // Callback
  27184. this.onDisposeObservable.notifyObservers(this);
  27185. this.onDisposeObservable.clear();
  27186. this.onBindObservable.clear();
  27187. this.onUnBindObservable.clear();
  27188. };
  27189. Material.prototype.serialize = function () {
  27190. return BABYLON.SerializationHelper.Serialize(this);
  27191. };
  27192. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  27193. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  27194. multiMaterial.id = parsedMultiMaterial.id;
  27195. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  27196. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  27197. var subMatId = parsedMultiMaterial.materials[matIndex];
  27198. if (subMatId) {
  27199. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  27200. }
  27201. else {
  27202. multiMaterial.subMaterials.push(null);
  27203. }
  27204. }
  27205. return multiMaterial;
  27206. };
  27207. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  27208. if (!parsedMaterial.customType) {
  27209. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  27210. }
  27211. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  27212. return materialType.Parse(parsedMaterial, scene, rootUrl);
  27213. ;
  27214. };
  27215. return Material;
  27216. }());
  27217. Material._TriangleFillMode = 0;
  27218. Material._WireFrameFillMode = 1;
  27219. Material._PointFillMode = 2;
  27220. Material._ClockWiseSideOrientation = 0;
  27221. Material._CounterClockWiseSideOrientation = 1;
  27222. __decorate([
  27223. BABYLON.serialize()
  27224. ], Material.prototype, "id", void 0);
  27225. __decorate([
  27226. BABYLON.serialize()
  27227. ], Material.prototype, "name", void 0);
  27228. __decorate([
  27229. BABYLON.serialize()
  27230. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  27231. __decorate([
  27232. BABYLON.serialize()
  27233. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  27234. __decorate([
  27235. BABYLON.serialize()
  27236. ], Material.prototype, "state", void 0);
  27237. __decorate([
  27238. BABYLON.serialize()
  27239. ], Material.prototype, "alpha", void 0);
  27240. __decorate([
  27241. BABYLON.serialize()
  27242. ], Material.prototype, "backFaceCulling", void 0);
  27243. __decorate([
  27244. BABYLON.serialize()
  27245. ], Material.prototype, "sideOrientation", void 0);
  27246. __decorate([
  27247. BABYLON.serialize()
  27248. ], Material.prototype, "alphaMode", void 0);
  27249. __decorate([
  27250. BABYLON.serialize()
  27251. ], Material.prototype, "disableDepthWrite", void 0);
  27252. __decorate([
  27253. BABYLON.serialize()
  27254. ], Material.prototype, "fogEnabled", void 0);
  27255. __decorate([
  27256. BABYLON.serialize()
  27257. ], Material.prototype, "pointSize", void 0);
  27258. __decorate([
  27259. BABYLON.serialize()
  27260. ], Material.prototype, "zOffset", void 0);
  27261. __decorate([
  27262. BABYLON.serialize()
  27263. ], Material.prototype, "wireframe", null);
  27264. __decorate([
  27265. BABYLON.serialize()
  27266. ], Material.prototype, "pointsCloud", null);
  27267. __decorate([
  27268. BABYLON.serialize()
  27269. ], Material.prototype, "fillMode", null);
  27270. BABYLON.Material = Material;
  27271. })(BABYLON || (BABYLON = {}));
  27272. //# sourceMappingURL=babylon.material.js.map
  27273. var BABYLON;
  27274. (function (BABYLON) {
  27275. var StandardMaterialDefines = (function (_super) {
  27276. __extends(StandardMaterialDefines, _super);
  27277. function StandardMaterialDefines() {
  27278. var _this = _super.call(this) || this;
  27279. _this.DIFFUSE = false;
  27280. _this.AMBIENT = false;
  27281. _this.OPACITY = false;
  27282. _this.OPACITYRGB = false;
  27283. _this.REFLECTION = false;
  27284. _this.EMISSIVE = false;
  27285. _this.SPECULAR = false;
  27286. _this.BUMP = false;
  27287. _this.PARALLAX = false;
  27288. _this.PARALLAXOCCLUSION = false;
  27289. _this.SPECULAROVERALPHA = false;
  27290. _this.CLIPPLANE = false;
  27291. _this.ALPHATEST = false;
  27292. _this.ALPHAFROMDIFFUSE = false;
  27293. _this.POINTSIZE = false;
  27294. _this.FOG = false;
  27295. _this.SPECULARTERM = false;
  27296. _this.DIFFUSEFRESNEL = false;
  27297. _this.OPACITYFRESNEL = false;
  27298. _this.REFLECTIONFRESNEL = false;
  27299. _this.REFRACTIONFRESNEL = false;
  27300. _this.EMISSIVEFRESNEL = false;
  27301. _this.FRESNEL = false;
  27302. _this.NORMAL = false;
  27303. _this.UV1 = false;
  27304. _this.UV2 = false;
  27305. _this.VERTEXCOLOR = false;
  27306. _this.VERTEXALPHA = false;
  27307. _this.NUM_BONE_INFLUENCERS = 0;
  27308. _this.BonesPerMesh = 0;
  27309. _this.INSTANCES = false;
  27310. _this.GLOSSINESS = false;
  27311. _this.ROUGHNESS = false;
  27312. _this.EMISSIVEASILLUMINATION = false;
  27313. _this.LINKEMISSIVEWITHDIFFUSE = false;
  27314. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  27315. _this.LIGHTMAP = false;
  27316. _this.USELIGHTMAPASSHADOWMAP = false;
  27317. _this.REFLECTIONMAP_3D = false;
  27318. _this.REFLECTIONMAP_SPHERICAL = false;
  27319. _this.REFLECTIONMAP_PLANAR = false;
  27320. _this.REFLECTIONMAP_CUBIC = false;
  27321. _this.REFLECTIONMAP_PROJECTION = false;
  27322. _this.REFLECTIONMAP_SKYBOX = false;
  27323. _this.REFLECTIONMAP_EXPLICIT = false;
  27324. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  27325. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  27326. _this.INVERTCUBICMAP = false;
  27327. _this.LOGARITHMICDEPTH = false;
  27328. _this.REFRACTION = false;
  27329. _this.REFRACTIONMAP_3D = false;
  27330. _this.REFLECTIONOVERALPHA = false;
  27331. _this.INVERTNORMALMAPX = false;
  27332. _this.INVERTNORMALMAPY = false;
  27333. _this.SHADOWFULLFLOAT = false;
  27334. _this.CAMERACOLORGRADING = false;
  27335. _this.CAMERACOLORCURVES = false;
  27336. _this.rebuild();
  27337. return _this;
  27338. }
  27339. return StandardMaterialDefines;
  27340. }(BABYLON.MaterialDefines));
  27341. var StandardMaterial = (function (_super) {
  27342. __extends(StandardMaterial, _super);
  27343. function StandardMaterial(name, scene) {
  27344. var _this = _super.call(this, name, scene) || this;
  27345. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  27346. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  27347. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  27348. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  27349. _this.specularPower = 64;
  27350. _this.useAlphaFromDiffuseTexture = false;
  27351. _this.useEmissiveAsIllumination = false;
  27352. _this.linkEmissiveWithDiffuse = false;
  27353. _this.useReflectionFresnelFromSpecular = false;
  27354. _this.useSpecularOverAlpha = false;
  27355. _this.useReflectionOverAlpha = false;
  27356. _this.disableLighting = false;
  27357. _this.useParallax = false;
  27358. _this.useParallaxOcclusion = false;
  27359. _this.parallaxScaleBias = 0.05;
  27360. _this.roughness = 0;
  27361. _this.indexOfRefraction = 0.98;
  27362. _this.invertRefractionY = true;
  27363. _this.useLightmapAsShadowmap = false;
  27364. _this.useGlossinessFromSpecularMapAlpha = false;
  27365. _this.maxSimultaneousLights = 4;
  27366. /**
  27367. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  27368. */
  27369. _this.invertNormalMapX = false;
  27370. /**
  27371. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  27372. */
  27373. _this.invertNormalMapY = false;
  27374. /**
  27375. * Color Grading 2D Lookup Texture.
  27376. * This allows special effects like sepia, black and white to sixties rendering style.
  27377. */
  27378. _this.cameraColorGradingTexture = null;
  27379. /**
  27380. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  27381. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  27382. * 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;
  27383. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  27384. */
  27385. _this.cameraColorCurves = null;
  27386. _this._renderTargets = new BABYLON.SmartArray(16);
  27387. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  27388. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  27389. _this._defines = new StandardMaterialDefines();
  27390. _this._cachedDefines = new StandardMaterialDefines();
  27391. _this._cachedDefines.BonesPerMesh = -1;
  27392. _this.getRenderTargetTextures = function () {
  27393. _this._renderTargets.reset();
  27394. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  27395. _this._renderTargets.push(_this.reflectionTexture);
  27396. }
  27397. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  27398. _this._renderTargets.push(_this.refractionTexture);
  27399. }
  27400. return _this._renderTargets;
  27401. };
  27402. return _this;
  27403. }
  27404. StandardMaterial.prototype.getClassName = function () {
  27405. return "StandardMaterial";
  27406. };
  27407. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  27408. get: function () {
  27409. return this._useLogarithmicDepth;
  27410. },
  27411. set: function (value) {
  27412. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  27413. },
  27414. enumerable: true,
  27415. configurable: true
  27416. });
  27417. StandardMaterial.prototype.needAlphaBlending = function () {
  27418. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  27419. };
  27420. StandardMaterial.prototype.needAlphaTesting = function () {
  27421. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  27422. };
  27423. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  27424. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  27425. };
  27426. StandardMaterial.prototype.getAlphaTestTexture = function () {
  27427. return this.diffuseTexture;
  27428. };
  27429. // Methods
  27430. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  27431. if (!mesh) {
  27432. return true;
  27433. }
  27434. if (this._defines.INSTANCES !== useInstances) {
  27435. return false;
  27436. }
  27437. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  27438. return true;
  27439. }
  27440. return false;
  27441. };
  27442. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  27443. if (this.isFrozen) {
  27444. if (this._wasPreviouslyReady) {
  27445. return true;
  27446. }
  27447. }
  27448. var scene = this.getScene();
  27449. var engine = scene.getEngine();
  27450. var needUVs = false;
  27451. var needNormals = false;
  27452. this._defines.reset();
  27453. // Lights
  27454. if (scene.lightsEnabled && !this.disableLighting) {
  27455. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  27456. }
  27457. if (!this.checkReadyOnEveryCall) {
  27458. if (this._renderId === scene.getRenderId()) {
  27459. if (this._checkCache(scene, mesh, useInstances)) {
  27460. return true;
  27461. }
  27462. }
  27463. }
  27464. // Textures
  27465. if (scene.texturesEnabled) {
  27466. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27467. if (!this.diffuseTexture.isReady()) {
  27468. return false;
  27469. }
  27470. else {
  27471. needUVs = true;
  27472. this._defines.DIFFUSE = true;
  27473. }
  27474. }
  27475. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27476. if (!this.ambientTexture.isReady()) {
  27477. return false;
  27478. }
  27479. else {
  27480. needUVs = true;
  27481. this._defines.AMBIENT = true;
  27482. }
  27483. }
  27484. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27485. if (!this.opacityTexture.isReady()) {
  27486. return false;
  27487. }
  27488. else {
  27489. needUVs = true;
  27490. this._defines.OPACITY = true;
  27491. if (this.opacityTexture.getAlphaFromRGB) {
  27492. this._defines.OPACITYRGB = true;
  27493. }
  27494. }
  27495. }
  27496. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27497. if (!this.reflectionTexture.isReady()) {
  27498. return false;
  27499. }
  27500. else {
  27501. needNormals = true;
  27502. this._defines.REFLECTION = true;
  27503. if (this.roughness > 0) {
  27504. this._defines.ROUGHNESS = true;
  27505. }
  27506. if (this.useReflectionOverAlpha) {
  27507. this._defines.REFLECTIONOVERALPHA = true;
  27508. }
  27509. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  27510. this._defines.INVERTCUBICMAP = true;
  27511. }
  27512. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  27513. switch (this.reflectionTexture.coordinatesMode) {
  27514. case BABYLON.Texture.CUBIC_MODE:
  27515. case BABYLON.Texture.INVCUBIC_MODE:
  27516. this._defines.REFLECTIONMAP_CUBIC = true;
  27517. break;
  27518. case BABYLON.Texture.EXPLICIT_MODE:
  27519. this._defines.REFLECTIONMAP_EXPLICIT = true;
  27520. break;
  27521. case BABYLON.Texture.PLANAR_MODE:
  27522. this._defines.REFLECTIONMAP_PLANAR = true;
  27523. break;
  27524. case BABYLON.Texture.PROJECTION_MODE:
  27525. this._defines.REFLECTIONMAP_PROJECTION = true;
  27526. break;
  27527. case BABYLON.Texture.SKYBOX_MODE:
  27528. this._defines.REFLECTIONMAP_SKYBOX = true;
  27529. break;
  27530. case BABYLON.Texture.SPHERICAL_MODE:
  27531. this._defines.REFLECTIONMAP_SPHERICAL = true;
  27532. break;
  27533. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  27534. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  27535. break;
  27536. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  27537. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  27538. break;
  27539. }
  27540. }
  27541. }
  27542. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27543. if (!this.emissiveTexture.isReady()) {
  27544. return false;
  27545. }
  27546. else {
  27547. needUVs = true;
  27548. this._defines.EMISSIVE = true;
  27549. }
  27550. }
  27551. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27552. if (!this.lightmapTexture.isReady()) {
  27553. return false;
  27554. }
  27555. else {
  27556. needUVs = true;
  27557. this._defines.LIGHTMAP = true;
  27558. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  27559. }
  27560. }
  27561. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27562. if (!this.specularTexture.isReady()) {
  27563. return false;
  27564. }
  27565. else {
  27566. needUVs = true;
  27567. this._defines.SPECULAR = true;
  27568. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  27569. }
  27570. }
  27571. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  27572. if (!this.bumpTexture.isReady()) {
  27573. return false;
  27574. }
  27575. else {
  27576. needUVs = true;
  27577. this._defines.BUMP = true;
  27578. if (this.useParallax) {
  27579. this._defines.PARALLAX = true;
  27580. if (this.useParallaxOcclusion) {
  27581. this._defines.PARALLAXOCCLUSION = true;
  27582. }
  27583. }
  27584. if (this.invertNormalMapX) {
  27585. this._defines.INVERTNORMALMAPX = true;
  27586. }
  27587. if (this.invertNormalMapY) {
  27588. this._defines.INVERTNORMALMAPY = true;
  27589. }
  27590. if (scene._mirroredCameraPosition) {
  27591. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  27592. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  27593. }
  27594. }
  27595. }
  27596. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27597. if (!this.refractionTexture.isReady()) {
  27598. return false;
  27599. }
  27600. else {
  27601. needUVs = true;
  27602. this._defines.REFRACTION = true;
  27603. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  27604. }
  27605. }
  27606. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27607. if (!this.cameraColorGradingTexture.isReady()) {
  27608. return false;
  27609. }
  27610. else {
  27611. this._defines.CAMERACOLORGRADING = true;
  27612. }
  27613. }
  27614. }
  27615. // Effect
  27616. if (scene.clipPlane) {
  27617. this._defines.CLIPPLANE = true;
  27618. }
  27619. if (engine.getAlphaTesting()) {
  27620. this._defines.ALPHATEST = true;
  27621. }
  27622. if (this._shouldUseAlphaFromDiffuseTexture()) {
  27623. this._defines.ALPHAFROMDIFFUSE = true;
  27624. }
  27625. if (this.useEmissiveAsIllumination) {
  27626. this._defines.EMISSIVEASILLUMINATION = true;
  27627. }
  27628. if (this.linkEmissiveWithDiffuse) {
  27629. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  27630. }
  27631. if (this.useLogarithmicDepth) {
  27632. this._defines.LOGARITHMICDEPTH = true;
  27633. }
  27634. if (this.cameraColorCurves) {
  27635. this._defines.CAMERACOLORCURVES = true;
  27636. }
  27637. // Point size
  27638. if (this.pointsCloud || scene.forcePointsCloud) {
  27639. this._defines.POINTSIZE = true;
  27640. }
  27641. // Fog
  27642. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  27643. this._defines.FOG = true;
  27644. }
  27645. if (StandardMaterial.FresnelEnabled) {
  27646. // Fresnel
  27647. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  27648. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  27649. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  27650. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  27651. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27652. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27653. this._defines.DIFFUSEFRESNEL = true;
  27654. }
  27655. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27656. this._defines.OPACITYFRESNEL = true;
  27657. }
  27658. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27659. this._defines.REFLECTIONFRESNEL = true;
  27660. if (this.useReflectionFresnelFromSpecular) {
  27661. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  27662. }
  27663. }
  27664. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27665. this._defines.REFRACTIONFRESNEL = true;
  27666. }
  27667. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27668. this._defines.EMISSIVEFRESNEL = true;
  27669. }
  27670. needNormals = true;
  27671. this._defines.FRESNEL = true;
  27672. }
  27673. }
  27674. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  27675. this._defines.SPECULAROVERALPHA = true;
  27676. }
  27677. // Attribs
  27678. if (mesh) {
  27679. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  27680. this._defines.NORMAL = true;
  27681. }
  27682. if (needUVs) {
  27683. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  27684. this._defines.UV1 = true;
  27685. }
  27686. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  27687. this._defines.UV2 = true;
  27688. }
  27689. }
  27690. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  27691. this._defines.VERTEXCOLOR = true;
  27692. if (mesh.hasVertexAlpha) {
  27693. this._defines.VERTEXALPHA = true;
  27694. }
  27695. }
  27696. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  27697. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  27698. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  27699. }
  27700. // Instances
  27701. if (useInstances) {
  27702. this._defines.INSTANCES = true;
  27703. }
  27704. }
  27705. // Get correct effect
  27706. if (!this._defines.isEqual(this._cachedDefines)) {
  27707. this._defines.cloneTo(this._cachedDefines);
  27708. scene.resetCachedMaterial();
  27709. // Fallbacks
  27710. var fallbacks = new BABYLON.EffectFallbacks();
  27711. if (this._defines.REFLECTION) {
  27712. fallbacks.addFallback(0, "REFLECTION");
  27713. }
  27714. if (this._defines.SPECULAR) {
  27715. fallbacks.addFallback(0, "SPECULAR");
  27716. }
  27717. if (this._defines.BUMP) {
  27718. fallbacks.addFallback(0, "BUMP");
  27719. }
  27720. if (this._defines.PARALLAX) {
  27721. fallbacks.addFallback(1, "PARALLAX");
  27722. }
  27723. if (this._defines.PARALLAXOCCLUSION) {
  27724. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  27725. }
  27726. if (this._defines.SPECULAROVERALPHA) {
  27727. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  27728. }
  27729. if (this._defines.FOG) {
  27730. fallbacks.addFallback(1, "FOG");
  27731. }
  27732. if (this._defines.POINTSIZE) {
  27733. fallbacks.addFallback(0, "POINTSIZE");
  27734. }
  27735. if (this._defines.LOGARITHMICDEPTH) {
  27736. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  27737. }
  27738. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  27739. if (this._defines.SPECULARTERM) {
  27740. fallbacks.addFallback(0, "SPECULARTERM");
  27741. }
  27742. if (this._defines.DIFFUSEFRESNEL) {
  27743. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  27744. }
  27745. if (this._defines.OPACITYFRESNEL) {
  27746. fallbacks.addFallback(2, "OPACITYFRESNEL");
  27747. }
  27748. if (this._defines.REFLECTIONFRESNEL) {
  27749. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  27750. }
  27751. if (this._defines.EMISSIVEFRESNEL) {
  27752. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  27753. }
  27754. if (this._defines.FRESNEL) {
  27755. fallbacks.addFallback(4, "FRESNEL");
  27756. }
  27757. //Attributes
  27758. var attribs = [BABYLON.VertexBuffer.PositionKind];
  27759. if (this._defines.NORMAL) {
  27760. attribs.push(BABYLON.VertexBuffer.NormalKind);
  27761. }
  27762. if (this._defines.UV1) {
  27763. attribs.push(BABYLON.VertexBuffer.UVKind);
  27764. }
  27765. if (this._defines.UV2) {
  27766. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  27767. }
  27768. if (this._defines.VERTEXCOLOR) {
  27769. attribs.push(BABYLON.VertexBuffer.ColorKind);
  27770. }
  27771. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  27772. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  27773. var shaderName = "default";
  27774. var join = this._defines.toString();
  27775. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  27776. "vFogInfos", "vFogColor", "pointSize",
  27777. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  27778. "mBones",
  27779. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  27780. "depthValues",
  27781. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  27782. "logarithmicDepthConstant"
  27783. ];
  27784. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  27785. if (this._defines.CAMERACOLORCURVES) {
  27786. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  27787. }
  27788. if (this._defines.CAMERACOLORGRADING) {
  27789. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  27790. }
  27791. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  27792. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  27793. }
  27794. if (!this._effect.isReady()) {
  27795. return false;
  27796. }
  27797. this._renderId = scene.getRenderId();
  27798. this._wasPreviouslyReady = true;
  27799. if (mesh) {
  27800. if (!mesh._materialDefines) {
  27801. mesh._materialDefines = new StandardMaterialDefines();
  27802. }
  27803. this._defines.cloneTo(mesh._materialDefines);
  27804. }
  27805. return true;
  27806. };
  27807. StandardMaterial.prototype.unbind = function () {
  27808. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  27809. this._effect.setTexture("reflection2DSampler", null);
  27810. }
  27811. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  27812. this._effect.setTexture("refraction2DSampler", null);
  27813. }
  27814. _super.prototype.unbind.call(this);
  27815. };
  27816. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  27817. this._effect.setMatrix("world", world);
  27818. };
  27819. StandardMaterial.prototype.bind = function (world, mesh) {
  27820. var scene = this.getScene();
  27821. // Matrices
  27822. this.bindOnlyWorldMatrix(world);
  27823. // Bones
  27824. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  27825. if (scene.getCachedMaterial() !== this) {
  27826. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  27827. if (StandardMaterial.FresnelEnabled) {
  27828. // Fresnel
  27829. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  27830. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  27831. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  27832. }
  27833. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  27834. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  27835. }
  27836. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  27837. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  27838. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  27839. }
  27840. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  27841. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  27842. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  27843. }
  27844. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  27845. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  27846. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  27847. }
  27848. }
  27849. // Textures
  27850. if (scene.texturesEnabled) {
  27851. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  27852. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  27853. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  27854. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  27855. }
  27856. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  27857. this._effect.setTexture("ambientSampler", this.ambientTexture);
  27858. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  27859. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  27860. }
  27861. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  27862. this._effect.setTexture("opacitySampler", this.opacityTexture);
  27863. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  27864. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  27865. }
  27866. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  27867. if (this.reflectionTexture.isCube) {
  27868. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  27869. }
  27870. else {
  27871. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  27872. }
  27873. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  27874. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  27875. }
  27876. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  27877. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  27878. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  27879. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  27880. }
  27881. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  27882. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  27883. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  27884. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  27885. }
  27886. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  27887. this._effect.setTexture("specularSampler", this.specularTexture);
  27888. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  27889. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  27890. }
  27891. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  27892. this._effect.setTexture("bumpSampler", this.bumpTexture);
  27893. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  27894. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  27895. }
  27896. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  27897. var depth = 1.0;
  27898. if (this.refractionTexture.isCube) {
  27899. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  27900. }
  27901. else {
  27902. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  27903. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  27904. if (this.refractionTexture.depth) {
  27905. depth = this.refractionTexture.depth;
  27906. }
  27907. }
  27908. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  27909. }
  27910. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  27911. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  27912. }
  27913. }
  27914. // Clip plane
  27915. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  27916. // Point size
  27917. if (this.pointsCloud) {
  27918. this._effect.setFloat("pointSize", this.pointSize);
  27919. }
  27920. // Colors
  27921. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27922. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27923. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27924. if (this._defines.SPECULARTERM) {
  27925. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  27926. }
  27927. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  27928. }
  27929. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  27930. // Diffuse
  27931. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27932. // Lights
  27933. if (scene.lightsEnabled && !this.disableLighting) {
  27934. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  27935. }
  27936. // View
  27937. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  27938. this._effect.setMatrix("view", scene.getViewMatrix());
  27939. }
  27940. // Fog
  27941. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  27942. // Log. depth
  27943. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  27944. // Color Curves
  27945. if (this.cameraColorCurves) {
  27946. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  27947. }
  27948. }
  27949. _super.prototype.bind.call(this, world, mesh);
  27950. };
  27951. StandardMaterial.prototype.getAnimatables = function () {
  27952. var results = [];
  27953. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  27954. results.push(this.diffuseTexture);
  27955. }
  27956. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  27957. results.push(this.ambientTexture);
  27958. }
  27959. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  27960. results.push(this.opacityTexture);
  27961. }
  27962. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  27963. results.push(this.reflectionTexture);
  27964. }
  27965. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  27966. results.push(this.emissiveTexture);
  27967. }
  27968. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  27969. results.push(this.specularTexture);
  27970. }
  27971. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  27972. results.push(this.bumpTexture);
  27973. }
  27974. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  27975. results.push(this.lightmapTexture);
  27976. }
  27977. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  27978. results.push(this.refractionTexture);
  27979. }
  27980. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  27981. results.push(this.cameraColorGradingTexture);
  27982. }
  27983. return results;
  27984. };
  27985. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27986. if (forceDisposeTextures) {
  27987. if (this.diffuseTexture) {
  27988. this.diffuseTexture.dispose();
  27989. }
  27990. if (this.ambientTexture) {
  27991. this.ambientTexture.dispose();
  27992. }
  27993. if (this.opacityTexture) {
  27994. this.opacityTexture.dispose();
  27995. }
  27996. if (this.reflectionTexture) {
  27997. this.reflectionTexture.dispose();
  27998. }
  27999. if (this.emissiveTexture) {
  28000. this.emissiveTexture.dispose();
  28001. }
  28002. if (this.specularTexture) {
  28003. this.specularTexture.dispose();
  28004. }
  28005. if (this.bumpTexture) {
  28006. this.bumpTexture.dispose();
  28007. }
  28008. if (this.lightmapTexture) {
  28009. this.lightmapTexture.dispose();
  28010. }
  28011. if (this.refractionTexture) {
  28012. this.refractionTexture.dispose();
  28013. }
  28014. if (this.cameraColorGradingTexture) {
  28015. this.cameraColorGradingTexture.dispose();
  28016. }
  28017. }
  28018. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  28019. };
  28020. StandardMaterial.prototype.clone = function (name) {
  28021. var _this = this;
  28022. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  28023. };
  28024. StandardMaterial.prototype.serialize = function () {
  28025. return BABYLON.SerializationHelper.Serialize(this);
  28026. };
  28027. // Statics
  28028. StandardMaterial.Parse = function (source, scene, rootUrl) {
  28029. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  28030. };
  28031. return StandardMaterial;
  28032. }(BABYLON.Material));
  28033. // Flags used to enable or disable a type of texture for all Standard Materials
  28034. StandardMaterial.DiffuseTextureEnabled = true;
  28035. StandardMaterial.AmbientTextureEnabled = true;
  28036. StandardMaterial.OpacityTextureEnabled = true;
  28037. StandardMaterial.ReflectionTextureEnabled = true;
  28038. StandardMaterial.EmissiveTextureEnabled = true;
  28039. StandardMaterial.SpecularTextureEnabled = true;
  28040. StandardMaterial.BumpTextureEnabled = true;
  28041. StandardMaterial.FresnelEnabled = true;
  28042. StandardMaterial.LightmapTextureEnabled = true;
  28043. StandardMaterial.RefractionTextureEnabled = true;
  28044. StandardMaterial.ColorGradingTextureEnabled = true;
  28045. __decorate([
  28046. BABYLON.serializeAsTexture()
  28047. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  28048. __decorate([
  28049. BABYLON.serializeAsTexture()
  28050. ], StandardMaterial.prototype, "ambientTexture", void 0);
  28051. __decorate([
  28052. BABYLON.serializeAsTexture()
  28053. ], StandardMaterial.prototype, "opacityTexture", void 0);
  28054. __decorate([
  28055. BABYLON.serializeAsTexture()
  28056. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  28057. __decorate([
  28058. BABYLON.serializeAsTexture()
  28059. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  28060. __decorate([
  28061. BABYLON.serializeAsTexture()
  28062. ], StandardMaterial.prototype, "specularTexture", void 0);
  28063. __decorate([
  28064. BABYLON.serializeAsTexture()
  28065. ], StandardMaterial.prototype, "bumpTexture", void 0);
  28066. __decorate([
  28067. BABYLON.serializeAsTexture()
  28068. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  28069. __decorate([
  28070. BABYLON.serializeAsTexture()
  28071. ], StandardMaterial.prototype, "refractionTexture", void 0);
  28072. __decorate([
  28073. BABYLON.serializeAsColor3("ambient")
  28074. ], StandardMaterial.prototype, "ambientColor", void 0);
  28075. __decorate([
  28076. BABYLON.serializeAsColor3("diffuse")
  28077. ], StandardMaterial.prototype, "diffuseColor", void 0);
  28078. __decorate([
  28079. BABYLON.serializeAsColor3("specular")
  28080. ], StandardMaterial.prototype, "specularColor", void 0);
  28081. __decorate([
  28082. BABYLON.serializeAsColor3("emissive")
  28083. ], StandardMaterial.prototype, "emissiveColor", void 0);
  28084. __decorate([
  28085. BABYLON.serialize()
  28086. ], StandardMaterial.prototype, "specularPower", void 0);
  28087. __decorate([
  28088. BABYLON.serialize()
  28089. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  28090. __decorate([
  28091. BABYLON.serialize()
  28092. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  28093. __decorate([
  28094. BABYLON.serialize()
  28095. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  28096. __decorate([
  28097. BABYLON.serialize()
  28098. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  28099. __decorate([
  28100. BABYLON.serialize()
  28101. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  28102. __decorate([
  28103. BABYLON.serialize()
  28104. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  28105. __decorate([
  28106. BABYLON.serialize()
  28107. ], StandardMaterial.prototype, "disableLighting", void 0);
  28108. __decorate([
  28109. BABYLON.serialize()
  28110. ], StandardMaterial.prototype, "useParallax", void 0);
  28111. __decorate([
  28112. BABYLON.serialize()
  28113. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  28114. __decorate([
  28115. BABYLON.serialize()
  28116. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  28117. __decorate([
  28118. BABYLON.serialize()
  28119. ], StandardMaterial.prototype, "roughness", void 0);
  28120. __decorate([
  28121. BABYLON.serialize()
  28122. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  28123. __decorate([
  28124. BABYLON.serialize()
  28125. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  28126. __decorate([
  28127. BABYLON.serialize()
  28128. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  28129. __decorate([
  28130. BABYLON.serializeAsFresnelParameters()
  28131. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  28132. __decorate([
  28133. BABYLON.serializeAsFresnelParameters()
  28134. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  28135. __decorate([
  28136. BABYLON.serializeAsFresnelParameters()
  28137. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  28138. __decorate([
  28139. BABYLON.serializeAsFresnelParameters()
  28140. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  28141. __decorate([
  28142. BABYLON.serializeAsFresnelParameters()
  28143. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  28144. __decorate([
  28145. BABYLON.serialize()
  28146. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  28147. __decorate([
  28148. BABYLON.serialize()
  28149. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  28150. __decorate([
  28151. BABYLON.serialize()
  28152. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  28153. __decorate([
  28154. BABYLON.serialize()
  28155. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  28156. __decorate([
  28157. BABYLON.serializeAsTexture()
  28158. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  28159. __decorate([
  28160. BABYLON.serializeAsColorCurves()
  28161. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  28162. __decorate([
  28163. BABYLON.serialize()
  28164. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  28165. BABYLON.StandardMaterial = StandardMaterial;
  28166. })(BABYLON || (BABYLON = {}));
  28167. //# sourceMappingURL=babylon.standardMaterial.js.map
  28168. var BABYLON;
  28169. (function (BABYLON) {
  28170. var MultiMaterial = (function (_super) {
  28171. __extends(MultiMaterial, _super);
  28172. function MultiMaterial(name, scene) {
  28173. var _this = _super.call(this, name, scene, true) || this;
  28174. _this.subMaterials = new Array();
  28175. scene.multiMaterials.push(_this);
  28176. return _this;
  28177. }
  28178. // Properties
  28179. MultiMaterial.prototype.getSubMaterial = function (index) {
  28180. if (index < 0 || index >= this.subMaterials.length) {
  28181. return this.getScene().defaultMaterial;
  28182. }
  28183. return this.subMaterials[index];
  28184. };
  28185. // Methods
  28186. MultiMaterial.prototype.getClassName = function () {
  28187. return "MultiMaterial";
  28188. };
  28189. MultiMaterial.prototype.isReady = function (mesh) {
  28190. for (var index = 0; index < this.subMaterials.length; index++) {
  28191. var subMaterial = this.subMaterials[index];
  28192. if (subMaterial) {
  28193. if (!this.subMaterials[index].isReady(mesh)) {
  28194. return false;
  28195. }
  28196. }
  28197. }
  28198. return true;
  28199. };
  28200. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  28201. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  28202. for (var index = 0; index < this.subMaterials.length; index++) {
  28203. var subMaterial = null;
  28204. if (cloneChildren) {
  28205. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  28206. }
  28207. else {
  28208. subMaterial = this.subMaterials[index];
  28209. }
  28210. newMultiMaterial.subMaterials.push(subMaterial);
  28211. }
  28212. return newMultiMaterial;
  28213. };
  28214. MultiMaterial.prototype.serialize = function () {
  28215. var serializationObject = {};
  28216. serializationObject.name = this.name;
  28217. serializationObject.id = this.id;
  28218. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28219. serializationObject.materials = [];
  28220. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  28221. var subMat = this.subMaterials[matIndex];
  28222. if (subMat) {
  28223. serializationObject.materials.push(subMat.id);
  28224. }
  28225. else {
  28226. serializationObject.materials.push(null);
  28227. }
  28228. }
  28229. return serializationObject;
  28230. };
  28231. return MultiMaterial;
  28232. }(BABYLON.Material));
  28233. BABYLON.MultiMaterial = MultiMaterial;
  28234. })(BABYLON || (BABYLON = {}));
  28235. //# sourceMappingURL=babylon.multiMaterial.js.map
  28236. var BABYLON;
  28237. (function (BABYLON) {
  28238. var SceneLoader = (function () {
  28239. function SceneLoader() {
  28240. }
  28241. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  28242. get: function () {
  28243. return 0;
  28244. },
  28245. enumerable: true,
  28246. configurable: true
  28247. });
  28248. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  28249. get: function () {
  28250. return 1;
  28251. },
  28252. enumerable: true,
  28253. configurable: true
  28254. });
  28255. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  28256. get: function () {
  28257. return 2;
  28258. },
  28259. enumerable: true,
  28260. configurable: true
  28261. });
  28262. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  28263. get: function () {
  28264. return 3;
  28265. },
  28266. enumerable: true,
  28267. configurable: true
  28268. });
  28269. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  28270. get: function () {
  28271. return SceneLoader._ForceFullSceneLoadingForIncremental;
  28272. },
  28273. set: function (value) {
  28274. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  28275. },
  28276. enumerable: true,
  28277. configurable: true
  28278. });
  28279. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  28280. get: function () {
  28281. return SceneLoader._ShowLoadingScreen;
  28282. },
  28283. set: function (value) {
  28284. SceneLoader._ShowLoadingScreen = value;
  28285. },
  28286. enumerable: true,
  28287. configurable: true
  28288. });
  28289. Object.defineProperty(SceneLoader, "loggingLevel", {
  28290. get: function () {
  28291. return SceneLoader._loggingLevel;
  28292. },
  28293. set: function (value) {
  28294. SceneLoader._loggingLevel = value;
  28295. },
  28296. enumerable: true,
  28297. configurable: true
  28298. });
  28299. SceneLoader._getDefaultPlugin = function () {
  28300. return SceneLoader._registeredPlugins[".babylon"];
  28301. };
  28302. SceneLoader._getPluginForExtension = function (extension) {
  28303. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  28304. if (registeredPlugin) {
  28305. return registeredPlugin;
  28306. }
  28307. return SceneLoader._getDefaultPlugin();
  28308. };
  28309. SceneLoader._getPluginForFilename = function (sceneFilename) {
  28310. if (sceneFilename.name) {
  28311. sceneFilename = sceneFilename.name;
  28312. }
  28313. var dotPosition = sceneFilename.lastIndexOf(".");
  28314. var queryStringPosition = sceneFilename.indexOf("?");
  28315. if (queryStringPosition === -1) {
  28316. queryStringPosition = sceneFilename.length;
  28317. }
  28318. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  28319. return SceneLoader._getPluginForExtension(extension);
  28320. };
  28321. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  28322. SceneLoader._getDirectLoad = function (sceneFilename) {
  28323. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  28324. return sceneFilename.substr(5);
  28325. }
  28326. return null;
  28327. };
  28328. // Public functions
  28329. SceneLoader.GetPluginForExtension = function (extension) {
  28330. return SceneLoader._getPluginForExtension(extension).plugin;
  28331. };
  28332. SceneLoader.RegisterPlugin = function (plugin) {
  28333. if (typeof plugin.extensions === "string") {
  28334. var extension = plugin.extensions;
  28335. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  28336. plugin: plugin,
  28337. isBinary: false
  28338. };
  28339. }
  28340. else {
  28341. var extensions = plugin.extensions;
  28342. Object.keys(extensions).forEach(function (extension) {
  28343. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  28344. plugin: plugin,
  28345. isBinary: extensions[extension].isBinary
  28346. };
  28347. });
  28348. }
  28349. };
  28350. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  28351. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28352. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28353. return;
  28354. }
  28355. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28356. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28357. return;
  28358. }
  28359. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  28360. var loadingToken = {};
  28361. scene._addPendingData(loadingToken);
  28362. var manifestChecked = function (success) {
  28363. scene.database = database;
  28364. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  28365. var plugin = registeredPlugin.plugin;
  28366. var useArrayBuffer = registeredPlugin.isBinary;
  28367. var importMeshFromData = function (data) {
  28368. var meshes = [];
  28369. var particleSystems = [];
  28370. var skeletons = [];
  28371. try {
  28372. if (plugin.importMesh) {
  28373. var syncedPlugin = plugin;
  28374. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  28375. if (onerror) {
  28376. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  28377. }
  28378. scene._removePendingData(loadingToken);
  28379. return;
  28380. }
  28381. if (onsuccess) {
  28382. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  28383. onsuccess(meshes, particleSystems, skeletons);
  28384. scene._removePendingData(loadingToken);
  28385. }
  28386. }
  28387. else {
  28388. var asyncedPlugin = plugin;
  28389. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  28390. if (onsuccess) {
  28391. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  28392. onsuccess(meshes, particleSystems, skeletons);
  28393. scene._removePendingData(loadingToken);
  28394. }
  28395. }, function () {
  28396. if (onerror) {
  28397. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  28398. }
  28399. scene._removePendingData(loadingToken);
  28400. });
  28401. }
  28402. }
  28403. catch (e) {
  28404. if (onerror) {
  28405. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  28406. }
  28407. scene._removePendingData(loadingToken);
  28408. }
  28409. };
  28410. if (directLoad) {
  28411. importMeshFromData(directLoad);
  28412. return;
  28413. }
  28414. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  28415. importMeshFromData(data);
  28416. }, progressCallBack, database, useArrayBuffer);
  28417. };
  28418. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  28419. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  28420. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  28421. }
  28422. else {
  28423. // If the scene is a data stream or offline support is not enabled, it's a direct load
  28424. manifestChecked(true);
  28425. }
  28426. };
  28427. /**
  28428. * Load a scene
  28429. * @param rootUrl a string that defines the root url for scene and resources
  28430. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  28431. * @param engine is the instance of BABYLON.Engine to use to create the scene
  28432. */
  28433. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  28434. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  28435. };
  28436. /**
  28437. * Append a scene
  28438. * @param rootUrl a string that defines the root url for scene and resources
  28439. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  28440. * @param scene is the instance of BABYLON.Scene to append to
  28441. */
  28442. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  28443. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  28444. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  28445. return;
  28446. }
  28447. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  28448. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  28449. var plugin = registeredPlugin.plugin;
  28450. var useArrayBuffer = registeredPlugin.isBinary;
  28451. var database;
  28452. var loadingToken = {};
  28453. scene._addPendingData(loadingToken);
  28454. if (SceneLoader.ShowLoadingScreen) {
  28455. scene.getEngine().displayLoadingUI();
  28456. }
  28457. var loadSceneFromData = function (data) {
  28458. scene.database = database;
  28459. if (plugin.load) {
  28460. var syncedPlugin = plugin;
  28461. if (!syncedPlugin.load(scene, data, rootUrl)) {
  28462. if (onerror) {
  28463. onerror(scene);
  28464. }
  28465. scene._removePendingData(loadingToken);
  28466. scene.getEngine().hideLoadingUI();
  28467. return;
  28468. }
  28469. if (onsuccess) {
  28470. onsuccess(scene);
  28471. }
  28472. scene._removePendingData(loadingToken);
  28473. }
  28474. else {
  28475. var asyncedPlugin = plugin;
  28476. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  28477. if (onsuccess) {
  28478. onsuccess(scene);
  28479. }
  28480. scene._removePendingData(loadingToken);
  28481. }, function () {
  28482. if (onerror) {
  28483. onerror(scene);
  28484. }
  28485. scene._removePendingData(loadingToken);
  28486. scene.getEngine().hideLoadingUI();
  28487. });
  28488. }
  28489. if (SceneLoader.ShowLoadingScreen) {
  28490. scene.executeWhenReady(function () {
  28491. scene.getEngine().hideLoadingUI();
  28492. });
  28493. }
  28494. };
  28495. var manifestChecked = function (success) {
  28496. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  28497. };
  28498. if (directLoad) {
  28499. loadSceneFromData(directLoad);
  28500. return;
  28501. }
  28502. if (rootUrl.indexOf("file:") === -1) {
  28503. if (scene.getEngine().enableOfflineSupport) {
  28504. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  28505. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  28506. }
  28507. else {
  28508. manifestChecked(true);
  28509. }
  28510. }
  28511. else {
  28512. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  28513. }
  28514. };
  28515. return SceneLoader;
  28516. }());
  28517. // Flags
  28518. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  28519. SceneLoader._ShowLoadingScreen = true;
  28520. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  28521. // Members
  28522. SceneLoader._registeredPlugins = {};
  28523. BABYLON.SceneLoader = SceneLoader;
  28524. ;
  28525. })(BABYLON || (BABYLON = {}));
  28526. //# sourceMappingURL=babylon.sceneLoader.js.map
  28527. var BABYLON;
  28528. (function (BABYLON) {
  28529. var Internals;
  28530. (function (Internals) {
  28531. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  28532. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  28533. var parsedMaterial = parsedData.materials[index];
  28534. if (parsedMaterial.id === id) {
  28535. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  28536. }
  28537. }
  28538. return null;
  28539. };
  28540. var isDescendantOf = function (mesh, names, hierarchyIds) {
  28541. names = (names instanceof Array) ? names : [names];
  28542. for (var i in names) {
  28543. if (mesh.name === names[i]) {
  28544. hierarchyIds.push(mesh.id);
  28545. return true;
  28546. }
  28547. }
  28548. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  28549. hierarchyIds.push(mesh.id);
  28550. return true;
  28551. }
  28552. return false;
  28553. };
  28554. var logOperation = function (operation, producer) {
  28555. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  28556. };
  28557. BABYLON.SceneLoader.RegisterPlugin({
  28558. extensions: ".babylon",
  28559. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  28560. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  28561. // when SceneLoader.debugLogging = true (default), or exception encountered.
  28562. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  28563. // and avoid problems with multiple concurrent .babylon loads.
  28564. var log = "importMesh has failed JSON parse";
  28565. try {
  28566. var parsedData = JSON.parse(data);
  28567. log = "";
  28568. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  28569. var loadedSkeletonsIds = [];
  28570. var loadedMaterialsIds = [];
  28571. var hierarchyIds = [];
  28572. var index;
  28573. var cache;
  28574. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  28575. var parsedMesh = parsedData.meshes[index];
  28576. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  28577. if (meshesNames instanceof Array) {
  28578. // Remove found mesh name from list.
  28579. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  28580. }
  28581. //Geometry?
  28582. if (parsedMesh.geometryId) {
  28583. //does the file contain geometries?
  28584. if (parsedData.geometries) {
  28585. //find the correct geometry and add it to the scene
  28586. var found = false;
  28587. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  28588. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  28589. return;
  28590. }
  28591. else {
  28592. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  28593. if (parsedGeometryData.id === parsedMesh.geometryId) {
  28594. switch (geometryType) {
  28595. case "boxes":
  28596. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  28597. break;
  28598. case "spheres":
  28599. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  28600. break;
  28601. case "cylinders":
  28602. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  28603. break;
  28604. case "toruses":
  28605. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  28606. break;
  28607. case "grounds":
  28608. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  28609. break;
  28610. case "planes":
  28611. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  28612. break;
  28613. case "torusKnots":
  28614. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  28615. break;
  28616. case "vertexData":
  28617. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  28618. break;
  28619. }
  28620. found = true;
  28621. }
  28622. });
  28623. }
  28624. });
  28625. if (!found) {
  28626. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  28627. }
  28628. }
  28629. }
  28630. // Material ?
  28631. if (parsedMesh.materialId) {
  28632. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  28633. if (!materialFound && parsedData.multiMaterials) {
  28634. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  28635. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  28636. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  28637. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  28638. var subMatId = parsedMultiMaterial.materials[matIndex];
  28639. loadedMaterialsIds.push(subMatId);
  28640. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  28641. log += "\n\tMaterial " + mat.toString(fullDetails);
  28642. }
  28643. loadedMaterialsIds.push(parsedMultiMaterial.id);
  28644. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  28645. materialFound = true;
  28646. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  28647. break;
  28648. }
  28649. }
  28650. }
  28651. if (!materialFound) {
  28652. loadedMaterialsIds.push(parsedMesh.materialId);
  28653. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  28654. if (!mat) {
  28655. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  28656. }
  28657. else {
  28658. log += "\n\tMaterial " + mat.toString(fullDetails);
  28659. }
  28660. }
  28661. }
  28662. // Skeleton ?
  28663. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  28664. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  28665. if (!skeletonAlreadyLoaded) {
  28666. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  28667. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  28668. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  28669. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  28670. skeletons.push(skeleton);
  28671. loadedSkeletonsIds.push(parsedSkeleton.id);
  28672. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  28673. }
  28674. }
  28675. }
  28676. }
  28677. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  28678. meshes.push(mesh);
  28679. log += "\n\tMesh " + mesh.toString(fullDetails);
  28680. }
  28681. }
  28682. // Connecting parents
  28683. var currentMesh;
  28684. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28685. currentMesh = scene.meshes[index];
  28686. if (currentMesh._waitingParentId) {
  28687. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  28688. currentMesh._waitingParentId = undefined;
  28689. }
  28690. }
  28691. // freeze and compute world matrix application
  28692. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28693. currentMesh = scene.meshes[index];
  28694. if (currentMesh._waitingFreezeWorldMatrix) {
  28695. currentMesh.freezeWorldMatrix();
  28696. currentMesh._waitingFreezeWorldMatrix = undefined;
  28697. }
  28698. else {
  28699. currentMesh.computeWorldMatrix(true);
  28700. }
  28701. }
  28702. // Particles
  28703. if (parsedData.particleSystems) {
  28704. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28705. var parsedParticleSystem = parsedData.particleSystems[index];
  28706. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  28707. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  28708. }
  28709. }
  28710. }
  28711. return true;
  28712. }
  28713. catch (err) {
  28714. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  28715. log = null;
  28716. throw err;
  28717. }
  28718. finally {
  28719. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28720. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28721. }
  28722. }
  28723. },
  28724. load: function (scene, data, rootUrl) {
  28725. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  28726. // when SceneLoader.debugLogging = true (default), or exception encountered.
  28727. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  28728. // and avoid problems with multiple concurrent .babylon loads.
  28729. var log = "importScene has failed JSON parse";
  28730. try {
  28731. var parsedData = JSON.parse(data);
  28732. log = "";
  28733. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  28734. // Scene
  28735. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  28736. scene.autoClear = parsedData.autoClear;
  28737. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  28738. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  28739. if (parsedData.gravity) {
  28740. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  28741. }
  28742. // Fog
  28743. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  28744. scene.fogMode = parsedData.fogMode;
  28745. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  28746. scene.fogStart = parsedData.fogStart;
  28747. scene.fogEnd = parsedData.fogEnd;
  28748. scene.fogDensity = parsedData.fogDensity;
  28749. log += "\tFog mode for scene: ";
  28750. switch (scene.fogMode) {
  28751. // getters not compiling, so using hardcoded
  28752. case 1:
  28753. log += "exp\n";
  28754. break;
  28755. case 2:
  28756. log += "exp2\n";
  28757. break;
  28758. case 3:
  28759. log += "linear\n";
  28760. break;
  28761. }
  28762. }
  28763. //Physics
  28764. if (parsedData.physicsEnabled) {
  28765. var physicsPlugin;
  28766. if (parsedData.physicsEngine === "cannon") {
  28767. physicsPlugin = new BABYLON.CannonJSPlugin();
  28768. }
  28769. else if (parsedData.physicsEngine === "oimo") {
  28770. physicsPlugin = new BABYLON.OimoJSPlugin();
  28771. }
  28772. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  28773. //else - default engine, which is currently oimo
  28774. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  28775. scene.enablePhysics(physicsGravity, physicsPlugin);
  28776. }
  28777. // Metadata
  28778. if (parsedData.metadata !== undefined) {
  28779. scene.metadata = parsedData.metadata;
  28780. }
  28781. //collisions, if defined. otherwise, default is true
  28782. if (parsedData.collisionsEnabled != undefined) {
  28783. scene.collisionsEnabled = parsedData.collisionsEnabled;
  28784. }
  28785. scene.workerCollisions = !!parsedData.workerCollisions;
  28786. var index;
  28787. var cache;
  28788. // Lights
  28789. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  28790. var parsedLight = parsedData.lights[index];
  28791. var light = BABYLON.Light.Parse(parsedLight, scene);
  28792. log += (index === 0 ? "\n\tLights:" : "");
  28793. log += "\n\t\t" + light.toString(fullDetails);
  28794. }
  28795. // Animations
  28796. if (parsedData.animations) {
  28797. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  28798. var parsedAnimation = parsedData.animations[index];
  28799. var animation = BABYLON.Animation.Parse(parsedAnimation);
  28800. scene.animations.push(animation);
  28801. log += (index === 0 ? "\n\tAnimations:" : "");
  28802. log += "\n\t\t" + animation.toString(fullDetails);
  28803. }
  28804. }
  28805. if (parsedData.autoAnimate) {
  28806. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  28807. }
  28808. // Materials
  28809. if (parsedData.materials) {
  28810. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  28811. var parsedMaterial = parsedData.materials[index];
  28812. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  28813. log += (index === 0 ? "\n\tMaterials:" : "");
  28814. log += "\n\t\t" + mat.toString(fullDetails);
  28815. }
  28816. }
  28817. if (parsedData.multiMaterials) {
  28818. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  28819. var parsedMultiMaterial = parsedData.multiMaterials[index];
  28820. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  28821. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  28822. log += "\n\t\t" + mmat.toString(fullDetails);
  28823. }
  28824. }
  28825. // Skeletons
  28826. if (parsedData.skeletons) {
  28827. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  28828. var parsedSkeleton = parsedData.skeletons[index];
  28829. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  28830. log += (index === 0 ? "\n\tSkeletons:" : "");
  28831. log += "\n\t\t" + skeleton.toString(fullDetails);
  28832. }
  28833. }
  28834. // Geometries
  28835. var geometries = parsedData.geometries;
  28836. if (geometries) {
  28837. // Boxes
  28838. var boxes = geometries.boxes;
  28839. if (boxes) {
  28840. for (index = 0, cache = boxes.length; index < cache; index++) {
  28841. var parsedBox = boxes[index];
  28842. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  28843. }
  28844. }
  28845. // Spheres
  28846. var spheres = geometries.spheres;
  28847. if (spheres) {
  28848. for (index = 0, cache = spheres.length; index < cache; index++) {
  28849. var parsedSphere = spheres[index];
  28850. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  28851. }
  28852. }
  28853. // Cylinders
  28854. var cylinders = geometries.cylinders;
  28855. if (cylinders) {
  28856. for (index = 0, cache = cylinders.length; index < cache; index++) {
  28857. var parsedCylinder = cylinders[index];
  28858. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  28859. }
  28860. }
  28861. // Toruses
  28862. var toruses = geometries.toruses;
  28863. if (toruses) {
  28864. for (index = 0, cache = toruses.length; index < cache; index++) {
  28865. var parsedTorus = toruses[index];
  28866. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  28867. }
  28868. }
  28869. // Grounds
  28870. var grounds = geometries.grounds;
  28871. if (grounds) {
  28872. for (index = 0, cache = grounds.length; index < cache; index++) {
  28873. var parsedGround = grounds[index];
  28874. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  28875. }
  28876. }
  28877. // Planes
  28878. var planes = geometries.planes;
  28879. if (planes) {
  28880. for (index = 0, cache = planes.length; index < cache; index++) {
  28881. var parsedPlane = planes[index];
  28882. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  28883. }
  28884. }
  28885. // TorusKnots
  28886. var torusKnots = geometries.torusKnots;
  28887. if (torusKnots) {
  28888. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  28889. var parsedTorusKnot = torusKnots[index];
  28890. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  28891. }
  28892. }
  28893. // VertexData
  28894. var vertexData = geometries.vertexData;
  28895. if (vertexData) {
  28896. for (index = 0, cache = vertexData.length; index < cache; index++) {
  28897. var parsedVertexData = vertexData[index];
  28898. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  28899. }
  28900. }
  28901. }
  28902. // Meshes
  28903. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  28904. var parsedMesh = parsedData.meshes[index];
  28905. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  28906. log += (index === 0 ? "\n\tMeshes:" : "");
  28907. log += "\n\t\t" + mesh.toString(fullDetails);
  28908. }
  28909. // Cameras
  28910. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  28911. var parsedCamera = parsedData.cameras[index];
  28912. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  28913. log += (index === 0 ? "\n\tCameras:" : "");
  28914. log += "\n\t\t" + camera.toString(fullDetails);
  28915. }
  28916. if (parsedData.activeCameraID) {
  28917. scene.setActiveCameraByID(parsedData.activeCameraID);
  28918. }
  28919. // Browsing all the graph to connect the dots
  28920. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  28921. var camera = scene.cameras[index];
  28922. if (camera._waitingParentId) {
  28923. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  28924. camera._waitingParentId = undefined;
  28925. }
  28926. }
  28927. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  28928. var light = scene.lights[index];
  28929. if (light._waitingParentId) {
  28930. light.parent = scene.getLastEntryByID(light._waitingParentId);
  28931. light._waitingParentId = undefined;
  28932. }
  28933. }
  28934. // Sounds
  28935. var loadedSounds = [];
  28936. var loadedSound;
  28937. if (BABYLON.AudioEngine && parsedData.sounds) {
  28938. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  28939. var parsedSound = parsedData.sounds[index];
  28940. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28941. if (!parsedSound.url)
  28942. parsedSound.url = parsedSound.name;
  28943. if (!loadedSounds[parsedSound.url]) {
  28944. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  28945. loadedSounds[parsedSound.url] = loadedSound;
  28946. }
  28947. else {
  28948. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  28949. }
  28950. }
  28951. else {
  28952. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  28953. }
  28954. }
  28955. }
  28956. loadedSounds = [];
  28957. // Connect parents & children and parse actions
  28958. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28959. var mesh = scene.meshes[index];
  28960. if (mesh._waitingParentId) {
  28961. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  28962. mesh._waitingParentId = undefined;
  28963. }
  28964. if (mesh._waitingActions) {
  28965. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  28966. mesh._waitingActions = undefined;
  28967. }
  28968. }
  28969. // freeze world matrix application
  28970. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28971. var currentMesh = scene.meshes[index];
  28972. if (currentMesh._waitingFreezeWorldMatrix) {
  28973. currentMesh.freezeWorldMatrix();
  28974. currentMesh._waitingFreezeWorldMatrix = undefined;
  28975. }
  28976. else {
  28977. currentMesh.computeWorldMatrix(true);
  28978. }
  28979. }
  28980. // Particles Systems
  28981. if (parsedData.particleSystems) {
  28982. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28983. var parsedParticleSystem = parsedData.particleSystems[index];
  28984. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  28985. }
  28986. }
  28987. // Lens flares
  28988. if (parsedData.lensFlareSystems) {
  28989. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  28990. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  28991. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  28992. }
  28993. }
  28994. // Shadows
  28995. if (parsedData.shadowGenerators) {
  28996. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  28997. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  28998. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  28999. }
  29000. }
  29001. // Actions (scene)
  29002. if (parsedData.actions) {
  29003. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  29004. }
  29005. // Finish
  29006. return true;
  29007. }
  29008. catch (err) {
  29009. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  29010. log = null;
  29011. throw err;
  29012. }
  29013. finally {
  29014. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  29015. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  29016. }
  29017. }
  29018. }
  29019. });
  29020. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  29021. })(BABYLON || (BABYLON = {}));
  29022. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  29023. var BABYLON;
  29024. (function (BABYLON) {
  29025. var SpriteManager = (function () {
  29026. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  29027. if (epsilon === void 0) { epsilon = 0.01; }
  29028. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  29029. this.name = name;
  29030. this.sprites = new Array();
  29031. this.renderingGroupId = 0;
  29032. this.layerMask = 0x0FFFFFFF;
  29033. this.fogEnabled = true;
  29034. this.isPickable = false;
  29035. /**
  29036. * An event triggered when the manager is disposed.
  29037. * @type {BABYLON.Observable}
  29038. */
  29039. this.onDisposeObservable = new BABYLON.Observable();
  29040. this._vertexBuffers = {};
  29041. this._capacity = capacity;
  29042. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  29043. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29044. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  29045. if (cellSize.width && cellSize.height) {
  29046. this.cellWidth = cellSize.width;
  29047. this.cellHeight = cellSize.height;
  29048. }
  29049. else if (cellSize !== undefined) {
  29050. this.cellWidth = cellSize;
  29051. this.cellHeight = cellSize;
  29052. }
  29053. else {
  29054. return;
  29055. }
  29056. this._epsilon = epsilon;
  29057. this._scene = scene;
  29058. this._scene.spriteManagers.push(this);
  29059. var indices = [];
  29060. var index = 0;
  29061. for (var count = 0; count < capacity; count++) {
  29062. indices.push(index);
  29063. indices.push(index + 1);
  29064. indices.push(index + 2);
  29065. indices.push(index);
  29066. indices.push(index + 2);
  29067. indices.push(index + 3);
  29068. index += 4;
  29069. }
  29070. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  29071. // VBO
  29072. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  29073. this._vertexData = new Float32Array(capacity * 16 * 4);
  29074. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  29075. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  29076. var options = this._buffer.createVertexBuffer("options", 4, 4);
  29077. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  29078. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  29079. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  29080. this._vertexBuffers["options"] = options;
  29081. this._vertexBuffers["cellInfo"] = cellInfo;
  29082. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  29083. // Effects
  29084. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  29085. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  29086. }
  29087. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  29088. set: function (callback) {
  29089. if (this._onDisposeObserver) {
  29090. this.onDisposeObservable.remove(this._onDisposeObserver);
  29091. }
  29092. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29093. },
  29094. enumerable: true,
  29095. configurable: true
  29096. });
  29097. Object.defineProperty(SpriteManager.prototype, "texture", {
  29098. get: function () {
  29099. return this._spriteTexture;
  29100. },
  29101. set: function (value) {
  29102. this._spriteTexture = value;
  29103. },
  29104. enumerable: true,
  29105. configurable: true
  29106. });
  29107. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  29108. var arrayOffset = index * 16;
  29109. if (offsetX === 0)
  29110. offsetX = this._epsilon;
  29111. else if (offsetX === 1)
  29112. offsetX = 1 - this._epsilon;
  29113. if (offsetY === 0)
  29114. offsetY = this._epsilon;
  29115. else if (offsetY === 1)
  29116. offsetY = 1 - this._epsilon;
  29117. this._vertexData[arrayOffset] = sprite.position.x;
  29118. this._vertexData[arrayOffset + 1] = sprite.position.y;
  29119. this._vertexData[arrayOffset + 2] = sprite.position.z;
  29120. this._vertexData[arrayOffset + 3] = sprite.angle;
  29121. this._vertexData[arrayOffset + 4] = sprite.width;
  29122. this._vertexData[arrayOffset + 5] = sprite.height;
  29123. this._vertexData[arrayOffset + 6] = offsetX;
  29124. this._vertexData[arrayOffset + 7] = offsetY;
  29125. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  29126. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  29127. var offset = (sprite.cellIndex / rowSize) >> 0;
  29128. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  29129. this._vertexData[arrayOffset + 11] = offset;
  29130. // Color
  29131. this._vertexData[arrayOffset + 12] = sprite.color.r;
  29132. this._vertexData[arrayOffset + 13] = sprite.color.g;
  29133. this._vertexData[arrayOffset + 14] = sprite.color.b;
  29134. this._vertexData[arrayOffset + 15] = sprite.color.a;
  29135. };
  29136. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  29137. var count = Math.min(this._capacity, this.sprites.length);
  29138. var min = BABYLON.Vector3.Zero();
  29139. var max = BABYLON.Vector3.Zero();
  29140. var distance = Number.MAX_VALUE;
  29141. var currentSprite;
  29142. var cameraSpacePosition = BABYLON.Vector3.Zero();
  29143. var cameraView = camera.getViewMatrix();
  29144. for (var index = 0; index < count; index++) {
  29145. var sprite = this.sprites[index];
  29146. if (!sprite) {
  29147. continue;
  29148. }
  29149. if (predicate) {
  29150. if (!predicate(sprite)) {
  29151. continue;
  29152. }
  29153. }
  29154. else if (!sprite.isPickable) {
  29155. continue;
  29156. }
  29157. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  29158. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  29159. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  29160. if (ray.intersectsBoxMinMax(min, max)) {
  29161. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  29162. if (distance > currentDistance) {
  29163. distance = currentDistance;
  29164. currentSprite = sprite;
  29165. if (fastCheck) {
  29166. break;
  29167. }
  29168. }
  29169. }
  29170. }
  29171. if (currentSprite) {
  29172. var result = new BABYLON.PickingInfo();
  29173. result.hit = true;
  29174. result.pickedSprite = currentSprite;
  29175. result.distance = distance;
  29176. return result;
  29177. }
  29178. return null;
  29179. };
  29180. SpriteManager.prototype.render = function () {
  29181. // Check
  29182. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  29183. return;
  29184. var engine = this._scene.getEngine();
  29185. var baseSize = this._spriteTexture.getBaseSize();
  29186. // Sprites
  29187. var deltaTime = engine.getDeltaTime();
  29188. var max = Math.min(this._capacity, this.sprites.length);
  29189. var rowSize = baseSize.width / this.cellWidth;
  29190. var offset = 0;
  29191. for (var index = 0; index < max; index++) {
  29192. var sprite = this.sprites[index];
  29193. if (!sprite) {
  29194. continue;
  29195. }
  29196. sprite._animate(deltaTime);
  29197. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  29198. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  29199. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  29200. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  29201. }
  29202. this._buffer.update(this._vertexData);
  29203. // Render
  29204. var effect = this._effectBase;
  29205. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  29206. effect = this._effectFog;
  29207. }
  29208. engine.enableEffect(effect);
  29209. var viewMatrix = this._scene.getViewMatrix();
  29210. effect.setTexture("diffuseSampler", this._spriteTexture);
  29211. effect.setMatrix("view", viewMatrix);
  29212. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  29213. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  29214. // Fog
  29215. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  29216. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  29217. effect.setColor3("vFogColor", this._scene.fogColor);
  29218. }
  29219. // VBOs
  29220. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29221. // Draw order
  29222. engine.setDepthFunctionToLessOrEqual();
  29223. effect.setBool("alphaTest", true);
  29224. engine.setColorWrite(false);
  29225. engine.draw(true, 0, max * 6);
  29226. engine.setColorWrite(true);
  29227. effect.setBool("alphaTest", false);
  29228. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29229. engine.draw(true, 0, max * 6);
  29230. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29231. };
  29232. SpriteManager.prototype.dispose = function () {
  29233. if (this._buffer) {
  29234. this._buffer.dispose();
  29235. this._buffer = null;
  29236. }
  29237. if (this._indexBuffer) {
  29238. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29239. this._indexBuffer = null;
  29240. }
  29241. if (this._spriteTexture) {
  29242. this._spriteTexture.dispose();
  29243. this._spriteTexture = null;
  29244. }
  29245. // Remove from scene
  29246. var index = this._scene.spriteManagers.indexOf(this);
  29247. this._scene.spriteManagers.splice(index, 1);
  29248. // Callback
  29249. this.onDisposeObservable.notifyObservers(this);
  29250. this.onDisposeObservable.clear();
  29251. };
  29252. return SpriteManager;
  29253. }());
  29254. BABYLON.SpriteManager = SpriteManager;
  29255. })(BABYLON || (BABYLON = {}));
  29256. //# sourceMappingURL=babylon.spriteManager.js.map
  29257. var BABYLON;
  29258. (function (BABYLON) {
  29259. var Sprite = (function () {
  29260. function Sprite(name, manager) {
  29261. this.name = name;
  29262. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29263. this.width = 1.0;
  29264. this.height = 1.0;
  29265. this.angle = 0;
  29266. this.cellIndex = 0;
  29267. this.invertU = 0;
  29268. this.invertV = 0;
  29269. this.animations = new Array();
  29270. this.isPickable = false;
  29271. this._animationStarted = false;
  29272. this._loopAnimation = false;
  29273. this._fromIndex = 0;
  29274. this._toIndex = 0;
  29275. this._delay = 0;
  29276. this._direction = 1;
  29277. this._frameCount = 0;
  29278. this._time = 0;
  29279. this._manager = manager;
  29280. this._manager.sprites.push(this);
  29281. this.position = BABYLON.Vector3.Zero();
  29282. }
  29283. Object.defineProperty(Sprite.prototype, "size", {
  29284. get: function () {
  29285. return this.width;
  29286. },
  29287. set: function (value) {
  29288. this.width = value;
  29289. this.height = value;
  29290. },
  29291. enumerable: true,
  29292. configurable: true
  29293. });
  29294. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  29295. this._fromIndex = from;
  29296. this._toIndex = to;
  29297. this._loopAnimation = loop;
  29298. this._delay = delay;
  29299. this._animationStarted = true;
  29300. this._direction = from < to ? 1 : -1;
  29301. this.cellIndex = from;
  29302. this._time = 0;
  29303. this._onAnimationEnd = onAnimationEnd;
  29304. };
  29305. Sprite.prototype.stopAnimation = function () {
  29306. this._animationStarted = false;
  29307. };
  29308. Sprite.prototype._animate = function (deltaTime) {
  29309. if (!this._animationStarted)
  29310. return;
  29311. this._time += deltaTime;
  29312. if (this._time > this._delay) {
  29313. this._time = this._time % this._delay;
  29314. this.cellIndex += this._direction;
  29315. if (this.cellIndex === this._toIndex) {
  29316. if (this._loopAnimation) {
  29317. this.cellIndex = this._fromIndex;
  29318. }
  29319. else {
  29320. this._animationStarted = false;
  29321. if (this._onAnimationEnd) {
  29322. this._onAnimationEnd();
  29323. }
  29324. if (this.disposeWhenFinishedAnimating) {
  29325. this.dispose();
  29326. }
  29327. }
  29328. }
  29329. }
  29330. };
  29331. Sprite.prototype.dispose = function () {
  29332. for (var i = 0; i < this._manager.sprites.length; i++) {
  29333. if (this._manager.sprites[i] == this) {
  29334. this._manager.sprites.splice(i, 1);
  29335. }
  29336. }
  29337. };
  29338. return Sprite;
  29339. }());
  29340. BABYLON.Sprite = Sprite;
  29341. })(BABYLON || (BABYLON = {}));
  29342. //# sourceMappingURL=babylon.sprite.js.map
  29343. var BABYLON;
  29344. (function (BABYLON) {
  29345. var Layer = (function () {
  29346. function Layer(name, imgUrl, scene, isBackground, color) {
  29347. this.name = name;
  29348. this.scale = new BABYLON.Vector2(1, 1);
  29349. this.offset = new BABYLON.Vector2(0, 0);
  29350. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  29351. this._vertexBuffers = {};
  29352. // Events
  29353. /**
  29354. * An event triggered when the layer is disposed.
  29355. * @type {BABYLON.Observable}
  29356. */
  29357. this.onDisposeObservable = new BABYLON.Observable();
  29358. /**
  29359. * An event triggered before rendering the scene
  29360. * @type {BABYLON.Observable}
  29361. */
  29362. this.onBeforeRenderObservable = new BABYLON.Observable();
  29363. /**
  29364. * An event triggered after rendering the scene
  29365. * @type {BABYLON.Observable}
  29366. */
  29367. this.onAfterRenderObservable = new BABYLON.Observable();
  29368. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  29369. this.isBackground = isBackground === undefined ? true : isBackground;
  29370. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  29371. this._scene = scene;
  29372. this._scene.layers.push(this);
  29373. var engine = scene.getEngine();
  29374. // VBO
  29375. var vertices = [];
  29376. vertices.push(1, 1);
  29377. vertices.push(-1, 1);
  29378. vertices.push(-1, -1);
  29379. vertices.push(1, -1);
  29380. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29381. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  29382. // Indices
  29383. var indices = [];
  29384. indices.push(0);
  29385. indices.push(1);
  29386. indices.push(2);
  29387. indices.push(0);
  29388. indices.push(2);
  29389. indices.push(3);
  29390. this._indexBuffer = engine.createIndexBuffer(indices);
  29391. // Effects
  29392. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  29393. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  29394. }
  29395. Object.defineProperty(Layer.prototype, "onDispose", {
  29396. set: function (callback) {
  29397. if (this._onDisposeObserver) {
  29398. this.onDisposeObservable.remove(this._onDisposeObserver);
  29399. }
  29400. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29401. },
  29402. enumerable: true,
  29403. configurable: true
  29404. });
  29405. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  29406. set: function (callback) {
  29407. if (this._onBeforeRenderObserver) {
  29408. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  29409. }
  29410. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  29411. },
  29412. enumerable: true,
  29413. configurable: true
  29414. });
  29415. Object.defineProperty(Layer.prototype, "onAfterRender", {
  29416. set: function (callback) {
  29417. if (this._onAfterRenderObserver) {
  29418. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  29419. }
  29420. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  29421. },
  29422. enumerable: true,
  29423. configurable: true
  29424. });
  29425. Layer.prototype.render = function () {
  29426. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  29427. // Check
  29428. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  29429. return;
  29430. var engine = this._scene.getEngine();
  29431. this.onBeforeRenderObservable.notifyObservers(this);
  29432. // Render
  29433. engine.enableEffect(currentEffect);
  29434. engine.setState(false);
  29435. // Texture
  29436. currentEffect.setTexture("textureSampler", this.texture);
  29437. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  29438. // Color
  29439. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  29440. // Scale / offset
  29441. currentEffect.setVector2("offset", this.offset);
  29442. currentEffect.setVector2("scale", this.scale);
  29443. // VBOs
  29444. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  29445. // Draw order
  29446. if (!this.alphaTest) {
  29447. engine.setAlphaMode(this.alphaBlendingMode);
  29448. engine.draw(true, 0, 6);
  29449. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29450. }
  29451. else {
  29452. engine.draw(true, 0, 6);
  29453. }
  29454. this.onAfterRenderObservable.notifyObservers(this);
  29455. };
  29456. Layer.prototype.dispose = function () {
  29457. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29458. if (vertexBuffer) {
  29459. vertexBuffer.dispose();
  29460. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29461. }
  29462. if (this._indexBuffer) {
  29463. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29464. this._indexBuffer = null;
  29465. }
  29466. if (this.texture) {
  29467. this.texture.dispose();
  29468. this.texture = null;
  29469. }
  29470. // Remove from scene
  29471. var index = this._scene.layers.indexOf(this);
  29472. this._scene.layers.splice(index, 1);
  29473. // Callback
  29474. this.onDisposeObservable.notifyObservers(this);
  29475. this.onDisposeObservable.clear();
  29476. this.onAfterRenderObservable.clear();
  29477. this.onBeforeRenderObservable.clear();
  29478. };
  29479. return Layer;
  29480. }());
  29481. BABYLON.Layer = Layer;
  29482. })(BABYLON || (BABYLON = {}));
  29483. //# sourceMappingURL=babylon.layer.js.map
  29484. var BABYLON;
  29485. (function (BABYLON) {
  29486. var Particle = (function () {
  29487. function Particle() {
  29488. this.position = BABYLON.Vector3.Zero();
  29489. this.direction = BABYLON.Vector3.Zero();
  29490. this.color = new BABYLON.Color4(0, 0, 0, 0);
  29491. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  29492. this.lifeTime = 1.0;
  29493. this.age = 0;
  29494. this.size = 0;
  29495. this.angle = 0;
  29496. this.angularSpeed = 0;
  29497. }
  29498. Particle.prototype.copyTo = function (other) {
  29499. other.position.copyFrom(this.position);
  29500. other.direction.copyFrom(this.direction);
  29501. other.color.copyFrom(this.color);
  29502. other.colorStep.copyFrom(this.colorStep);
  29503. other.lifeTime = this.lifeTime;
  29504. other.age = this.age;
  29505. other.size = this.size;
  29506. other.angle = this.angle;
  29507. other.angularSpeed = this.angularSpeed;
  29508. };
  29509. return Particle;
  29510. }());
  29511. BABYLON.Particle = Particle;
  29512. })(BABYLON || (BABYLON = {}));
  29513. //# sourceMappingURL=babylon.particle.js.map
  29514. var BABYLON;
  29515. (function (BABYLON) {
  29516. var randomNumber = function (min, max) {
  29517. if (min === max) {
  29518. return (min);
  29519. }
  29520. var random = Math.random();
  29521. return ((random * (max - min)) + min);
  29522. };
  29523. var ParticleSystem = (function () {
  29524. function ParticleSystem(name, capacity, scene, customEffect) {
  29525. var _this = this;
  29526. this.name = name;
  29527. // Members
  29528. this.animations = [];
  29529. this.renderingGroupId = 0;
  29530. this.emitter = null;
  29531. this.emitRate = 10;
  29532. this.manualEmitCount = -1;
  29533. this.updateSpeed = 0.01;
  29534. this.targetStopDuration = 0;
  29535. this.disposeOnStop = false;
  29536. this.minEmitPower = 1;
  29537. this.maxEmitPower = 1;
  29538. this.minLifeTime = 1;
  29539. this.maxLifeTime = 1;
  29540. this.minSize = 1;
  29541. this.maxSize = 1;
  29542. this.minAngularSpeed = 0;
  29543. this.maxAngularSpeed = 0;
  29544. this.layerMask = 0x0FFFFFFF;
  29545. this.customShader = null;
  29546. this.preventAutoStart = false;
  29547. /**
  29548. * An event triggered when the system is disposed.
  29549. * @type {BABYLON.Observable}
  29550. */
  29551. this.onDisposeObservable = new BABYLON.Observable();
  29552. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  29553. this.forceDepthWrite = false;
  29554. this.gravity = BABYLON.Vector3.Zero();
  29555. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  29556. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  29557. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  29558. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  29559. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29560. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29561. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  29562. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  29563. this.particles = new Array();
  29564. this._stockParticles = new Array();
  29565. this._newPartsExcess = 0;
  29566. this._vertexBuffers = {};
  29567. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  29568. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  29569. this._scaledDirection = BABYLON.Vector3.Zero();
  29570. this._scaledGravity = BABYLON.Vector3.Zero();
  29571. this._currentRenderId = -1;
  29572. this._started = false;
  29573. this._stopped = false;
  29574. this._actualFrame = 0;
  29575. this.id = name;
  29576. this._capacity = capacity;
  29577. this._scene = scene;
  29578. this._customEffect = customEffect;
  29579. scene.particleSystems.push(this);
  29580. var indices = [];
  29581. var index = 0;
  29582. for (var count = 0; count < capacity; count++) {
  29583. indices.push(index);
  29584. indices.push(index + 1);
  29585. indices.push(index + 2);
  29586. indices.push(index);
  29587. indices.push(index + 2);
  29588. indices.push(index + 3);
  29589. index += 4;
  29590. }
  29591. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  29592. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  29593. this._vertexData = new Float32Array(capacity * 11 * 4);
  29594. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  29595. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  29596. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  29597. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  29598. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  29599. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  29600. this._vertexBuffers["options"] = options;
  29601. // Default behaviors
  29602. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  29603. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  29604. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  29605. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  29606. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  29607. };
  29608. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  29609. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  29610. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  29611. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  29612. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  29613. };
  29614. this.updateFunction = function (particles) {
  29615. for (var index = 0; index < particles.length; index++) {
  29616. var particle = particles[index];
  29617. particle.age += _this._scaledUpdateSpeed;
  29618. if (particle.age >= particle.lifeTime) {
  29619. _this.recycleParticle(particle);
  29620. index--;
  29621. continue;
  29622. }
  29623. else {
  29624. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  29625. particle.color.addInPlace(_this._scaledColorStep);
  29626. if (particle.color.a < 0)
  29627. particle.color.a = 0;
  29628. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  29629. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  29630. particle.position.addInPlace(_this._scaledDirection);
  29631. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  29632. particle.direction.addInPlace(_this._scaledGravity);
  29633. }
  29634. }
  29635. };
  29636. }
  29637. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  29638. set: function (callback) {
  29639. if (this._onDisposeObserver) {
  29640. this.onDisposeObservable.remove(this._onDisposeObserver);
  29641. }
  29642. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  29643. },
  29644. enumerable: true,
  29645. configurable: true
  29646. });
  29647. ParticleSystem.prototype.recycleParticle = function (particle) {
  29648. var lastParticle = this.particles.pop();
  29649. if (lastParticle !== particle) {
  29650. lastParticle.copyTo(particle);
  29651. this._stockParticles.push(lastParticle);
  29652. }
  29653. };
  29654. ParticleSystem.prototype.getCapacity = function () {
  29655. return this._capacity;
  29656. };
  29657. ParticleSystem.prototype.isAlive = function () {
  29658. return this._alive;
  29659. };
  29660. ParticleSystem.prototype.isStarted = function () {
  29661. return this._started;
  29662. };
  29663. ParticleSystem.prototype.start = function () {
  29664. this._started = true;
  29665. this._stopped = false;
  29666. this._actualFrame = 0;
  29667. };
  29668. ParticleSystem.prototype.stop = function () {
  29669. this._stopped = true;
  29670. };
  29671. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  29672. var offset = index * 11;
  29673. this._vertexData[offset] = particle.position.x;
  29674. this._vertexData[offset + 1] = particle.position.y;
  29675. this._vertexData[offset + 2] = particle.position.z;
  29676. this._vertexData[offset + 3] = particle.color.r;
  29677. this._vertexData[offset + 4] = particle.color.g;
  29678. this._vertexData[offset + 5] = particle.color.b;
  29679. this._vertexData[offset + 6] = particle.color.a;
  29680. this._vertexData[offset + 7] = particle.angle;
  29681. this._vertexData[offset + 8] = particle.size;
  29682. this._vertexData[offset + 9] = offsetX;
  29683. this._vertexData[offset + 10] = offsetY;
  29684. };
  29685. ParticleSystem.prototype._update = function (newParticles) {
  29686. // Update current
  29687. this._alive = this.particles.length > 0;
  29688. this.updateFunction(this.particles);
  29689. // Add new ones
  29690. var worldMatrix;
  29691. if (this.emitter.position) {
  29692. worldMatrix = this.emitter.getWorldMatrix();
  29693. }
  29694. else {
  29695. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  29696. }
  29697. var particle;
  29698. for (var index = 0; index < newParticles; index++) {
  29699. if (this.particles.length === this._capacity) {
  29700. break;
  29701. }
  29702. if (this._stockParticles.length !== 0) {
  29703. particle = this._stockParticles.pop();
  29704. particle.age = 0;
  29705. }
  29706. else {
  29707. particle = new BABYLON.Particle();
  29708. }
  29709. this.particles.push(particle);
  29710. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  29711. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  29712. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  29713. particle.size = randomNumber(this.minSize, this.maxSize);
  29714. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  29715. this.startPositionFunction(worldMatrix, particle.position, particle);
  29716. var step = randomNumber(0, 1.0);
  29717. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  29718. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  29719. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  29720. }
  29721. };
  29722. ParticleSystem.prototype._getEffect = function () {
  29723. if (this._customEffect) {
  29724. return this._customEffect;
  29725. }
  29726. ;
  29727. var defines = [];
  29728. if (this._scene.clipPlane) {
  29729. defines.push("#define CLIPPLANE");
  29730. }
  29731. // Effect
  29732. var join = defines.join("\n");
  29733. if (this._cachedDefines !== join) {
  29734. this._cachedDefines = join;
  29735. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  29736. }
  29737. return this._effect;
  29738. };
  29739. ParticleSystem.prototype.animate = function () {
  29740. if (!this._started)
  29741. return;
  29742. var effect = this._getEffect();
  29743. // Check
  29744. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  29745. return;
  29746. if (this._currentRenderId === this._scene.getRenderId()) {
  29747. return;
  29748. }
  29749. this._currentRenderId = this._scene.getRenderId();
  29750. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  29751. // determine the number of particles we need to create
  29752. var newParticles;
  29753. if (this.manualEmitCount > -1) {
  29754. newParticles = this.manualEmitCount;
  29755. this._newPartsExcess = 0;
  29756. this.manualEmitCount = 0;
  29757. }
  29758. else {
  29759. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  29760. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  29761. }
  29762. if (this._newPartsExcess > 1.0) {
  29763. newParticles += this._newPartsExcess >> 0;
  29764. this._newPartsExcess -= this._newPartsExcess >> 0;
  29765. }
  29766. this._alive = false;
  29767. if (!this._stopped) {
  29768. this._actualFrame += this._scaledUpdateSpeed;
  29769. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  29770. this.stop();
  29771. }
  29772. else {
  29773. newParticles = 0;
  29774. }
  29775. this._update(newParticles);
  29776. // Stopped?
  29777. if (this._stopped) {
  29778. if (!this._alive) {
  29779. this._started = false;
  29780. if (this.disposeOnStop) {
  29781. this._scene._toBeDisposed.push(this);
  29782. }
  29783. }
  29784. }
  29785. // Update VBO
  29786. var offset = 0;
  29787. for (var index = 0; index < this.particles.length; index++) {
  29788. var particle = this.particles[index];
  29789. this._appendParticleVertex(offset++, particle, 0, 0);
  29790. this._appendParticleVertex(offset++, particle, 1, 0);
  29791. this._appendParticleVertex(offset++, particle, 1, 1);
  29792. this._appendParticleVertex(offset++, particle, 0, 1);
  29793. }
  29794. this._vertexBuffer.update(this._vertexData);
  29795. };
  29796. ParticleSystem.prototype.render = function () {
  29797. var effect = this._getEffect();
  29798. // Check
  29799. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  29800. return 0;
  29801. var engine = this._scene.getEngine();
  29802. // Render
  29803. engine.enableEffect(effect);
  29804. engine.setState(false);
  29805. var viewMatrix = this._scene.getViewMatrix();
  29806. effect.setTexture("diffuseSampler", this.particleTexture);
  29807. effect.setMatrix("view", viewMatrix);
  29808. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  29809. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  29810. if (this._scene.clipPlane) {
  29811. var clipPlane = this._scene.clipPlane;
  29812. var invView = viewMatrix.clone();
  29813. invView.invert();
  29814. effect.setMatrix("invView", invView);
  29815. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  29816. }
  29817. // VBOs
  29818. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29819. // Draw order
  29820. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  29821. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  29822. }
  29823. else {
  29824. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  29825. }
  29826. if (this.forceDepthWrite) {
  29827. engine.setDepthWrite(true);
  29828. }
  29829. engine.draw(true, 0, this.particles.length * 6);
  29830. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29831. return this.particles.length;
  29832. };
  29833. ParticleSystem.prototype.dispose = function () {
  29834. if (this._vertexBuffer) {
  29835. this._vertexBuffer.dispose();
  29836. this._vertexBuffer = null;
  29837. }
  29838. if (this._indexBuffer) {
  29839. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29840. this._indexBuffer = null;
  29841. }
  29842. if (this.particleTexture) {
  29843. this.particleTexture.dispose();
  29844. this.particleTexture = null;
  29845. }
  29846. // Remove from scene
  29847. var index = this._scene.particleSystems.indexOf(this);
  29848. this._scene.particleSystems.splice(index, 1);
  29849. // Callback
  29850. this.onDisposeObservable.notifyObservers(this);
  29851. this.onDisposeObservable.clear();
  29852. };
  29853. // Clone
  29854. ParticleSystem.prototype.clone = function (name, newEmitter) {
  29855. var custom = null;
  29856. var program = null;
  29857. if (this.customShader != null) {
  29858. program = this.customShader;
  29859. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  29860. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  29861. }
  29862. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  29863. result.customShader = program;
  29864. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  29865. if (newEmitter === undefined) {
  29866. newEmitter = this.emitter;
  29867. }
  29868. result.emitter = newEmitter;
  29869. if (this.particleTexture) {
  29870. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  29871. }
  29872. if (!this.preventAutoStart) {
  29873. result.start();
  29874. }
  29875. return result;
  29876. };
  29877. ParticleSystem.prototype.serialize = function () {
  29878. var serializationObject = {};
  29879. serializationObject.name = this.name;
  29880. serializationObject.id = this.id;
  29881. // Emitter
  29882. if (this.emitter.position) {
  29883. serializationObject.emitterId = this.emitter.id;
  29884. }
  29885. else {
  29886. serializationObject.emitter = this.emitter.asArray();
  29887. }
  29888. serializationObject.capacity = this.getCapacity();
  29889. if (this.particleTexture) {
  29890. serializationObject.textureName = this.particleTexture.name;
  29891. }
  29892. // Animations
  29893. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  29894. // Particle system
  29895. serializationObject.minAngularSpeed = this.minAngularSpeed;
  29896. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  29897. serializationObject.minSize = this.minSize;
  29898. serializationObject.maxSize = this.maxSize;
  29899. serializationObject.minEmitPower = this.minEmitPower;
  29900. serializationObject.maxEmitPower = this.maxEmitPower;
  29901. serializationObject.minLifeTime = this.minLifeTime;
  29902. serializationObject.maxLifeTime = this.maxLifeTime;
  29903. serializationObject.emitRate = this.emitRate;
  29904. serializationObject.minEmitBox = this.minEmitBox.asArray();
  29905. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  29906. serializationObject.gravity = this.gravity.asArray();
  29907. serializationObject.direction1 = this.direction1.asArray();
  29908. serializationObject.direction2 = this.direction2.asArray();
  29909. serializationObject.color1 = this.color1.asArray();
  29910. serializationObject.color2 = this.color2.asArray();
  29911. serializationObject.colorDead = this.colorDead.asArray();
  29912. serializationObject.updateSpeed = this.updateSpeed;
  29913. serializationObject.targetStopDuration = this.targetStopDuration;
  29914. serializationObject.textureMask = this.textureMask.asArray();
  29915. serializationObject.blendMode = this.blendMode;
  29916. serializationObject.customShader = this.customShader;
  29917. serializationObject.preventAutoStart = this.preventAutoStart;
  29918. return serializationObject;
  29919. };
  29920. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  29921. var name = parsedParticleSystem.name;
  29922. var custom = null;
  29923. var program = null;
  29924. if (parsedParticleSystem.customShader) {
  29925. program = parsedParticleSystem.customShader;
  29926. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  29927. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  29928. }
  29929. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  29930. particleSystem.customShader = program;
  29931. if (parsedParticleSystem.id) {
  29932. particleSystem.id = parsedParticleSystem.id;
  29933. }
  29934. // Auto start
  29935. if (parsedParticleSystem.preventAutoStart) {
  29936. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  29937. }
  29938. // Texture
  29939. if (parsedParticleSystem.textureName) {
  29940. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  29941. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  29942. }
  29943. // Emitter
  29944. if (parsedParticleSystem.emitterId) {
  29945. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  29946. }
  29947. else {
  29948. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  29949. }
  29950. // Animations
  29951. if (parsedParticleSystem.animations) {
  29952. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  29953. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  29954. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29955. }
  29956. }
  29957. if (parsedParticleSystem.autoAnimate) {
  29958. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  29959. }
  29960. // Particle system
  29961. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  29962. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  29963. particleSystem.minSize = parsedParticleSystem.minSize;
  29964. particleSystem.maxSize = parsedParticleSystem.maxSize;
  29965. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  29966. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  29967. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  29968. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  29969. particleSystem.emitRate = parsedParticleSystem.emitRate;
  29970. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  29971. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  29972. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  29973. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  29974. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  29975. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  29976. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  29977. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  29978. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  29979. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  29980. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  29981. particleSystem.blendMode = parsedParticleSystem.blendMode;
  29982. if (!particleSystem.preventAutoStart) {
  29983. particleSystem.start();
  29984. }
  29985. return particleSystem;
  29986. };
  29987. return ParticleSystem;
  29988. }());
  29989. // Statics
  29990. ParticleSystem.BLENDMODE_ONEONE = 0;
  29991. ParticleSystem.BLENDMODE_STANDARD = 1;
  29992. BABYLON.ParticleSystem = ParticleSystem;
  29993. })(BABYLON || (BABYLON = {}));
  29994. //# sourceMappingURL=babylon.particleSystem.js.map
  29995. var BABYLON;
  29996. (function (BABYLON) {
  29997. var AnimationRange = (function () {
  29998. function AnimationRange(name, from, to) {
  29999. this.name = name;
  30000. this.from = from;
  30001. this.to = to;
  30002. }
  30003. AnimationRange.prototype.clone = function () {
  30004. return new AnimationRange(this.name, this.from, this.to);
  30005. };
  30006. return AnimationRange;
  30007. }());
  30008. BABYLON.AnimationRange = AnimationRange;
  30009. /**
  30010. * Composed of a frame, and an action function
  30011. */
  30012. var AnimationEvent = (function () {
  30013. function AnimationEvent(frame, action, onlyOnce) {
  30014. this.frame = frame;
  30015. this.action = action;
  30016. this.onlyOnce = onlyOnce;
  30017. this.isDone = false;
  30018. }
  30019. return AnimationEvent;
  30020. }());
  30021. BABYLON.AnimationEvent = AnimationEvent;
  30022. var PathCursor = (function () {
  30023. function PathCursor(path) {
  30024. this.path = path;
  30025. this._onchange = new Array();
  30026. this.value = 0;
  30027. this.animations = new Array();
  30028. }
  30029. PathCursor.prototype.getPoint = function () {
  30030. var point = this.path.getPointAtLengthPosition(this.value);
  30031. return new BABYLON.Vector3(point.x, 0, point.y);
  30032. };
  30033. PathCursor.prototype.moveAhead = function (step) {
  30034. if (step === void 0) { step = 0.002; }
  30035. this.move(step);
  30036. return this;
  30037. };
  30038. PathCursor.prototype.moveBack = function (step) {
  30039. if (step === void 0) { step = 0.002; }
  30040. this.move(-step);
  30041. return this;
  30042. };
  30043. PathCursor.prototype.move = function (step) {
  30044. if (Math.abs(step) > 1) {
  30045. throw "step size should be less than 1.";
  30046. }
  30047. this.value += step;
  30048. this.ensureLimits();
  30049. this.raiseOnChange();
  30050. return this;
  30051. };
  30052. PathCursor.prototype.ensureLimits = function () {
  30053. while (this.value > 1) {
  30054. this.value -= 1;
  30055. }
  30056. while (this.value < 0) {
  30057. this.value += 1;
  30058. }
  30059. return this;
  30060. };
  30061. // used by animation engine
  30062. PathCursor.prototype.markAsDirty = function (propertyName) {
  30063. this.ensureLimits();
  30064. this.raiseOnChange();
  30065. return this;
  30066. };
  30067. PathCursor.prototype.raiseOnChange = function () {
  30068. var _this = this;
  30069. this._onchange.forEach(function (f) { return f(_this); });
  30070. return this;
  30071. };
  30072. PathCursor.prototype.onchange = function (f) {
  30073. this._onchange.push(f);
  30074. return this;
  30075. };
  30076. return PathCursor;
  30077. }());
  30078. BABYLON.PathCursor = PathCursor;
  30079. var Animation = (function () {
  30080. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  30081. this.name = name;
  30082. this.targetProperty = targetProperty;
  30083. this.framePerSecond = framePerSecond;
  30084. this.dataType = dataType;
  30085. this.loopMode = loopMode;
  30086. this.enableBlending = enableBlending;
  30087. this._offsetsCache = {};
  30088. this._highLimitsCache = {};
  30089. this._stopped = false;
  30090. this._blendingFactor = 0;
  30091. // The set of event that will be linked to this animation
  30092. this._events = new Array();
  30093. this.allowMatricesInterpolation = false;
  30094. this.blendingSpeed = 0.01;
  30095. this._ranges = {};
  30096. this.targetPropertyPath = targetProperty.split(".");
  30097. this.dataType = dataType;
  30098. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  30099. }
  30100. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  30101. var dataType = undefined;
  30102. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  30103. dataType = Animation.ANIMATIONTYPE_FLOAT;
  30104. }
  30105. else if (from instanceof BABYLON.Quaternion) {
  30106. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  30107. }
  30108. else if (from instanceof BABYLON.Vector3) {
  30109. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  30110. }
  30111. else if (from instanceof BABYLON.Vector2) {
  30112. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  30113. }
  30114. else if (from instanceof BABYLON.Color3) {
  30115. dataType = Animation.ANIMATIONTYPE_COLOR3;
  30116. }
  30117. else if (from instanceof BABYLON.Size) {
  30118. dataType = Animation.ANIMATIONTYPE_SIZE;
  30119. }
  30120. if (dataType == undefined) {
  30121. return null;
  30122. }
  30123. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  30124. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  30125. animation.setKeys(keys);
  30126. if (easingFunction !== undefined) {
  30127. animation.setEasingFunction(easingFunction);
  30128. }
  30129. return animation;
  30130. };
  30131. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30132. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30133. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30134. };
  30135. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  30136. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  30137. node.animations.push(animation);
  30138. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  30139. };
  30140. // Methods
  30141. /**
  30142. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  30143. */
  30144. Animation.prototype.toString = function (fullDetails) {
  30145. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  30146. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  30147. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  30148. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  30149. if (fullDetails) {
  30150. ret += ", Ranges: {";
  30151. var first = true;
  30152. for (var name in this._ranges) {
  30153. if (first) {
  30154. ret += ", ";
  30155. first = false;
  30156. }
  30157. ret += name;
  30158. }
  30159. ret += "}";
  30160. }
  30161. return ret;
  30162. };
  30163. /**
  30164. * Add an event to this animation.
  30165. */
  30166. Animation.prototype.addEvent = function (event) {
  30167. this._events.push(event);
  30168. };
  30169. /**
  30170. * Remove all events found at the given frame
  30171. * @param frame
  30172. */
  30173. Animation.prototype.removeEvents = function (frame) {
  30174. for (var index = 0; index < this._events.length; index++) {
  30175. if (this._events[index].frame === frame) {
  30176. this._events.splice(index, 1);
  30177. index--;
  30178. }
  30179. }
  30180. };
  30181. Animation.prototype.createRange = function (name, from, to) {
  30182. // check name not already in use; could happen for bones after serialized
  30183. if (!this._ranges[name]) {
  30184. this._ranges[name] = new AnimationRange(name, from, to);
  30185. }
  30186. };
  30187. Animation.prototype.deleteRange = function (name, deleteFrames) {
  30188. if (deleteFrames === void 0) { deleteFrames = true; }
  30189. if (this._ranges[name]) {
  30190. if (deleteFrames) {
  30191. var from = this._ranges[name].from;
  30192. var to = this._ranges[name].to;
  30193. // this loop MUST go high to low for multiple splices to work
  30194. for (var key = this._keys.length - 1; key >= 0; key--) {
  30195. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  30196. this._keys.splice(key, 1);
  30197. }
  30198. }
  30199. }
  30200. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  30201. }
  30202. };
  30203. Animation.prototype.getRange = function (name) {
  30204. return this._ranges[name];
  30205. };
  30206. Animation.prototype.reset = function () {
  30207. this._offsetsCache = {};
  30208. this._highLimitsCache = {};
  30209. this.currentFrame = 0;
  30210. this._blendingFactor = 0;
  30211. this._originalBlendValue = null;
  30212. };
  30213. Animation.prototype.isStopped = function () {
  30214. return this._stopped;
  30215. };
  30216. Animation.prototype.getKeys = function () {
  30217. return this._keys;
  30218. };
  30219. Animation.prototype.getHighestFrame = function () {
  30220. var ret = 0;
  30221. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  30222. if (ret < this._keys[key].frame) {
  30223. ret = this._keys[key].frame;
  30224. }
  30225. }
  30226. return ret;
  30227. };
  30228. Animation.prototype.getEasingFunction = function () {
  30229. return this._easingFunction;
  30230. };
  30231. Animation.prototype.setEasingFunction = function (easingFunction) {
  30232. this._easingFunction = easingFunction;
  30233. };
  30234. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  30235. return startValue + (endValue - startValue) * gradient;
  30236. };
  30237. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  30238. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  30239. };
  30240. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  30241. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  30242. };
  30243. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  30244. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  30245. };
  30246. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  30247. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  30248. };
  30249. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  30250. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  30251. };
  30252. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  30253. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  30254. };
  30255. Animation.prototype.clone = function () {
  30256. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  30257. clone.enableBlending = this.enableBlending;
  30258. clone.blendingSpeed = this.blendingSpeed;
  30259. if (this._keys) {
  30260. clone.setKeys(this._keys);
  30261. }
  30262. if (this._ranges) {
  30263. clone._ranges = {};
  30264. for (var name in this._ranges) {
  30265. clone._ranges[name] = this._ranges[name].clone();
  30266. }
  30267. }
  30268. return clone;
  30269. };
  30270. Animation.prototype.setKeys = function (values) {
  30271. this._keys = values.slice(0);
  30272. this._offsetsCache = {};
  30273. this._highLimitsCache = {};
  30274. };
  30275. Animation.prototype._getKeyValue = function (value) {
  30276. if (typeof value === "function") {
  30277. return value();
  30278. }
  30279. return value;
  30280. };
  30281. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  30282. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  30283. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  30284. }
  30285. this.currentFrame = currentFrame;
  30286. // Try to get a hash to find the right key
  30287. 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));
  30288. if (this._keys[startKey].frame >= currentFrame) {
  30289. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  30290. startKey--;
  30291. }
  30292. }
  30293. for (var key = startKey; key < this._keys.length; key++) {
  30294. if (this._keys[key + 1].frame >= currentFrame) {
  30295. var startValue = this._getKeyValue(this._keys[key].value);
  30296. var endValue = this._getKeyValue(this._keys[key + 1].value);
  30297. // gradient : percent of currentFrame between the frame inf and the frame sup
  30298. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  30299. // check for easingFunction and correction of gradient
  30300. if (this._easingFunction != null) {
  30301. gradient = this._easingFunction.ease(gradient);
  30302. }
  30303. switch (this.dataType) {
  30304. // Float
  30305. case Animation.ANIMATIONTYPE_FLOAT:
  30306. switch (loopMode) {
  30307. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30308. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30309. return this.floatInterpolateFunction(startValue, endValue, gradient);
  30310. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30311. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  30312. }
  30313. break;
  30314. // Quaternion
  30315. case Animation.ANIMATIONTYPE_QUATERNION:
  30316. var quaternion = null;
  30317. switch (loopMode) {
  30318. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30319. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30320. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  30321. break;
  30322. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30323. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30324. break;
  30325. }
  30326. return quaternion;
  30327. // Vector3
  30328. case Animation.ANIMATIONTYPE_VECTOR3:
  30329. switch (loopMode) {
  30330. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30331. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30332. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  30333. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30334. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30335. }
  30336. // Vector2
  30337. case Animation.ANIMATIONTYPE_VECTOR2:
  30338. switch (loopMode) {
  30339. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30340. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30341. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  30342. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30343. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30344. }
  30345. // Size
  30346. case Animation.ANIMATIONTYPE_SIZE:
  30347. switch (loopMode) {
  30348. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30349. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30350. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  30351. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30352. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30353. }
  30354. // Color3
  30355. case Animation.ANIMATIONTYPE_COLOR3:
  30356. switch (loopMode) {
  30357. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30358. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30359. return this.color3InterpolateFunction(startValue, endValue, gradient);
  30360. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30361. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  30362. }
  30363. // Matrix
  30364. case Animation.ANIMATIONTYPE_MATRIX:
  30365. switch (loopMode) {
  30366. case Animation.ANIMATIONLOOPMODE_CYCLE:
  30367. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  30368. if (this.allowMatricesInterpolation) {
  30369. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  30370. }
  30371. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  30372. return startValue;
  30373. }
  30374. default:
  30375. break;
  30376. }
  30377. break;
  30378. }
  30379. }
  30380. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  30381. };
  30382. Animation.prototype.setValue = function (currentValue, blend) {
  30383. if (blend === void 0) { blend = false; }
  30384. // Set value
  30385. var path;
  30386. var destination;
  30387. if (this.targetPropertyPath.length > 1) {
  30388. var property = this._target[this.targetPropertyPath[0]];
  30389. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  30390. property = property[this.targetPropertyPath[index]];
  30391. }
  30392. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  30393. destination = property;
  30394. }
  30395. else {
  30396. path = this.targetPropertyPath[0];
  30397. destination = this._target;
  30398. }
  30399. // Blending
  30400. if (this.enableBlending && this._blendingFactor <= 1.0) {
  30401. if (!this._originalBlendValue) {
  30402. if (destination[path].clone) {
  30403. this._originalBlendValue = destination[path].clone();
  30404. }
  30405. else {
  30406. this._originalBlendValue = destination[path];
  30407. }
  30408. }
  30409. if (this._originalBlendValue.prototype) {
  30410. if (this._originalBlendValue.prototype.Lerp) {
  30411. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  30412. }
  30413. else {
  30414. destination[path] = currentValue;
  30415. }
  30416. }
  30417. else if (this._originalBlendValue.m) {
  30418. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  30419. }
  30420. else {
  30421. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  30422. }
  30423. this._blendingFactor += this.blendingSpeed;
  30424. }
  30425. else {
  30426. destination[path] = currentValue;
  30427. }
  30428. if (this._target.markAsDirty) {
  30429. this._target.markAsDirty(this.targetProperty);
  30430. }
  30431. };
  30432. Animation.prototype.goToFrame = function (frame) {
  30433. if (frame < this._keys[0].frame) {
  30434. frame = this._keys[0].frame;
  30435. }
  30436. else if (frame > this._keys[this._keys.length - 1].frame) {
  30437. frame = this._keys[this._keys.length - 1].frame;
  30438. }
  30439. var currentValue = this._interpolate(frame, 0, this.loopMode);
  30440. this.setValue(currentValue);
  30441. };
  30442. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  30443. if (blend === void 0) { blend = false; }
  30444. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  30445. this._stopped = true;
  30446. return false;
  30447. }
  30448. var returnValue = true;
  30449. // Adding a start key at frame 0 if missing
  30450. if (this._keys[0].frame !== 0) {
  30451. var newKey = { frame: 0, value: this._keys[0].value };
  30452. this._keys.splice(0, 0, newKey);
  30453. }
  30454. // Check limits
  30455. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  30456. from = this._keys[0].frame;
  30457. }
  30458. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  30459. to = this._keys[this._keys.length - 1].frame;
  30460. }
  30461. //to and from cannot be the same key
  30462. if (from === to) {
  30463. from++;
  30464. }
  30465. // Compute ratio
  30466. var range = to - from;
  30467. var offsetValue;
  30468. // ratio represents the frame delta between from and to
  30469. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  30470. var highLimitValue = 0;
  30471. if (ratio > range && !loop) {
  30472. returnValue = false;
  30473. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  30474. }
  30475. else {
  30476. // Get max value if required
  30477. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  30478. var keyOffset = to.toString() + from.toString();
  30479. if (!this._offsetsCache[keyOffset]) {
  30480. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30481. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  30482. switch (this.dataType) {
  30483. // Float
  30484. case Animation.ANIMATIONTYPE_FLOAT:
  30485. this._offsetsCache[keyOffset] = toValue - fromValue;
  30486. break;
  30487. // Quaternion
  30488. case Animation.ANIMATIONTYPE_QUATERNION:
  30489. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30490. break;
  30491. // Vector3
  30492. case Animation.ANIMATIONTYPE_VECTOR3:
  30493. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30494. // Vector2
  30495. case Animation.ANIMATIONTYPE_VECTOR2:
  30496. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30497. // Size
  30498. case Animation.ANIMATIONTYPE_SIZE:
  30499. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30500. // Color3
  30501. case Animation.ANIMATIONTYPE_COLOR3:
  30502. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  30503. default:
  30504. break;
  30505. }
  30506. this._highLimitsCache[keyOffset] = toValue;
  30507. }
  30508. highLimitValue = this._highLimitsCache[keyOffset];
  30509. offsetValue = this._offsetsCache[keyOffset];
  30510. }
  30511. }
  30512. if (offsetValue === undefined) {
  30513. switch (this.dataType) {
  30514. // Float
  30515. case Animation.ANIMATIONTYPE_FLOAT:
  30516. offsetValue = 0;
  30517. break;
  30518. // Quaternion
  30519. case Animation.ANIMATIONTYPE_QUATERNION:
  30520. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  30521. break;
  30522. // Vector3
  30523. case Animation.ANIMATIONTYPE_VECTOR3:
  30524. offsetValue = BABYLON.Vector3.Zero();
  30525. break;
  30526. // Vector2
  30527. case Animation.ANIMATIONTYPE_VECTOR2:
  30528. offsetValue = BABYLON.Vector2.Zero();
  30529. break;
  30530. // Size
  30531. case Animation.ANIMATIONTYPE_SIZE:
  30532. offsetValue = BABYLON.Size.Zero();
  30533. break;
  30534. // Color3
  30535. case Animation.ANIMATIONTYPE_COLOR3:
  30536. offsetValue = BABYLON.Color3.Black();
  30537. }
  30538. }
  30539. // Compute value
  30540. var repeatCount = (ratio / range) >> 0;
  30541. var currentFrame = returnValue ? from + ratio % range : to;
  30542. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  30543. // Set value
  30544. this.setValue(currentValue);
  30545. // Check events
  30546. for (var index = 0; index < this._events.length; index++) {
  30547. if (currentFrame >= this._events[index].frame) {
  30548. var event = this._events[index];
  30549. if (!event.isDone) {
  30550. // If event should be done only once, remove it.
  30551. if (event.onlyOnce) {
  30552. this._events.splice(index, 1);
  30553. index--;
  30554. }
  30555. event.isDone = true;
  30556. event.action();
  30557. } // Don't do anything if the event has already be done.
  30558. }
  30559. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  30560. // reset event, the animation is looping
  30561. this._events[index].isDone = false;
  30562. }
  30563. }
  30564. if (!returnValue) {
  30565. this._stopped = true;
  30566. }
  30567. return returnValue;
  30568. };
  30569. Animation.prototype.serialize = function () {
  30570. var serializationObject = {};
  30571. serializationObject.name = this.name;
  30572. serializationObject.property = this.targetProperty;
  30573. serializationObject.framePerSecond = this.framePerSecond;
  30574. serializationObject.dataType = this.dataType;
  30575. serializationObject.loopBehavior = this.loopMode;
  30576. serializationObject.enableBlending = this.enableBlending;
  30577. serializationObject.blendingSpeed = this.blendingSpeed;
  30578. var dataType = this.dataType;
  30579. serializationObject.keys = [];
  30580. var keys = this.getKeys();
  30581. for (var index = 0; index < keys.length; index++) {
  30582. var animationKey = keys[index];
  30583. var key = {};
  30584. key.frame = animationKey.frame;
  30585. switch (dataType) {
  30586. case Animation.ANIMATIONTYPE_FLOAT:
  30587. key.values = [animationKey.value];
  30588. break;
  30589. case Animation.ANIMATIONTYPE_QUATERNION:
  30590. case Animation.ANIMATIONTYPE_MATRIX:
  30591. case Animation.ANIMATIONTYPE_VECTOR3:
  30592. case Animation.ANIMATIONTYPE_COLOR3:
  30593. key.values = animationKey.value.asArray();
  30594. break;
  30595. }
  30596. serializationObject.keys.push(key);
  30597. }
  30598. serializationObject.ranges = [];
  30599. for (var name in this._ranges) {
  30600. var range = {};
  30601. range.name = name;
  30602. range.from = this._ranges[name].from;
  30603. range.to = this._ranges[name].to;
  30604. serializationObject.ranges.push(range);
  30605. }
  30606. return serializationObject;
  30607. };
  30608. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  30609. get: function () {
  30610. return Animation._ANIMATIONTYPE_FLOAT;
  30611. },
  30612. enumerable: true,
  30613. configurable: true
  30614. });
  30615. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  30616. get: function () {
  30617. return Animation._ANIMATIONTYPE_VECTOR3;
  30618. },
  30619. enumerable: true,
  30620. configurable: true
  30621. });
  30622. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  30623. get: function () {
  30624. return Animation._ANIMATIONTYPE_VECTOR2;
  30625. },
  30626. enumerable: true,
  30627. configurable: true
  30628. });
  30629. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  30630. get: function () {
  30631. return Animation._ANIMATIONTYPE_SIZE;
  30632. },
  30633. enumerable: true,
  30634. configurable: true
  30635. });
  30636. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  30637. get: function () {
  30638. return Animation._ANIMATIONTYPE_QUATERNION;
  30639. },
  30640. enumerable: true,
  30641. configurable: true
  30642. });
  30643. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  30644. get: function () {
  30645. return Animation._ANIMATIONTYPE_MATRIX;
  30646. },
  30647. enumerable: true,
  30648. configurable: true
  30649. });
  30650. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  30651. get: function () {
  30652. return Animation._ANIMATIONTYPE_COLOR3;
  30653. },
  30654. enumerable: true,
  30655. configurable: true
  30656. });
  30657. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  30658. get: function () {
  30659. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  30660. },
  30661. enumerable: true,
  30662. configurable: true
  30663. });
  30664. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  30665. get: function () {
  30666. return Animation._ANIMATIONLOOPMODE_CYCLE;
  30667. },
  30668. enumerable: true,
  30669. configurable: true
  30670. });
  30671. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  30672. get: function () {
  30673. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  30674. },
  30675. enumerable: true,
  30676. configurable: true
  30677. });
  30678. Animation.Parse = function (parsedAnimation) {
  30679. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  30680. var dataType = parsedAnimation.dataType;
  30681. var keys = [];
  30682. var data;
  30683. var index;
  30684. if (parsedAnimation.enableBlending) {
  30685. animation.enableBlending = parsedAnimation.enableBlending;
  30686. }
  30687. if (parsedAnimation.blendingSpeed) {
  30688. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  30689. }
  30690. for (index = 0; index < parsedAnimation.keys.length; index++) {
  30691. var key = parsedAnimation.keys[index];
  30692. switch (dataType) {
  30693. case Animation.ANIMATIONTYPE_FLOAT:
  30694. data = key.values[0];
  30695. break;
  30696. case Animation.ANIMATIONTYPE_QUATERNION:
  30697. data = BABYLON.Quaternion.FromArray(key.values);
  30698. break;
  30699. case Animation.ANIMATIONTYPE_MATRIX:
  30700. data = BABYLON.Matrix.FromArray(key.values);
  30701. break;
  30702. case Animation.ANIMATIONTYPE_COLOR3:
  30703. data = BABYLON.Color3.FromArray(key.values);
  30704. break;
  30705. case Animation.ANIMATIONTYPE_VECTOR3:
  30706. default:
  30707. data = BABYLON.Vector3.FromArray(key.values);
  30708. break;
  30709. }
  30710. keys.push({
  30711. frame: key.frame,
  30712. value: data
  30713. });
  30714. }
  30715. animation.setKeys(keys);
  30716. if (parsedAnimation.ranges) {
  30717. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  30718. data = parsedAnimation.ranges[index];
  30719. animation.createRange(data.name, data.from, data.to);
  30720. }
  30721. }
  30722. return animation;
  30723. };
  30724. Animation.AppendSerializedAnimations = function (source, destination) {
  30725. if (source.animations) {
  30726. destination.animations = [];
  30727. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  30728. var animation = source.animations[animationIndex];
  30729. destination.animations.push(animation.serialize());
  30730. }
  30731. }
  30732. };
  30733. return Animation;
  30734. }());
  30735. // Statics
  30736. Animation._ANIMATIONTYPE_FLOAT = 0;
  30737. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  30738. Animation._ANIMATIONTYPE_QUATERNION = 2;
  30739. Animation._ANIMATIONTYPE_MATRIX = 3;
  30740. Animation._ANIMATIONTYPE_COLOR3 = 4;
  30741. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  30742. Animation._ANIMATIONTYPE_SIZE = 6;
  30743. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  30744. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  30745. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  30746. BABYLON.Animation = Animation;
  30747. })(BABYLON || (BABYLON = {}));
  30748. //# sourceMappingURL=babylon.animation.js.map
  30749. var BABYLON;
  30750. (function (BABYLON) {
  30751. var Animatable = (function () {
  30752. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  30753. if (fromFrame === void 0) { fromFrame = 0; }
  30754. if (toFrame === void 0) { toFrame = 100; }
  30755. if (loopAnimation === void 0) { loopAnimation = false; }
  30756. if (speedRatio === void 0) { speedRatio = 1.0; }
  30757. this.target = target;
  30758. this.fromFrame = fromFrame;
  30759. this.toFrame = toFrame;
  30760. this.loopAnimation = loopAnimation;
  30761. this.speedRatio = speedRatio;
  30762. this.onAnimationEnd = onAnimationEnd;
  30763. this._animations = new Array();
  30764. this._paused = false;
  30765. this.animationStarted = false;
  30766. if (animations) {
  30767. this.appendAnimations(target, animations);
  30768. }
  30769. this._scene = scene;
  30770. scene._activeAnimatables.push(this);
  30771. }
  30772. // Methods
  30773. Animatable.prototype.getAnimations = function () {
  30774. return this._animations;
  30775. };
  30776. Animatable.prototype.appendAnimations = function (target, animations) {
  30777. for (var index = 0; index < animations.length; index++) {
  30778. var animation = animations[index];
  30779. animation._target = target;
  30780. this._animations.push(animation);
  30781. }
  30782. };
  30783. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  30784. var animations = this._animations;
  30785. for (var index = 0; index < animations.length; index++) {
  30786. if (animations[index].targetProperty === property) {
  30787. return animations[index];
  30788. }
  30789. }
  30790. return null;
  30791. };
  30792. Animatable.prototype.reset = function () {
  30793. var animations = this._animations;
  30794. for (var index = 0; index < animations.length; index++) {
  30795. animations[index].reset();
  30796. }
  30797. this._localDelayOffset = null;
  30798. this._pausedDelay = null;
  30799. };
  30800. Animatable.prototype.enableBlending = function (blendingSpeed) {
  30801. var animations = this._animations;
  30802. for (var index = 0; index < animations.length; index++) {
  30803. animations[index].enableBlending = true;
  30804. animations[index].blendingSpeed = blendingSpeed;
  30805. }
  30806. };
  30807. Animatable.prototype.disableBlending = function () {
  30808. var animations = this._animations;
  30809. for (var index = 0; index < animations.length; index++) {
  30810. animations[index].enableBlending = false;
  30811. }
  30812. };
  30813. Animatable.prototype.goToFrame = function (frame) {
  30814. var animations = this._animations;
  30815. if (animations[0]) {
  30816. var fps = animations[0].framePerSecond;
  30817. var currentFrame = animations[0].currentFrame;
  30818. var adjustTime = frame - currentFrame;
  30819. var delay = adjustTime * 1000 / fps;
  30820. this._localDelayOffset -= delay;
  30821. }
  30822. for (var index = 0; index < animations.length; index++) {
  30823. animations[index].goToFrame(frame);
  30824. }
  30825. };
  30826. Animatable.prototype.pause = function () {
  30827. if (this._paused) {
  30828. return;
  30829. }
  30830. this._paused = true;
  30831. };
  30832. Animatable.prototype.restart = function () {
  30833. this._paused = false;
  30834. };
  30835. Animatable.prototype.stop = function (animationName) {
  30836. if (animationName) {
  30837. var idx = this._scene._activeAnimatables.indexOf(this);
  30838. if (idx > -1) {
  30839. var animations = this._animations;
  30840. for (var index = animations.length - 1; index >= 0; index--) {
  30841. if (typeof animationName === "string" && animations[index].name != animationName) {
  30842. continue;
  30843. }
  30844. animations[index].reset();
  30845. animations.splice(index, 1);
  30846. }
  30847. if (animations.length == 0) {
  30848. this._scene._activeAnimatables.splice(idx, 1);
  30849. if (this.onAnimationEnd) {
  30850. this.onAnimationEnd();
  30851. }
  30852. }
  30853. }
  30854. }
  30855. else {
  30856. var index = this._scene._activeAnimatables.indexOf(this);
  30857. if (index > -1) {
  30858. this._scene._activeAnimatables.splice(index, 1);
  30859. var animations = this._animations;
  30860. for (var index = 0; index < animations.length; index++) {
  30861. animations[index].reset();
  30862. }
  30863. if (this.onAnimationEnd) {
  30864. this.onAnimationEnd();
  30865. }
  30866. }
  30867. }
  30868. };
  30869. Animatable.prototype._animate = function (delay) {
  30870. if (this._paused) {
  30871. this.animationStarted = false;
  30872. if (!this._pausedDelay) {
  30873. this._pausedDelay = delay;
  30874. }
  30875. return true;
  30876. }
  30877. if (!this._localDelayOffset) {
  30878. this._localDelayOffset = delay;
  30879. }
  30880. else if (this._pausedDelay) {
  30881. this._localDelayOffset += delay - this._pausedDelay;
  30882. this._pausedDelay = null;
  30883. }
  30884. // Animating
  30885. var running = false;
  30886. var animations = this._animations;
  30887. var index;
  30888. for (index = 0; index < animations.length; index++) {
  30889. var animation = animations[index];
  30890. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  30891. running = running || isRunning;
  30892. }
  30893. this.animationStarted = running;
  30894. if (!running) {
  30895. // Remove from active animatables
  30896. index = this._scene._activeAnimatables.indexOf(this);
  30897. this._scene._activeAnimatables.splice(index, 1);
  30898. }
  30899. if (!running && this.onAnimationEnd) {
  30900. this.onAnimationEnd();
  30901. this.onAnimationEnd = null;
  30902. }
  30903. return running;
  30904. };
  30905. return Animatable;
  30906. }());
  30907. BABYLON.Animatable = Animatable;
  30908. })(BABYLON || (BABYLON = {}));
  30909. //# sourceMappingURL=babylon.animatable.js.map
  30910. var BABYLON;
  30911. (function (BABYLON) {
  30912. var EasingFunction = (function () {
  30913. function EasingFunction() {
  30914. // Properties
  30915. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  30916. }
  30917. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  30918. get: function () {
  30919. return EasingFunction._EASINGMODE_EASEIN;
  30920. },
  30921. enumerable: true,
  30922. configurable: true
  30923. });
  30924. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  30925. get: function () {
  30926. return EasingFunction._EASINGMODE_EASEOUT;
  30927. },
  30928. enumerable: true,
  30929. configurable: true
  30930. });
  30931. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  30932. get: function () {
  30933. return EasingFunction._EASINGMODE_EASEINOUT;
  30934. },
  30935. enumerable: true,
  30936. configurable: true
  30937. });
  30938. EasingFunction.prototype.setEasingMode = function (easingMode) {
  30939. var n = Math.min(Math.max(easingMode, 0), 2);
  30940. this._easingMode = n;
  30941. };
  30942. EasingFunction.prototype.getEasingMode = function () {
  30943. return this._easingMode;
  30944. };
  30945. EasingFunction.prototype.easeInCore = function (gradient) {
  30946. throw new Error('You must implement this method');
  30947. };
  30948. EasingFunction.prototype.ease = function (gradient) {
  30949. switch (this._easingMode) {
  30950. case EasingFunction.EASINGMODE_EASEIN:
  30951. return this.easeInCore(gradient);
  30952. case EasingFunction.EASINGMODE_EASEOUT:
  30953. return (1 - this.easeInCore(1 - gradient));
  30954. }
  30955. if (gradient >= 0.5) {
  30956. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  30957. }
  30958. return (this.easeInCore(gradient * 2) * 0.5);
  30959. };
  30960. return EasingFunction;
  30961. }());
  30962. //Statics
  30963. EasingFunction._EASINGMODE_EASEIN = 0;
  30964. EasingFunction._EASINGMODE_EASEOUT = 1;
  30965. EasingFunction._EASINGMODE_EASEINOUT = 2;
  30966. BABYLON.EasingFunction = EasingFunction;
  30967. var CircleEase = (function (_super) {
  30968. __extends(CircleEase, _super);
  30969. function CircleEase() {
  30970. return _super.apply(this, arguments) || this;
  30971. }
  30972. CircleEase.prototype.easeInCore = function (gradient) {
  30973. gradient = Math.max(0, Math.min(1, gradient));
  30974. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  30975. };
  30976. return CircleEase;
  30977. }(EasingFunction));
  30978. BABYLON.CircleEase = CircleEase;
  30979. var BackEase = (function (_super) {
  30980. __extends(BackEase, _super);
  30981. function BackEase(amplitude) {
  30982. if (amplitude === void 0) { amplitude = 1; }
  30983. var _this = _super.call(this) || this;
  30984. _this.amplitude = amplitude;
  30985. return _this;
  30986. }
  30987. BackEase.prototype.easeInCore = function (gradient) {
  30988. var num = Math.max(0, this.amplitude);
  30989. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  30990. };
  30991. return BackEase;
  30992. }(EasingFunction));
  30993. BABYLON.BackEase = BackEase;
  30994. var BounceEase = (function (_super) {
  30995. __extends(BounceEase, _super);
  30996. function BounceEase(bounces, bounciness) {
  30997. if (bounces === void 0) { bounces = 3; }
  30998. if (bounciness === void 0) { bounciness = 2; }
  30999. var _this = _super.call(this) || this;
  31000. _this.bounces = bounces;
  31001. _this.bounciness = bounciness;
  31002. return _this;
  31003. }
  31004. BounceEase.prototype.easeInCore = function (gradient) {
  31005. var y = Math.max(0.0, this.bounces);
  31006. var bounciness = this.bounciness;
  31007. if (bounciness <= 1.0) {
  31008. bounciness = 1.001;
  31009. }
  31010. var num9 = Math.pow(bounciness, y);
  31011. var num5 = 1.0 - bounciness;
  31012. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  31013. var num15 = gradient * num4;
  31014. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  31015. var num3 = Math.floor(num65);
  31016. var num13 = num3 + 1.0;
  31017. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  31018. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  31019. var num7 = (num8 + num12) * 0.5;
  31020. var num6 = gradient - num7;
  31021. var num2 = num7 - num8;
  31022. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  31023. };
  31024. return BounceEase;
  31025. }(EasingFunction));
  31026. BABYLON.BounceEase = BounceEase;
  31027. var CubicEase = (function (_super) {
  31028. __extends(CubicEase, _super);
  31029. function CubicEase() {
  31030. return _super.apply(this, arguments) || this;
  31031. }
  31032. CubicEase.prototype.easeInCore = function (gradient) {
  31033. return (gradient * gradient * gradient);
  31034. };
  31035. return CubicEase;
  31036. }(EasingFunction));
  31037. BABYLON.CubicEase = CubicEase;
  31038. var ElasticEase = (function (_super) {
  31039. __extends(ElasticEase, _super);
  31040. function ElasticEase(oscillations, springiness) {
  31041. if (oscillations === void 0) { oscillations = 3; }
  31042. if (springiness === void 0) { springiness = 3; }
  31043. var _this = _super.call(this) || this;
  31044. _this.oscillations = oscillations;
  31045. _this.springiness = springiness;
  31046. return _this;
  31047. }
  31048. ElasticEase.prototype.easeInCore = function (gradient) {
  31049. var num2;
  31050. var num3 = Math.max(0.0, this.oscillations);
  31051. var num = Math.max(0.0, this.springiness);
  31052. if (num == 0) {
  31053. num2 = gradient;
  31054. }
  31055. else {
  31056. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  31057. }
  31058. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  31059. };
  31060. return ElasticEase;
  31061. }(EasingFunction));
  31062. BABYLON.ElasticEase = ElasticEase;
  31063. var ExponentialEase = (function (_super) {
  31064. __extends(ExponentialEase, _super);
  31065. function ExponentialEase(exponent) {
  31066. if (exponent === void 0) { exponent = 2; }
  31067. var _this = _super.call(this) || this;
  31068. _this.exponent = exponent;
  31069. return _this;
  31070. }
  31071. ExponentialEase.prototype.easeInCore = function (gradient) {
  31072. if (this.exponent <= 0) {
  31073. return gradient;
  31074. }
  31075. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  31076. };
  31077. return ExponentialEase;
  31078. }(EasingFunction));
  31079. BABYLON.ExponentialEase = ExponentialEase;
  31080. var PowerEase = (function (_super) {
  31081. __extends(PowerEase, _super);
  31082. function PowerEase(power) {
  31083. if (power === void 0) { power = 2; }
  31084. var _this = _super.call(this) || this;
  31085. _this.power = power;
  31086. return _this;
  31087. }
  31088. PowerEase.prototype.easeInCore = function (gradient) {
  31089. var y = Math.max(0.0, this.power);
  31090. return Math.pow(gradient, y);
  31091. };
  31092. return PowerEase;
  31093. }(EasingFunction));
  31094. BABYLON.PowerEase = PowerEase;
  31095. var QuadraticEase = (function (_super) {
  31096. __extends(QuadraticEase, _super);
  31097. function QuadraticEase() {
  31098. return _super.apply(this, arguments) || this;
  31099. }
  31100. QuadraticEase.prototype.easeInCore = function (gradient) {
  31101. return (gradient * gradient);
  31102. };
  31103. return QuadraticEase;
  31104. }(EasingFunction));
  31105. BABYLON.QuadraticEase = QuadraticEase;
  31106. var QuarticEase = (function (_super) {
  31107. __extends(QuarticEase, _super);
  31108. function QuarticEase() {
  31109. return _super.apply(this, arguments) || this;
  31110. }
  31111. QuarticEase.prototype.easeInCore = function (gradient) {
  31112. return (gradient * gradient * gradient * gradient);
  31113. };
  31114. return QuarticEase;
  31115. }(EasingFunction));
  31116. BABYLON.QuarticEase = QuarticEase;
  31117. var QuinticEase = (function (_super) {
  31118. __extends(QuinticEase, _super);
  31119. function QuinticEase() {
  31120. return _super.apply(this, arguments) || this;
  31121. }
  31122. QuinticEase.prototype.easeInCore = function (gradient) {
  31123. return (gradient * gradient * gradient * gradient * gradient);
  31124. };
  31125. return QuinticEase;
  31126. }(EasingFunction));
  31127. BABYLON.QuinticEase = QuinticEase;
  31128. var SineEase = (function (_super) {
  31129. __extends(SineEase, _super);
  31130. function SineEase() {
  31131. return _super.apply(this, arguments) || this;
  31132. }
  31133. SineEase.prototype.easeInCore = function (gradient) {
  31134. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  31135. };
  31136. return SineEase;
  31137. }(EasingFunction));
  31138. BABYLON.SineEase = SineEase;
  31139. var BezierCurveEase = (function (_super) {
  31140. __extends(BezierCurveEase, _super);
  31141. function BezierCurveEase(x1, y1, x2, y2) {
  31142. if (x1 === void 0) { x1 = 0; }
  31143. if (y1 === void 0) { y1 = 0; }
  31144. if (x2 === void 0) { x2 = 1; }
  31145. if (y2 === void 0) { y2 = 1; }
  31146. var _this = _super.call(this) || this;
  31147. _this.x1 = x1;
  31148. _this.y1 = y1;
  31149. _this.x2 = x2;
  31150. _this.y2 = y2;
  31151. return _this;
  31152. }
  31153. BezierCurveEase.prototype.easeInCore = function (gradient) {
  31154. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  31155. };
  31156. return BezierCurveEase;
  31157. }(EasingFunction));
  31158. BABYLON.BezierCurveEase = BezierCurveEase;
  31159. })(BABYLON || (BABYLON = {}));
  31160. //# sourceMappingURL=babylon.easing.js.map
  31161. var BABYLON;
  31162. (function (BABYLON) {
  31163. var Bone = (function (_super) {
  31164. __extends(Bone, _super);
  31165. function Bone(name, skeleton, parentBone, matrix, restPose) {
  31166. var _this = _super.call(this, name, skeleton.getScene()) || this;
  31167. _this.name = name;
  31168. _this.children = new Array();
  31169. _this.animations = new Array();
  31170. _this._worldTransform = new BABYLON.Matrix();
  31171. _this._absoluteTransform = new BABYLON.Matrix();
  31172. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  31173. _this._scaleMatrix = BABYLON.Matrix.Identity();
  31174. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  31175. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  31176. _this._scalingDeterminant = 1;
  31177. _this._syncScaleVector = function () {
  31178. var lm = this.getLocalMatrix();
  31179. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  31180. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  31181. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  31182. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  31183. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  31184. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  31185. this._scaleVector.x = xs * Math.sqrt(xsq);
  31186. this._scaleVector.y = ys * Math.sqrt(ysq);
  31187. this._scaleVector.z = zs * Math.sqrt(zsq);
  31188. if (this._parent) {
  31189. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  31190. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  31191. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  31192. }
  31193. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  31194. };
  31195. _this._skeleton = skeleton;
  31196. _this._matrix = matrix;
  31197. _this._baseMatrix = matrix;
  31198. _this._restPose = restPose ? restPose : matrix.clone();
  31199. skeleton.bones.push(_this);
  31200. if (parentBone) {
  31201. _this._parent = parentBone;
  31202. parentBone.children.push(_this);
  31203. }
  31204. else {
  31205. _this._parent = null;
  31206. }
  31207. _this._updateDifferenceMatrix();
  31208. if (_this.getAbsoluteTransform().determinant() < 0) {
  31209. _this._scalingDeterminant *= -1;
  31210. }
  31211. return _this;
  31212. }
  31213. // Members
  31214. Bone.prototype.getParent = function () {
  31215. return this._parent;
  31216. };
  31217. Bone.prototype.getLocalMatrix = function () {
  31218. return this._matrix;
  31219. };
  31220. Bone.prototype.getBaseMatrix = function () {
  31221. return this._baseMatrix;
  31222. };
  31223. Bone.prototype.getRestPose = function () {
  31224. return this._restPose;
  31225. };
  31226. Bone.prototype.returnToRest = function () {
  31227. this.updateMatrix(this._restPose.clone());
  31228. };
  31229. Bone.prototype.getWorldMatrix = function () {
  31230. return this._worldTransform;
  31231. };
  31232. Bone.prototype.getInvertedAbsoluteTransform = function () {
  31233. return this._invertedAbsoluteTransform;
  31234. };
  31235. Bone.prototype.getAbsoluteTransform = function () {
  31236. return this._absoluteTransform;
  31237. };
  31238. // Methods
  31239. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  31240. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  31241. this._baseMatrix = matrix.clone();
  31242. this._matrix = matrix.clone();
  31243. this._skeleton._markAsDirty();
  31244. if (updateDifferenceMatrix) {
  31245. this._updateDifferenceMatrix();
  31246. }
  31247. };
  31248. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  31249. if (!rootMatrix) {
  31250. rootMatrix = this._baseMatrix;
  31251. }
  31252. if (this._parent) {
  31253. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  31254. }
  31255. else {
  31256. this._absoluteTransform.copyFrom(rootMatrix);
  31257. }
  31258. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  31259. for (var index = 0; index < this.children.length; index++) {
  31260. this.children[index]._updateDifferenceMatrix();
  31261. }
  31262. };
  31263. Bone.prototype.markAsDirty = function () {
  31264. this._currentRenderId++;
  31265. this._skeleton._markAsDirty();
  31266. };
  31267. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  31268. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31269. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  31270. // all animation may be coming from a library skeleton, so may need to create animation
  31271. if (this.animations.length === 0) {
  31272. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  31273. this.animations[0].setKeys([]);
  31274. }
  31275. // get animation info / verify there is such a range from the source bone
  31276. var sourceRange = source.animations[0].getRange(rangeName);
  31277. if (!sourceRange) {
  31278. return false;
  31279. }
  31280. var from = sourceRange.from;
  31281. var to = sourceRange.to;
  31282. var sourceKeys = source.animations[0].getKeys();
  31283. // rescaling prep
  31284. var sourceBoneLength = source.length;
  31285. var sourceParent = source.getParent();
  31286. var parent = this.getParent();
  31287. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  31288. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  31289. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  31290. var destKeys = this.animations[0].getKeys();
  31291. // loop vars declaration
  31292. var orig;
  31293. var origTranslation;
  31294. var mat;
  31295. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  31296. orig = sourceKeys[key];
  31297. if (orig.frame >= from && orig.frame <= to) {
  31298. if (rescaleAsRequired) {
  31299. mat = orig.value.clone();
  31300. // scale based on parent ratio, when bone has parent
  31301. if (parentScalingReqd) {
  31302. origTranslation = mat.getTranslation();
  31303. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  31304. }
  31305. else if (dimensionsScalingReqd) {
  31306. origTranslation = mat.getTranslation();
  31307. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  31308. }
  31309. else {
  31310. mat = orig.value;
  31311. }
  31312. }
  31313. else {
  31314. mat = orig.value;
  31315. }
  31316. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  31317. }
  31318. }
  31319. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  31320. return true;
  31321. };
  31322. Bone.prototype.translate = function (vec, space, mesh) {
  31323. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31324. var lm = this.getLocalMatrix();
  31325. if (space == BABYLON.Space.LOCAL) {
  31326. lm.m[12] += vec.x;
  31327. lm.m[13] += vec.y;
  31328. lm.m[14] += vec.z;
  31329. }
  31330. else {
  31331. this._skeleton.computeAbsoluteTransforms();
  31332. var tmat = BABYLON.Tmp.Matrix[0];
  31333. var tvec = BABYLON.Tmp.Vector3[0];
  31334. if (mesh) {
  31335. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31336. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31337. }
  31338. else {
  31339. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31340. }
  31341. tmat.m[12] = 0;
  31342. tmat.m[13] = 0;
  31343. tmat.m[14] = 0;
  31344. tmat.invert();
  31345. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  31346. lm.m[12] += tvec.x;
  31347. lm.m[13] += tvec.y;
  31348. lm.m[14] += tvec.z;
  31349. }
  31350. this.markAsDirty();
  31351. };
  31352. Bone.prototype.setPosition = function (position, space, mesh) {
  31353. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31354. var lm = this.getLocalMatrix();
  31355. if (space == BABYLON.Space.LOCAL) {
  31356. lm.m[12] = position.x;
  31357. lm.m[13] = position.y;
  31358. lm.m[14] = position.z;
  31359. }
  31360. else {
  31361. this._skeleton.computeAbsoluteTransforms();
  31362. var tmat = BABYLON.Tmp.Matrix[0];
  31363. var vec = BABYLON.Tmp.Vector3[0];
  31364. if (mesh) {
  31365. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31366. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31367. }
  31368. else {
  31369. tmat.copyFrom(this._parent.getAbsoluteTransform());
  31370. }
  31371. tmat.invert();
  31372. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  31373. lm.m[12] = vec.x;
  31374. lm.m[13] = vec.y;
  31375. lm.m[14] = vec.z;
  31376. }
  31377. this.markAsDirty();
  31378. };
  31379. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  31380. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  31381. };
  31382. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  31383. if (scaleChildren === void 0) { scaleChildren = false; }
  31384. if (this.animations[0] && !this.animations[0].isStopped()) {
  31385. if (!scaleChildren) {
  31386. this._negateScaleChildren.x = 1 / x;
  31387. this._negateScaleChildren.y = 1 / y;
  31388. this._negateScaleChildren.z = 1 / z;
  31389. }
  31390. this._syncScaleVector();
  31391. }
  31392. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  31393. };
  31394. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  31395. if (scaleChildren === void 0) { scaleChildren = false; }
  31396. var locMat = this.getLocalMatrix();
  31397. var origLocMat = BABYLON.Tmp.Matrix[0];
  31398. origLocMat.copyFrom(locMat);
  31399. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  31400. origLocMatInv.copyFrom(origLocMat);
  31401. origLocMatInv.invert();
  31402. var scaleMat = BABYLON.Tmp.Matrix[2];
  31403. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  31404. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  31405. this._scaleVector.x *= x;
  31406. this._scaleVector.y *= y;
  31407. this._scaleVector.z *= z;
  31408. locMat.multiplyToRef(origLocMatInv, locMat);
  31409. locMat.multiplyToRef(scaleMat, locMat);
  31410. locMat.multiplyToRef(origLocMat, locMat);
  31411. var parent = this.getParent();
  31412. if (parent) {
  31413. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  31414. }
  31415. else {
  31416. this.getAbsoluteTransform().copyFrom(locMat);
  31417. }
  31418. var len = this.children.length;
  31419. scaleMat.invert();
  31420. for (var i = 0; i < len; i++) {
  31421. var child = this.children[i];
  31422. var cm = child.getLocalMatrix();
  31423. cm.multiplyToRef(scaleMat, cm);
  31424. var lm = child.getLocalMatrix();
  31425. lm.m[12] *= x;
  31426. lm.m[13] *= y;
  31427. lm.m[14] *= z;
  31428. }
  31429. this.computeAbsoluteTransforms();
  31430. if (scaleChildren) {
  31431. for (var i = 0; i < len; i++) {
  31432. this.children[i].scale(x, y, z, scaleChildren);
  31433. }
  31434. }
  31435. this.markAsDirty();
  31436. };
  31437. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  31438. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31439. var rotMat = BABYLON.Tmp.Matrix[0];
  31440. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  31441. var rotMatInv = BABYLON.Tmp.Matrix[1];
  31442. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31443. rotMatInv.multiplyToRef(rotMat, rotMat);
  31444. this._rotateWithMatrix(rotMat, space, mesh);
  31445. };
  31446. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  31447. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31448. var rmat = BABYLON.Tmp.Matrix[0];
  31449. rmat.m[12] = 0;
  31450. rmat.m[13] = 0;
  31451. rmat.m[14] = 0;
  31452. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  31453. this._rotateWithMatrix(rmat, space, mesh);
  31454. };
  31455. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  31456. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31457. var rotMat = BABYLON.Tmp.Matrix[0];
  31458. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  31459. var rotMatInv = BABYLON.Tmp.Matrix[1];
  31460. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31461. rotMatInv.multiplyToRef(rotMat, rotMat);
  31462. this._rotateWithMatrix(rotMat, space, mesh);
  31463. };
  31464. Bone.prototype.setRotation = function (rotation, space, mesh) {
  31465. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31466. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  31467. };
  31468. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  31469. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31470. var rotMatInv = BABYLON.Tmp.Matrix[0];
  31471. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31472. var rotMat = BABYLON.Tmp.Matrix[1];
  31473. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  31474. rotMatInv.multiplyToRef(rotMat, rotMat);
  31475. this._rotateWithMatrix(rotMat, space, mesh);
  31476. };
  31477. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  31478. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31479. var rotMatInv = BABYLON.Tmp.Matrix[0];
  31480. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  31481. var rotMat2 = BABYLON.Tmp.Matrix[1];
  31482. rotMat2.copyFrom(rotMat);
  31483. rotMatInv.multiplyToRef(rotMat, rotMat2);
  31484. this._rotateWithMatrix(rotMat2, space, mesh);
  31485. };
  31486. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  31487. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31488. var lmat = this.getLocalMatrix();
  31489. var lx = lmat.m[12];
  31490. var ly = lmat.m[13];
  31491. var lz = lmat.m[14];
  31492. var parent = this.getParent();
  31493. var parentScale = BABYLON.Tmp.Matrix[3];
  31494. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  31495. if (parent) {
  31496. if (space == BABYLON.Space.WORLD) {
  31497. if (mesh) {
  31498. parentScale.copyFrom(mesh.getWorldMatrix());
  31499. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  31500. }
  31501. else {
  31502. parentScale.copyFrom(parent.getAbsoluteTransform());
  31503. }
  31504. }
  31505. else {
  31506. parentScale = parent._scaleMatrix;
  31507. }
  31508. parentScaleInv.copyFrom(parentScale);
  31509. parentScaleInv.invert();
  31510. lmat.multiplyToRef(parentScale, lmat);
  31511. lmat.multiplyToRef(rmat, lmat);
  31512. lmat.multiplyToRef(parentScaleInv, lmat);
  31513. }
  31514. else {
  31515. if (space == BABYLON.Space.WORLD && mesh) {
  31516. parentScale.copyFrom(mesh.getWorldMatrix());
  31517. parentScaleInv.copyFrom(parentScale);
  31518. parentScaleInv.invert();
  31519. lmat.multiplyToRef(parentScale, lmat);
  31520. lmat.multiplyToRef(rmat, lmat);
  31521. lmat.multiplyToRef(parentScaleInv, lmat);
  31522. }
  31523. else {
  31524. lmat.multiplyToRef(rmat, lmat);
  31525. }
  31526. }
  31527. lmat.m[12] = lx;
  31528. lmat.m[13] = ly;
  31529. lmat.m[14] = lz;
  31530. this.computeAbsoluteTransforms();
  31531. this.markAsDirty();
  31532. };
  31533. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  31534. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31535. if (space == BABYLON.Space.WORLD) {
  31536. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  31537. scaleMatrix.copyFrom(this._scaleMatrix);
  31538. rotMatInv.copyFrom(this.getAbsoluteTransform());
  31539. if (mesh) {
  31540. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  31541. var meshScale = BABYLON.Tmp.Matrix[3];
  31542. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  31543. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  31544. }
  31545. rotMatInv.invert();
  31546. scaleMatrix.m[0] *= this._scalingDeterminant;
  31547. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  31548. }
  31549. else {
  31550. rotMatInv.copyFrom(this.getLocalMatrix());
  31551. rotMatInv.invert();
  31552. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  31553. scaleMatrix.copyFrom(this._scaleMatrix);
  31554. if (this._parent) {
  31555. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  31556. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  31557. pscaleMatrix.invert();
  31558. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  31559. }
  31560. else {
  31561. scaleMatrix.m[0] *= this._scalingDeterminant;
  31562. }
  31563. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  31564. }
  31565. };
  31566. Bone.prototype.getScale = function () {
  31567. return this._scaleVector.clone();
  31568. };
  31569. Bone.prototype.getScaleToRef = function (result) {
  31570. result.copyFrom(this._scaleVector);
  31571. };
  31572. Bone.prototype.getPosition = function (space, mesh) {
  31573. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31574. var pos = BABYLON.Vector3.Zero();
  31575. this.getPositionToRef(space, mesh, pos);
  31576. return pos;
  31577. };
  31578. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  31579. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31580. if (space == BABYLON.Space.LOCAL) {
  31581. var lm = this.getLocalMatrix();
  31582. result.x = lm.m[12];
  31583. result.y = lm.m[13];
  31584. result.z = lm.m[14];
  31585. }
  31586. else {
  31587. this._skeleton.computeAbsoluteTransforms();
  31588. var tmat = BABYLON.Tmp.Matrix[0];
  31589. if (mesh) {
  31590. tmat.copyFrom(this.getAbsoluteTransform());
  31591. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31592. }
  31593. else {
  31594. tmat = this.getAbsoluteTransform();
  31595. }
  31596. result.x = tmat.m[12];
  31597. result.y = tmat.m[13];
  31598. result.z = tmat.m[14];
  31599. }
  31600. };
  31601. Bone.prototype.getAbsolutePosition = function (mesh) {
  31602. var pos = BABYLON.Vector3.Zero();
  31603. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  31604. return pos;
  31605. };
  31606. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  31607. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  31608. };
  31609. Bone.prototype.computeAbsoluteTransforms = function () {
  31610. if (this._parent) {
  31611. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  31612. }
  31613. else {
  31614. this._absoluteTransform.copyFrom(this._matrix);
  31615. var poseMatrix = this._skeleton.getPoseMatrix();
  31616. if (poseMatrix) {
  31617. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  31618. }
  31619. }
  31620. var children = this.children;
  31621. var len = children.length;
  31622. for (var i = 0; i < len; i++) {
  31623. children[i].computeAbsoluteTransforms();
  31624. }
  31625. };
  31626. Bone.prototype.getDirection = function (localAxis, mesh) {
  31627. var result = BABYLON.Vector3.Zero();
  31628. this.getDirectionToRef(localAxis, mesh, result);
  31629. return result;
  31630. };
  31631. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  31632. this._skeleton.computeAbsoluteTransforms();
  31633. var mat = BABYLON.Tmp.Matrix[0];
  31634. mat.copyFrom(this.getAbsoluteTransform());
  31635. if (mesh) {
  31636. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31637. }
  31638. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  31639. result.normalize();
  31640. };
  31641. Bone.prototype.getRotation = function (space, mesh) {
  31642. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31643. var result = BABYLON.Vector3.Zero();
  31644. this.getRotationToRef(space, mesh, result);
  31645. return result;
  31646. };
  31647. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  31648. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31649. var quat = BABYLON.Tmp.Quaternion[0];
  31650. this.getRotationQuaternionToRef(space, mesh, quat);
  31651. quat.toEulerAnglesToRef(result);
  31652. };
  31653. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  31654. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31655. var result = BABYLON.Quaternion.Identity();
  31656. this.getRotationQuaternionToRef(space, mesh, result);
  31657. return result;
  31658. };
  31659. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  31660. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31661. if (space == BABYLON.Space.LOCAL) {
  31662. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  31663. }
  31664. else {
  31665. var mat = BABYLON.Tmp.Matrix[0];
  31666. var amat = this.getAbsoluteTransform();
  31667. if (mesh) {
  31668. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31669. }
  31670. else {
  31671. mat.copyFrom(amat);
  31672. }
  31673. mat.m[0] *= this._scalingDeterminant;
  31674. mat.m[1] *= this._scalingDeterminant;
  31675. mat.m[2] *= this._scalingDeterminant;
  31676. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  31677. }
  31678. };
  31679. Bone.prototype.getRotationMatrix = function (space, mesh) {
  31680. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31681. var result = BABYLON.Matrix.Identity();
  31682. this.getRotationMatrixToRef(space, mesh, result);
  31683. return result;
  31684. };
  31685. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  31686. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  31687. if (space == BABYLON.Space.LOCAL) {
  31688. this.getLocalMatrix().getRotationMatrixToRef(result);
  31689. }
  31690. else {
  31691. var mat = BABYLON.Tmp.Matrix[0];
  31692. var amat = this.getAbsoluteTransform();
  31693. if (mesh) {
  31694. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  31695. }
  31696. else {
  31697. mat.copyFrom(amat);
  31698. }
  31699. mat.m[0] *= this._scalingDeterminant;
  31700. mat.m[1] *= this._scalingDeterminant;
  31701. mat.m[2] *= this._scalingDeterminant;
  31702. mat.getRotationMatrixToRef(result);
  31703. }
  31704. };
  31705. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  31706. var result = BABYLON.Vector3.Zero();
  31707. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  31708. return result;
  31709. };
  31710. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  31711. this._skeleton.computeAbsoluteTransforms();
  31712. var tmat = BABYLON.Tmp.Matrix[0];
  31713. if (mesh) {
  31714. tmat.copyFrom(this.getAbsoluteTransform());
  31715. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31716. }
  31717. else {
  31718. tmat = this.getAbsoluteTransform();
  31719. }
  31720. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  31721. };
  31722. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  31723. var result = BABYLON.Vector3.Zero();
  31724. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  31725. return result;
  31726. };
  31727. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  31728. this._skeleton.computeAbsoluteTransforms();
  31729. var tmat = BABYLON.Tmp.Matrix[0];
  31730. tmat.copyFrom(this.getAbsoluteTransform());
  31731. if (mesh) {
  31732. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  31733. }
  31734. tmat.invert();
  31735. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  31736. };
  31737. return Bone;
  31738. }(BABYLON.Node));
  31739. BABYLON.Bone = Bone;
  31740. })(BABYLON || (BABYLON = {}));
  31741. //# sourceMappingURL=babylon.bone.js.map
  31742. var BABYLON;
  31743. (function (BABYLON) {
  31744. var BoneIKController = (function () {
  31745. function BoneIKController(mesh, bone, options) {
  31746. this.targetPosition = BABYLON.Vector3.Zero();
  31747. this.poleTargetPosition = BABYLON.Vector3.Zero();
  31748. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  31749. this.poleAngle = 0;
  31750. this.slerpAmount = 1;
  31751. this._bone1Quat = BABYLON.Quaternion.Identity();
  31752. this._bone1Mat = BABYLON.Matrix.Identity();
  31753. this._bone2Ang = Math.PI;
  31754. this._maxAngle = Math.PI;
  31755. this._tmpVec1 = BABYLON.Vector3.Zero();
  31756. this._tmpVec2 = BABYLON.Vector3.Zero();
  31757. this._tmpVec3 = BABYLON.Vector3.Zero();
  31758. this._tmpVec4 = BABYLON.Vector3.Zero();
  31759. this._tmpVec5 = BABYLON.Vector3.Zero();
  31760. this._tmpMat1 = BABYLON.Matrix.Identity();
  31761. this._tmpMat2 = BABYLON.Matrix.Identity();
  31762. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  31763. this._rightHandedSystem = false;
  31764. this._bendAxis = BABYLON.Vector3.Right();
  31765. this._slerping = false;
  31766. this._bone2 = bone;
  31767. this._bone1 = bone.getParent();
  31768. this.mesh = mesh;
  31769. if (bone.getAbsoluteTransform().determinant() > 0) {
  31770. this._rightHandedSystem = true;
  31771. this._bendAxis.x = 0;
  31772. this._bendAxis.y = 0;
  31773. this._bendAxis.z = 1;
  31774. }
  31775. if (this._bone1.length) {
  31776. var boneScale1 = this._bone1.getScale();
  31777. var boneScale2 = this._bone2.getScale();
  31778. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  31779. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  31780. }
  31781. else if (this._bone1.children[0]) {
  31782. mesh.computeWorldMatrix(true);
  31783. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  31784. var pos2 = this._bone2.getAbsolutePosition(mesh);
  31785. var pos3 = this._bone1.getAbsolutePosition(mesh);
  31786. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  31787. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  31788. }
  31789. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  31790. this.maxAngle = Math.PI;
  31791. if (options) {
  31792. if (options.targetMesh) {
  31793. this.targetMesh = options.targetMesh;
  31794. this.targetMesh.computeWorldMatrix(true);
  31795. }
  31796. if (options.poleTargetMesh) {
  31797. this.poleTargetMesh = options.poleTargetMesh;
  31798. this.poleTargetMesh.computeWorldMatrix(true);
  31799. }
  31800. else if (options.poleTargetBone) {
  31801. this.poleTargetBone = options.poleTargetBone;
  31802. }
  31803. else if (this._bone1.getParent()) {
  31804. this.poleTargetBone = this._bone1.getParent();
  31805. }
  31806. if (options.poleTargetLocalOffset) {
  31807. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  31808. }
  31809. if (options.poleAngle) {
  31810. this.poleAngle = options.poleAngle;
  31811. }
  31812. if (options.bendAxis) {
  31813. this._bendAxis.copyFrom(options.bendAxis);
  31814. }
  31815. if (options.maxAngle) {
  31816. this.maxAngle = options.maxAngle;
  31817. }
  31818. if (options.slerpAmount) {
  31819. this.slerpAmount = options.slerpAmount;
  31820. }
  31821. }
  31822. }
  31823. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  31824. get: function () {
  31825. return this._maxAngle;
  31826. },
  31827. set: function (value) {
  31828. this._setMaxAngle(value);
  31829. },
  31830. enumerable: true,
  31831. configurable: true
  31832. });
  31833. BoneIKController.prototype._setMaxAngle = function (ang) {
  31834. if (ang < 0) {
  31835. ang = 0;
  31836. }
  31837. if (ang > Math.PI || ang == undefined) {
  31838. ang = Math.PI;
  31839. }
  31840. this._maxAngle = ang;
  31841. var a = this._bone1Length;
  31842. var b = this._bone2Length;
  31843. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  31844. };
  31845. BoneIKController.prototype.update = function () {
  31846. var bone1 = this._bone1;
  31847. var target = this.targetPosition;
  31848. var poleTarget = this.poleTargetPosition;
  31849. var mat1 = this._tmpMat1;
  31850. var mat2 = this._tmpMat2;
  31851. if (this.targetMesh) {
  31852. target.copyFrom(this.targetMesh.getAbsolutePosition());
  31853. }
  31854. if (this.poleTargetBone) {
  31855. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  31856. }
  31857. else if (this.poleTargetMesh) {
  31858. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  31859. }
  31860. var bonePos = this._tmpVec1;
  31861. var zaxis = this._tmpVec2;
  31862. var xaxis = this._tmpVec3;
  31863. var yaxis = this._tmpVec4;
  31864. var upAxis = this._tmpVec5;
  31865. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  31866. poleTarget.subtractToRef(bonePos, upAxis);
  31867. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  31868. upAxis.y = 1;
  31869. }
  31870. else {
  31871. upAxis.normalize();
  31872. }
  31873. target.subtractToRef(bonePos, yaxis);
  31874. yaxis.normalize();
  31875. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  31876. zaxis.normalize();
  31877. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  31878. xaxis.normalize();
  31879. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  31880. var a = this._bone1Length;
  31881. var b = this._bone2Length;
  31882. var c = BABYLON.Vector3.Distance(bonePos, target);
  31883. if (this._maxReach > 0) {
  31884. c = Math.min(this._maxReach, c);
  31885. }
  31886. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  31887. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  31888. if (acosa > 1) {
  31889. acosa = 1;
  31890. }
  31891. if (acosb > 1) {
  31892. acosb = 1;
  31893. }
  31894. if (acosa < -1) {
  31895. acosa = -1;
  31896. }
  31897. if (acosb < -1) {
  31898. acosb = -1;
  31899. }
  31900. var angA = Math.acos(acosa);
  31901. var angB = Math.acos(acosb);
  31902. var angC = -angA - angB;
  31903. if (this._rightHandedSystem) {
  31904. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  31905. mat2.multiplyToRef(mat1, mat1);
  31906. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  31907. mat2.multiplyToRef(mat1, mat1);
  31908. }
  31909. else {
  31910. this._tmpVec1.copyFrom(this._bendAxis);
  31911. this._tmpVec1.x *= -1;
  31912. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  31913. mat2.multiplyToRef(mat1, mat1);
  31914. }
  31915. if (this.poleAngle) {
  31916. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  31917. mat1.multiplyToRef(mat2, mat1);
  31918. }
  31919. if (this.slerpAmount < 1) {
  31920. if (!this._slerping) {
  31921. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  31922. }
  31923. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  31924. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  31925. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  31926. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  31927. this._slerping = true;
  31928. }
  31929. else {
  31930. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  31931. this._bone1Mat.copyFrom(mat1);
  31932. this._slerping = false;
  31933. }
  31934. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  31935. this._bone2Ang = angC;
  31936. };
  31937. return BoneIKController;
  31938. }());
  31939. BABYLON.BoneIKController = BoneIKController;
  31940. })(BABYLON || (BABYLON = {}));
  31941. //# sourceMappingURL=babylon.boneIKController.js.map
  31942. var BABYLON;
  31943. (function (BABYLON) {
  31944. var BoneLookController = (function () {
  31945. function BoneLookController(mesh, bone, target, options) {
  31946. this.upAxis = BABYLON.Vector3.Up();
  31947. this.adjustYaw = 0;
  31948. this.adjustPitch = 0;
  31949. this.adjustRoll = 0;
  31950. this._tmpVec1 = BABYLON.Vector3.Zero();
  31951. this._tmpVec2 = BABYLON.Vector3.Zero();
  31952. this._tmpVec3 = BABYLON.Vector3.Zero();
  31953. this._tmpVec4 = BABYLON.Vector3.Zero();
  31954. this._tmpMat1 = BABYLON.Matrix.Identity();
  31955. this._tmpMat2 = BABYLON.Matrix.Identity();
  31956. this.mesh = mesh;
  31957. this.bone = bone;
  31958. this.target = target;
  31959. if (options) {
  31960. if (options.adjustYaw) {
  31961. this.adjustYaw = options.adjustYaw;
  31962. }
  31963. if (options.adjustPitch) {
  31964. this.adjustPitch = options.adjustPitch;
  31965. }
  31966. if (options.adjustRoll) {
  31967. this.adjustRoll = options.adjustRoll;
  31968. }
  31969. }
  31970. }
  31971. BoneLookController.prototype.update = function () {
  31972. var bone = this.bone;
  31973. var target = this.target;
  31974. var bonePos = this._tmpVec1;
  31975. var zaxis = this._tmpVec2;
  31976. var xaxis = this._tmpVec3;
  31977. var yaxis = this._tmpVec4;
  31978. var mat1 = this._tmpMat1;
  31979. var mat2 = this._tmpMat2;
  31980. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  31981. target.subtractToRef(bonePos, zaxis);
  31982. zaxis.normalize();
  31983. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  31984. xaxis.normalize();
  31985. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  31986. yaxis.normalize();
  31987. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  31988. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  31989. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  31990. mat2.multiplyToRef(mat1, mat1);
  31991. }
  31992. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  31993. };
  31994. return BoneLookController;
  31995. }());
  31996. BABYLON.BoneLookController = BoneLookController;
  31997. })(BABYLON || (BABYLON = {}));
  31998. //# sourceMappingURL=babylon.boneLookController.js.map
  31999. var BABYLON;
  32000. (function (BABYLON) {
  32001. var Skeleton = (function () {
  32002. function Skeleton(name, id, scene) {
  32003. this.name = name;
  32004. this.id = id;
  32005. this.bones = new Array();
  32006. this.needInitialSkinMatrix = false;
  32007. this._isDirty = true;
  32008. this._meshesWithPoseMatrix = new Array();
  32009. this._identity = BABYLON.Matrix.Identity();
  32010. this._ranges = {};
  32011. this._lastAbsoluteTransformsUpdateId = -1;
  32012. this.bones = [];
  32013. this._scene = scene;
  32014. scene.skeletons.push(this);
  32015. //make sure it will recalculate the matrix next time prepare is called.
  32016. this._isDirty = true;
  32017. }
  32018. // Members
  32019. Skeleton.prototype.getTransformMatrices = function (mesh) {
  32020. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  32021. return mesh._bonesTransformMatrices;
  32022. }
  32023. if (!this._transformMatrices) {
  32024. this.prepare();
  32025. }
  32026. return this._transformMatrices;
  32027. };
  32028. Skeleton.prototype.getScene = function () {
  32029. return this._scene;
  32030. };
  32031. // Methods
  32032. /**
  32033. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  32034. */
  32035. Skeleton.prototype.toString = function (fullDetails) {
  32036. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  32037. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  32038. if (fullDetails) {
  32039. ret += ", Ranges: {";
  32040. var first = true;
  32041. for (var name_1 in this._ranges) {
  32042. if (first) {
  32043. ret += ", ";
  32044. first = false;
  32045. }
  32046. ret += name_1;
  32047. }
  32048. ret += "}";
  32049. }
  32050. return ret;
  32051. };
  32052. /**
  32053. * Get bone's index searching by name
  32054. * @param {string} name is bone's name to search for
  32055. * @return {number} Indice of the bone. Returns -1 if not found
  32056. */
  32057. Skeleton.prototype.getBoneIndexByName = function (name) {
  32058. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  32059. if (this.bones[boneIndex].name === name) {
  32060. return boneIndex;
  32061. }
  32062. }
  32063. return -1;
  32064. };
  32065. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  32066. // check name not already in use
  32067. if (!this._ranges[name]) {
  32068. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  32069. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  32070. if (this.bones[i].animations[0]) {
  32071. this.bones[i].animations[0].createRange(name, from, to);
  32072. }
  32073. }
  32074. }
  32075. };
  32076. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  32077. if (deleteFrames === void 0) { deleteFrames = true; }
  32078. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  32079. if (this.bones[i].animations[0]) {
  32080. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  32081. }
  32082. }
  32083. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  32084. };
  32085. Skeleton.prototype.getAnimationRange = function (name) {
  32086. return this._ranges[name];
  32087. };
  32088. /**
  32089. * Returns as an Array, all AnimationRanges defined on this skeleton
  32090. */
  32091. Skeleton.prototype.getAnimationRanges = function () {
  32092. var animationRanges = [];
  32093. var name;
  32094. var i = 0;
  32095. for (name in this._ranges) {
  32096. animationRanges[i] = this._ranges[name];
  32097. i++;
  32098. }
  32099. return animationRanges;
  32100. };
  32101. /**
  32102. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  32103. */
  32104. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  32105. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  32106. if (this._ranges[name] || !source.getAnimationRange(name)) {
  32107. return false;
  32108. }
  32109. var ret = true;
  32110. var frameOffset = this._getHighestAnimationFrame() + 1;
  32111. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  32112. var boneDict = {};
  32113. var sourceBones = source.bones;
  32114. var nBones;
  32115. var i;
  32116. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  32117. boneDict[sourceBones[i].name] = sourceBones[i];
  32118. }
  32119. if (this.bones.length !== sourceBones.length) {
  32120. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  32121. ret = false;
  32122. }
  32123. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  32124. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  32125. var boneName = this.bones[i].name;
  32126. var sourceBone = boneDict[boneName];
  32127. if (sourceBone) {
  32128. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  32129. }
  32130. else {
  32131. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  32132. ret = false;
  32133. }
  32134. }
  32135. // do not call createAnimationRange(), since it also is done to bones, which was already done
  32136. var range = source.getAnimationRange(name);
  32137. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  32138. return ret;
  32139. };
  32140. Skeleton.prototype.returnToRest = function () {
  32141. for (var index = 0; index < this.bones.length; index++) {
  32142. this.bones[index].returnToRest();
  32143. }
  32144. };
  32145. Skeleton.prototype._getHighestAnimationFrame = function () {
  32146. var ret = 0;
  32147. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  32148. if (this.bones[i].animations[0]) {
  32149. var highest = this.bones[i].animations[0].getHighestFrame();
  32150. if (ret < highest) {
  32151. ret = highest;
  32152. }
  32153. }
  32154. }
  32155. return ret;
  32156. };
  32157. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  32158. var range = this.getAnimationRange(name);
  32159. if (!range) {
  32160. return null;
  32161. }
  32162. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  32163. };
  32164. Skeleton.prototype._markAsDirty = function () {
  32165. this._isDirty = true;
  32166. };
  32167. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  32168. this._meshesWithPoseMatrix.push(mesh);
  32169. };
  32170. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  32171. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  32172. if (index > -1) {
  32173. this._meshesWithPoseMatrix.splice(index, 1);
  32174. }
  32175. };
  32176. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  32177. for (var index = 0; index < this.bones.length; index++) {
  32178. var bone = this.bones[index];
  32179. var parentBone = bone.getParent();
  32180. if (parentBone) {
  32181. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  32182. }
  32183. else {
  32184. if (initialSkinMatrix) {
  32185. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  32186. }
  32187. else {
  32188. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  32189. }
  32190. }
  32191. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  32192. }
  32193. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  32194. };
  32195. Skeleton.prototype.prepare = function () {
  32196. if (!this._isDirty) {
  32197. return;
  32198. }
  32199. if (this.needInitialSkinMatrix) {
  32200. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  32201. var mesh = this._meshesWithPoseMatrix[index];
  32202. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  32203. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  32204. }
  32205. var poseMatrix = mesh.getPoseMatrix();
  32206. // Prepare bones
  32207. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  32208. var bone = this.bones[boneIndex];
  32209. if (!bone.getParent()) {
  32210. var matrix = bone.getBaseMatrix();
  32211. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  32212. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  32213. }
  32214. }
  32215. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  32216. }
  32217. }
  32218. else {
  32219. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  32220. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  32221. }
  32222. this._computeTransformMatrices(this._transformMatrices, null);
  32223. }
  32224. this._isDirty = false;
  32225. this._scene._activeBones.addCount(this.bones.length, false);
  32226. };
  32227. Skeleton.prototype.getAnimatables = function () {
  32228. if (!this._animatables || this._animatables.length !== this.bones.length) {
  32229. this._animatables = [];
  32230. for (var index = 0; index < this.bones.length; index++) {
  32231. this._animatables.push(this.bones[index]);
  32232. }
  32233. }
  32234. return this._animatables;
  32235. };
  32236. Skeleton.prototype.clone = function (name, id) {
  32237. var result = new Skeleton(name, id || name, this._scene);
  32238. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  32239. for (var index = 0; index < this.bones.length; index++) {
  32240. var source = this.bones[index];
  32241. var parentBone = null;
  32242. if (source.getParent()) {
  32243. var parentIndex = this.bones.indexOf(source.getParent());
  32244. parentBone = result.bones[parentIndex];
  32245. }
  32246. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  32247. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  32248. }
  32249. if (this._ranges) {
  32250. result._ranges = {};
  32251. for (var rangeName in this._ranges) {
  32252. result._ranges[rangeName] = this._ranges[rangeName].clone();
  32253. }
  32254. }
  32255. this._isDirty = true;
  32256. return result;
  32257. };
  32258. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  32259. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  32260. this.bones.forEach(function (bone) {
  32261. bone.animations.forEach(function (animation) {
  32262. animation.enableBlending = true;
  32263. animation.blendingSpeed = blendingSpeed;
  32264. });
  32265. });
  32266. };
  32267. Skeleton.prototype.dispose = function () {
  32268. this._meshesWithPoseMatrix = [];
  32269. // Animations
  32270. this.getScene().stopAnimation(this);
  32271. // Remove from scene
  32272. this.getScene().removeSkeleton(this);
  32273. };
  32274. Skeleton.prototype.serialize = function () {
  32275. var serializationObject = {};
  32276. serializationObject.name = this.name;
  32277. serializationObject.id = this.id;
  32278. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  32279. serializationObject.bones = [];
  32280. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  32281. for (var index = 0; index < this.bones.length; index++) {
  32282. var bone = this.bones[index];
  32283. var serializedBone = {
  32284. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  32285. name: bone.name,
  32286. matrix: bone.getLocalMatrix().toArray(),
  32287. rest: bone.getRestPose().toArray()
  32288. };
  32289. serializationObject.bones.push(serializedBone);
  32290. if (bone.length) {
  32291. serializedBone.length = bone.length;
  32292. }
  32293. if (bone.animations && bone.animations.length > 0) {
  32294. serializedBone.animation = bone.animations[0].serialize();
  32295. }
  32296. serializationObject.ranges = [];
  32297. for (var name in this._ranges) {
  32298. var range = {};
  32299. range.name = name;
  32300. range.from = this._ranges[name].from;
  32301. range.to = this._ranges[name].to;
  32302. serializationObject.ranges.push(range);
  32303. }
  32304. }
  32305. return serializationObject;
  32306. };
  32307. Skeleton.Parse = function (parsedSkeleton, scene) {
  32308. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  32309. if (parsedSkeleton.dimensionsAtRest) {
  32310. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  32311. }
  32312. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  32313. var index;
  32314. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  32315. var parsedBone = parsedSkeleton.bones[index];
  32316. var parentBone = null;
  32317. if (parsedBone.parentBoneIndex > -1) {
  32318. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  32319. }
  32320. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  32321. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  32322. if (parsedBone.length) {
  32323. bone.length = parsedBone.length;
  32324. }
  32325. if (parsedBone.animation) {
  32326. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  32327. }
  32328. }
  32329. // placed after bones, so createAnimationRange can cascade down
  32330. if (parsedSkeleton.ranges) {
  32331. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  32332. var data = parsedSkeleton.ranges[index];
  32333. skeleton.createAnimationRange(data.name, data.from, data.to);
  32334. }
  32335. }
  32336. return skeleton;
  32337. };
  32338. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  32339. if (forceUpdate === void 0) { forceUpdate = false; }
  32340. var renderId = this._scene.getRenderId();
  32341. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  32342. this.bones[0].computeAbsoluteTransforms();
  32343. this._lastAbsoluteTransformsUpdateId = renderId;
  32344. }
  32345. };
  32346. Skeleton.prototype.getPoseMatrix = function () {
  32347. var poseMatrix;
  32348. if (this._meshesWithPoseMatrix.length > 0) {
  32349. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  32350. }
  32351. return poseMatrix;
  32352. };
  32353. return Skeleton;
  32354. }());
  32355. BABYLON.Skeleton = Skeleton;
  32356. })(BABYLON || (BABYLON = {}));
  32357. //# sourceMappingURL=babylon.skeleton.js.map
  32358. var BABYLON;
  32359. (function (BABYLON) {
  32360. var PostProcess = (function () {
  32361. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  32362. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  32363. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  32364. this.name = name;
  32365. this.width = -1;
  32366. this.height = -1;
  32367. /*
  32368. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  32369. Can only be used on a single postprocess or on the last one of a chain.
  32370. */
  32371. this.enablePixelPerfectMode = false;
  32372. this._reusable = false;
  32373. this._textures = new BABYLON.SmartArray(2);
  32374. this._currentRenderTextureInd = 0;
  32375. this._scaleRatio = new BABYLON.Vector2(1, 1);
  32376. // Events
  32377. /**
  32378. * An event triggered when the postprocess is activated.
  32379. * @type {BABYLON.Observable}
  32380. */
  32381. this.onActivateObservable = new BABYLON.Observable();
  32382. /**
  32383. * An event triggered when the postprocess changes its size.
  32384. * @type {BABYLON.Observable}
  32385. */
  32386. this.onSizeChangedObservable = new BABYLON.Observable();
  32387. /**
  32388. * An event triggered when the postprocess applies its effect.
  32389. * @type {BABYLON.Observable}
  32390. */
  32391. this.onApplyObservable = new BABYLON.Observable();
  32392. /**
  32393. * An event triggered before rendering the postprocess
  32394. * @type {BABYLON.Observable}
  32395. */
  32396. this.onBeforeRenderObservable = new BABYLON.Observable();
  32397. /**
  32398. * An event triggered after rendering the postprocess
  32399. * @type {BABYLON.Observable}
  32400. */
  32401. this.onAfterRenderObservable = new BABYLON.Observable();
  32402. if (camera != null) {
  32403. this._camera = camera;
  32404. this._scene = camera.getScene();
  32405. camera.attachPostProcess(this);
  32406. this._engine = this._scene.getEngine();
  32407. }
  32408. else {
  32409. this._engine = engine;
  32410. }
  32411. this._options = options;
  32412. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  32413. this._reusable = reusable || false;
  32414. this._textureType = textureType;
  32415. this._samplers = samplers || [];
  32416. this._samplers.push("textureSampler");
  32417. this._fragmentUrl = fragmentUrl;
  32418. this._parameters = parameters || [];
  32419. this._parameters.push("scale");
  32420. this.updateEffect(defines);
  32421. }
  32422. Object.defineProperty(PostProcess.prototype, "onActivate", {
  32423. set: function (callback) {
  32424. if (this._onActivateObserver) {
  32425. this.onActivateObservable.remove(this._onActivateObserver);
  32426. }
  32427. this._onActivateObserver = this.onActivateObservable.add(callback);
  32428. },
  32429. enumerable: true,
  32430. configurable: true
  32431. });
  32432. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  32433. set: function (callback) {
  32434. if (this._onSizeChangedObserver) {
  32435. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  32436. }
  32437. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  32438. },
  32439. enumerable: true,
  32440. configurable: true
  32441. });
  32442. Object.defineProperty(PostProcess.prototype, "onApply", {
  32443. set: function (callback) {
  32444. if (this._onApplyObserver) {
  32445. this.onApplyObservable.remove(this._onApplyObserver);
  32446. }
  32447. this._onApplyObserver = this.onApplyObservable.add(callback);
  32448. },
  32449. enumerable: true,
  32450. configurable: true
  32451. });
  32452. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  32453. set: function (callback) {
  32454. if (this._onBeforeRenderObserver) {
  32455. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  32456. }
  32457. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  32458. },
  32459. enumerable: true,
  32460. configurable: true
  32461. });
  32462. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  32463. set: function (callback) {
  32464. if (this._onAfterRenderObserver) {
  32465. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  32466. }
  32467. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  32468. },
  32469. enumerable: true,
  32470. configurable: true
  32471. });
  32472. PostProcess.prototype.updateEffect = function (defines) {
  32473. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  32474. };
  32475. PostProcess.prototype.isReusable = function () {
  32476. return this._reusable;
  32477. };
  32478. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  32479. PostProcess.prototype.markTextureDirty = function () {
  32480. this.width = -1;
  32481. };
  32482. PostProcess.prototype.activate = function (camera, sourceTexture) {
  32483. camera = camera || this._camera;
  32484. var scene = camera.getScene();
  32485. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  32486. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  32487. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  32488. var desiredWidth = this._options.width || requiredWidth;
  32489. var desiredHeight = this._options.height || requiredHeight;
  32490. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  32491. if (!this._options.width) {
  32492. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  32493. }
  32494. if (!this._options.height) {
  32495. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  32496. }
  32497. }
  32498. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  32499. if (this._textures.length > 0) {
  32500. for (var i = 0; i < this._textures.length; i++) {
  32501. this._engine._releaseTexture(this._textures.data[i]);
  32502. }
  32503. this._textures.reset();
  32504. }
  32505. this.width = desiredWidth;
  32506. this.height = desiredHeight;
  32507. var textureSize = { width: this.width, height: this.height };
  32508. var textureOptions = {
  32509. generateMipMaps: false,
  32510. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  32511. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  32512. samplingMode: this.renderTargetSamplingMode,
  32513. type: this._textureType
  32514. };
  32515. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32516. if (this._reusable) {
  32517. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  32518. }
  32519. this.onSizeChangedObservable.notifyObservers(this);
  32520. }
  32521. if (this.enablePixelPerfectMode) {
  32522. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  32523. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  32524. }
  32525. else {
  32526. this._scaleRatio.copyFromFloats(1, 1);
  32527. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  32528. }
  32529. this.onActivateObservable.notifyObservers(camera);
  32530. // Clear
  32531. if (this.clearColor) {
  32532. this._engine.clear(this.clearColor, true, true, true);
  32533. }
  32534. else {
  32535. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  32536. }
  32537. if (this._reusable) {
  32538. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  32539. }
  32540. };
  32541. Object.defineProperty(PostProcess.prototype, "isSupported", {
  32542. get: function () {
  32543. return this._effect.isSupported;
  32544. },
  32545. enumerable: true,
  32546. configurable: true
  32547. });
  32548. PostProcess.prototype.apply = function () {
  32549. // Check
  32550. if (!this._effect.isReady())
  32551. return null;
  32552. // States
  32553. this._engine.enableEffect(this._effect);
  32554. this._engine.setState(false);
  32555. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  32556. this._engine.setDepthBuffer(false);
  32557. this._engine.setDepthWrite(false);
  32558. // Texture
  32559. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  32560. // Parameters
  32561. this._effect.setVector2("scale", this._scaleRatio);
  32562. this.onApplyObservable.notifyObservers(this._effect);
  32563. return this._effect;
  32564. };
  32565. PostProcess.prototype.dispose = function (camera) {
  32566. camera = camera || this._camera;
  32567. if (this._textures.length > 0) {
  32568. for (var i = 0; i < this._textures.length; i++) {
  32569. this._engine._releaseTexture(this._textures.data[i]);
  32570. }
  32571. this._textures.reset();
  32572. }
  32573. if (!camera) {
  32574. return;
  32575. }
  32576. camera.detachPostProcess(this);
  32577. var index = camera._postProcesses.indexOf(this);
  32578. if (index === 0 && camera._postProcesses.length > 0) {
  32579. this._camera._postProcesses[0].markTextureDirty();
  32580. }
  32581. this.onActivateObservable.clear();
  32582. this.onAfterRenderObservable.clear();
  32583. this.onApplyObservable.clear();
  32584. this.onBeforeRenderObservable.clear();
  32585. this.onSizeChangedObservable.clear();
  32586. };
  32587. return PostProcess;
  32588. }());
  32589. BABYLON.PostProcess = PostProcess;
  32590. })(BABYLON || (BABYLON = {}));
  32591. //# sourceMappingURL=babylon.postProcess.js.map
  32592. var BABYLON;
  32593. (function (BABYLON) {
  32594. var PostProcessManager = (function () {
  32595. function PostProcessManager(scene) {
  32596. this._vertexBuffers = {};
  32597. this._scene = scene;
  32598. }
  32599. PostProcessManager.prototype._prepareBuffers = function () {
  32600. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  32601. return;
  32602. }
  32603. // VBO
  32604. var vertices = [];
  32605. vertices.push(1, 1);
  32606. vertices.push(-1, 1);
  32607. vertices.push(-1, -1);
  32608. vertices.push(1, -1);
  32609. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  32610. // Indices
  32611. var indices = [];
  32612. indices.push(0);
  32613. indices.push(1);
  32614. indices.push(2);
  32615. indices.push(0);
  32616. indices.push(2);
  32617. indices.push(3);
  32618. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  32619. };
  32620. // Methods
  32621. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  32622. var postProcesses = this._scene.activeCamera._postProcesses;
  32623. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32624. return false;
  32625. }
  32626. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  32627. return true;
  32628. };
  32629. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  32630. var engine = this._scene.getEngine();
  32631. for (var index = 0; index < postProcesses.length; index++) {
  32632. if (index < postProcesses.length - 1) {
  32633. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32634. }
  32635. else {
  32636. if (targetTexture) {
  32637. engine.bindFramebuffer(targetTexture);
  32638. }
  32639. else {
  32640. engine.restoreDefaultFramebuffer();
  32641. }
  32642. }
  32643. var pp = postProcesses[index];
  32644. var effect = pp.apply();
  32645. if (effect) {
  32646. pp.onBeforeRenderObservable.notifyObservers(effect);
  32647. // VBOs
  32648. this._prepareBuffers();
  32649. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32650. // Draw order
  32651. engine.draw(true, 0, 6);
  32652. pp.onAfterRenderObservable.notifyObservers(effect);
  32653. }
  32654. }
  32655. // Restore depth buffer
  32656. engine.setDepthBuffer(true);
  32657. engine.setDepthWrite(true);
  32658. };
  32659. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  32660. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  32661. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  32662. return;
  32663. }
  32664. var engine = this._scene.getEngine();
  32665. for (var index = 0, len = postProcesses.length; index < len; index++) {
  32666. if (index < len - 1) {
  32667. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  32668. }
  32669. else {
  32670. if (targetTexture) {
  32671. engine.bindFramebuffer(targetTexture, faceIndex);
  32672. }
  32673. else {
  32674. engine.restoreDefaultFramebuffer();
  32675. }
  32676. }
  32677. if (doNotPresent) {
  32678. break;
  32679. }
  32680. var pp = postProcesses[index];
  32681. var effect = pp.apply();
  32682. if (effect) {
  32683. pp.onBeforeRenderObservable.notifyObservers(effect);
  32684. // VBOs
  32685. this._prepareBuffers();
  32686. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  32687. // Draw order
  32688. engine.draw(true, 0, 6);
  32689. pp.onAfterRenderObservable.notifyObservers(effect);
  32690. }
  32691. }
  32692. // Restore depth buffer
  32693. engine.setDepthBuffer(true);
  32694. engine.setDepthWrite(true);
  32695. };
  32696. PostProcessManager.prototype.dispose = function () {
  32697. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  32698. if (buffer) {
  32699. buffer.dispose();
  32700. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  32701. }
  32702. if (this._indexBuffer) {
  32703. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  32704. this._indexBuffer = null;
  32705. }
  32706. };
  32707. return PostProcessManager;
  32708. }());
  32709. BABYLON.PostProcessManager = PostProcessManager;
  32710. })(BABYLON || (BABYLON = {}));
  32711. //# sourceMappingURL=babylon.postProcessManager.js.map
  32712. var BABYLON;
  32713. (function (BABYLON) {
  32714. var PassPostProcess = (function (_super) {
  32715. __extends(PassPostProcess, _super);
  32716. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  32717. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  32718. }
  32719. return PassPostProcess;
  32720. }(BABYLON.PostProcess));
  32721. BABYLON.PassPostProcess = PassPostProcess;
  32722. })(BABYLON || (BABYLON = {}));
  32723. //# sourceMappingURL=babylon.passPostProcess.js.map
  32724. var BABYLON;
  32725. (function (BABYLON) {
  32726. /**
  32727. * This is a holder class for the physics joint created by the physics plugin.
  32728. * It holds a set of functions to control the underlying joint.
  32729. */
  32730. var PhysicsJoint = (function () {
  32731. function PhysicsJoint(type, jointData) {
  32732. this.type = type;
  32733. this.jointData = jointData;
  32734. jointData.nativeParams = jointData.nativeParams || {};
  32735. }
  32736. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  32737. get: function () {
  32738. return this._physicsJoint;
  32739. },
  32740. set: function (newJoint) {
  32741. if (this._physicsJoint) {
  32742. }
  32743. this._physicsJoint = newJoint;
  32744. },
  32745. enumerable: true,
  32746. configurable: true
  32747. });
  32748. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  32749. set: function (physicsPlugin) {
  32750. this._physicsPlugin = physicsPlugin;
  32751. },
  32752. enumerable: true,
  32753. configurable: true
  32754. });
  32755. /**
  32756. * Execute a function that is physics-plugin specific.
  32757. * @param {Function} func the function that will be executed.
  32758. * It accepts two parameters: the physics world and the physics joint.
  32759. */
  32760. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  32761. func(this._physicsPlugin.world, this._physicsJoint);
  32762. };
  32763. return PhysicsJoint;
  32764. }());
  32765. //TODO check if the native joints are the same
  32766. //Joint Types
  32767. PhysicsJoint.DistanceJoint = 0;
  32768. PhysicsJoint.HingeJoint = 1;
  32769. PhysicsJoint.BallAndSocketJoint = 2;
  32770. PhysicsJoint.WheelJoint = 3;
  32771. PhysicsJoint.SliderJoint = 4;
  32772. //OIMO
  32773. PhysicsJoint.PrismaticJoint = 5;
  32774. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  32775. PhysicsJoint.UniversalJoint = 6;
  32776. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  32777. //Cannon
  32778. //Similar to a Ball-Joint. Different in params
  32779. PhysicsJoint.PointToPointJoint = 8;
  32780. //Cannon only at the moment
  32781. PhysicsJoint.SpringJoint = 9;
  32782. PhysicsJoint.LockJoint = 10;
  32783. BABYLON.PhysicsJoint = PhysicsJoint;
  32784. /**
  32785. * A class representing a physics distance joint.
  32786. */
  32787. var DistanceJoint = (function (_super) {
  32788. __extends(DistanceJoint, _super);
  32789. function DistanceJoint(jointData) {
  32790. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  32791. }
  32792. /**
  32793. * Update the predefined distance.
  32794. */
  32795. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  32796. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  32797. };
  32798. return DistanceJoint;
  32799. }(PhysicsJoint));
  32800. BABYLON.DistanceJoint = DistanceJoint;
  32801. var MotorEnabledJoint = (function (_super) {
  32802. __extends(MotorEnabledJoint, _super);
  32803. function MotorEnabledJoint(type, jointData) {
  32804. return _super.call(this, type, jointData) || this;
  32805. }
  32806. /**
  32807. * Set the motor values.
  32808. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32809. * @param {number} force the force to apply
  32810. * @param {number} maxForce max force for this motor.
  32811. */
  32812. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  32813. this._physicsPlugin.setMotor(this, force, maxForce);
  32814. };
  32815. /**
  32816. * Set the motor's limits.
  32817. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32818. */
  32819. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  32820. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  32821. };
  32822. return MotorEnabledJoint;
  32823. }(PhysicsJoint));
  32824. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  32825. /**
  32826. * This class represents a single hinge physics joint
  32827. */
  32828. var HingeJoint = (function (_super) {
  32829. __extends(HingeJoint, _super);
  32830. function HingeJoint(jointData) {
  32831. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  32832. }
  32833. /**
  32834. * Set the motor values.
  32835. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32836. * @param {number} force the force to apply
  32837. * @param {number} maxForce max force for this motor.
  32838. */
  32839. HingeJoint.prototype.setMotor = function (force, maxForce) {
  32840. this._physicsPlugin.setMotor(this, force, maxForce);
  32841. };
  32842. /**
  32843. * Set the motor's limits.
  32844. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32845. */
  32846. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  32847. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  32848. };
  32849. return HingeJoint;
  32850. }(MotorEnabledJoint));
  32851. BABYLON.HingeJoint = HingeJoint;
  32852. /**
  32853. * This class represents a dual hinge physics joint (same as wheel joint)
  32854. */
  32855. var Hinge2Joint = (function (_super) {
  32856. __extends(Hinge2Joint, _super);
  32857. function Hinge2Joint(jointData) {
  32858. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  32859. }
  32860. /**
  32861. * Set the motor values.
  32862. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32863. * @param {number} force the force to apply
  32864. * @param {number} maxForce max force for this motor.
  32865. * @param {motorIndex} the motor's index, 0 or 1.
  32866. */
  32867. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  32868. if (motorIndex === void 0) { motorIndex = 0; }
  32869. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  32870. };
  32871. /**
  32872. * Set the motor limits.
  32873. * Attention, this function is plugin specific. Engines won't react 100% the same.
  32874. * @param {number} upperLimit the upper limit
  32875. * @param {number} lowerLimit lower limit
  32876. * @param {motorIndex} the motor's index, 0 or 1.
  32877. */
  32878. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  32879. if (motorIndex === void 0) { motorIndex = 0; }
  32880. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  32881. };
  32882. return Hinge2Joint;
  32883. }(MotorEnabledJoint));
  32884. BABYLON.Hinge2Joint = Hinge2Joint;
  32885. })(BABYLON || (BABYLON = {}));
  32886. //# sourceMappingURL=babylon.physicsJoint.js.map
  32887. var BABYLON;
  32888. (function (BABYLON) {
  32889. var PhysicsImpostor = (function () {
  32890. function PhysicsImpostor(object, type, _options, _scene) {
  32891. if (_options === void 0) { _options = { mass: 0 }; }
  32892. var _this = this;
  32893. this.object = object;
  32894. this.type = type;
  32895. this._options = _options;
  32896. this._scene = _scene;
  32897. this._bodyUpdateRequired = false;
  32898. this._onBeforePhysicsStepCallbacks = new Array();
  32899. this._onAfterPhysicsStepCallbacks = new Array();
  32900. this._onPhysicsCollideCallbacks = [];
  32901. this._deltaPosition = BABYLON.Vector3.Zero();
  32902. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  32903. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  32904. /**
  32905. * this function is executed by the physics engine.
  32906. */
  32907. this.beforeStep = function () {
  32908. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  32909. //conjugate deltaRotation
  32910. if (_this._deltaRotationConjugated) {
  32911. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  32912. }
  32913. else {
  32914. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  32915. }
  32916. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  32917. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  32918. func(_this);
  32919. });
  32920. };
  32921. /**
  32922. * this function is executed by the physics engine.
  32923. */
  32924. this.afterStep = function () {
  32925. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  32926. func(_this);
  32927. });
  32928. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  32929. _this.object.position.addInPlace(_this._deltaPosition);
  32930. if (_this._deltaRotation) {
  32931. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  32932. }
  32933. };
  32934. /**
  32935. * Legacy collision detection event support
  32936. */
  32937. this.onCollideEvent = null;
  32938. //event and body object due to cannon's event-based architecture.
  32939. this.onCollide = function (e) {
  32940. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  32941. return;
  32942. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  32943. if (otherImpostor) {
  32944. // Legacy collision detection event support
  32945. if (_this.onCollideEvent) {
  32946. _this.onCollideEvent(_this, otherImpostor);
  32947. }
  32948. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  32949. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  32950. }).forEach(function (obj) {
  32951. obj.callback(_this, otherImpostor);
  32952. });
  32953. }
  32954. };
  32955. //sanity check!
  32956. if (!this.object) {
  32957. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  32958. return;
  32959. }
  32960. //legacy support for old syntax.
  32961. if (!this._scene && object.getScene) {
  32962. this._scene = object.getScene();
  32963. }
  32964. this._physicsEngine = this._scene.getPhysicsEngine();
  32965. if (!this._physicsEngine) {
  32966. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  32967. }
  32968. else {
  32969. //set the object's quaternion, if not set
  32970. if (!this.object.rotationQuaternion) {
  32971. if (this.object.rotation) {
  32972. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  32973. }
  32974. else {
  32975. this.object.rotationQuaternion = new BABYLON.Quaternion();
  32976. }
  32977. }
  32978. //default options params
  32979. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  32980. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  32981. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  32982. this._joints = [];
  32983. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  32984. if (!this.object.parent) {
  32985. this._init();
  32986. }
  32987. }
  32988. }
  32989. /**
  32990. * This function will completly initialize this impostor.
  32991. * It will create a new body - but only if this mesh has no parent.
  32992. * If it has, this impostor will not be used other than to define the impostor
  32993. * of the child mesh.
  32994. */
  32995. PhysicsImpostor.prototype._init = function () {
  32996. this._physicsEngine.removeImpostor(this);
  32997. this.physicsBody = null;
  32998. this._parent = this._parent || this._getPhysicsParent();
  32999. if (!this.parent) {
  33000. this._physicsEngine.addImpostor(this);
  33001. }
  33002. };
  33003. PhysicsImpostor.prototype._getPhysicsParent = function () {
  33004. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  33005. var parentMesh = this.object.parent;
  33006. return parentMesh.physicsImpostor;
  33007. }
  33008. return;
  33009. };
  33010. /**
  33011. * Should a new body be generated.
  33012. */
  33013. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  33014. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  33015. };
  33016. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  33017. this.forceUpdate();
  33018. };
  33019. /**
  33020. * Force a regeneration of this or the parent's impostor's body.
  33021. * Use under cautious - This will remove all joints already implemented.
  33022. */
  33023. PhysicsImpostor.prototype.forceUpdate = function () {
  33024. this._init();
  33025. if (this.parent) {
  33026. this.parent.forceUpdate();
  33027. }
  33028. };
  33029. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  33030. /*public get mesh(): AbstractMesh {
  33031. return this._mesh;
  33032. }*/
  33033. /**
  33034. * Gets the body that holds this impostor. Either its own, or its parent.
  33035. */
  33036. get: function () {
  33037. return this._parent ? this._parent.physicsBody : this._physicsBody;
  33038. },
  33039. /**
  33040. * Set the physics body. Used mainly by the physics engine/plugin
  33041. */
  33042. set: function (physicsBody) {
  33043. if (this._physicsBody) {
  33044. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  33045. }
  33046. this._physicsBody = physicsBody;
  33047. this.resetUpdateFlags();
  33048. },
  33049. enumerable: true,
  33050. configurable: true
  33051. });
  33052. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  33053. get: function () {
  33054. return this._parent;
  33055. },
  33056. set: function (value) {
  33057. this._parent = value;
  33058. },
  33059. enumerable: true,
  33060. configurable: true
  33061. });
  33062. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  33063. this._bodyUpdateRequired = false;
  33064. };
  33065. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  33066. if (this.object.getBoundingInfo) {
  33067. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  33068. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  33069. }
  33070. else {
  33071. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  33072. }
  33073. };
  33074. PhysicsImpostor.prototype.getObjectCenter = function () {
  33075. if (this.object.getBoundingInfo) {
  33076. return this.object.getBoundingInfo().boundingBox.center;
  33077. }
  33078. else {
  33079. return this.object.position;
  33080. }
  33081. };
  33082. /**
  33083. * Get a specific parametes from the options parameter.
  33084. */
  33085. PhysicsImpostor.prototype.getParam = function (paramName) {
  33086. return this._options[paramName];
  33087. };
  33088. /**
  33089. * Sets a specific parameter in the options given to the physics plugin
  33090. */
  33091. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  33092. this._options[paramName] = value;
  33093. this._bodyUpdateRequired = true;
  33094. };
  33095. /**
  33096. * Specifically change the body's mass option. Won't recreate the physics body object
  33097. */
  33098. PhysicsImpostor.prototype.setMass = function (mass) {
  33099. if (this.getParam("mass") !== mass) {
  33100. this.setParam("mass", mass);
  33101. }
  33102. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  33103. };
  33104. PhysicsImpostor.prototype.getLinearVelocity = function () {
  33105. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  33106. };
  33107. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  33108. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  33109. };
  33110. PhysicsImpostor.prototype.getAngularVelocity = function () {
  33111. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  33112. };
  33113. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  33114. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  33115. };
  33116. /**
  33117. * Execute a function with the physics plugin native code.
  33118. * Provide a function the will have two variables - the world object and the physics body object.
  33119. */
  33120. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  33121. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  33122. };
  33123. /**
  33124. * Register a function that will be executed before the physics world is stepping forward.
  33125. */
  33126. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  33127. this._onBeforePhysicsStepCallbacks.push(func);
  33128. };
  33129. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  33130. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  33131. if (index > -1) {
  33132. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  33133. }
  33134. else {
  33135. BABYLON.Tools.Warn("Function to remove was not found");
  33136. }
  33137. };
  33138. /**
  33139. * Register a function that will be executed after the physics step
  33140. */
  33141. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  33142. this._onAfterPhysicsStepCallbacks.push(func);
  33143. };
  33144. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  33145. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  33146. if (index > -1) {
  33147. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  33148. }
  33149. else {
  33150. BABYLON.Tools.Warn("Function to remove was not found");
  33151. }
  33152. };
  33153. /**
  33154. * register a function that will be executed when this impostor collides against a different body.
  33155. */
  33156. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  33157. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  33158. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  33159. };
  33160. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  33161. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  33162. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  33163. if (index > -1) {
  33164. this._onPhysicsCollideCallbacks.splice(index, 1);
  33165. }
  33166. else {
  33167. BABYLON.Tools.Warn("Function to remove was not found");
  33168. }
  33169. };
  33170. /**
  33171. * Apply a force
  33172. */
  33173. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  33174. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  33175. };
  33176. /**
  33177. * Apply an impulse
  33178. */
  33179. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  33180. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  33181. };
  33182. /**
  33183. * A help function to create a joint.
  33184. */
  33185. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  33186. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  33187. this.addJoint(otherImpostor, joint);
  33188. };
  33189. /**
  33190. * Add a joint to this impostor with a different impostor.
  33191. */
  33192. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  33193. this._joints.push({
  33194. otherImpostor: otherImpostor,
  33195. joint: joint
  33196. });
  33197. this._physicsEngine.addJoint(this, otherImpostor, joint);
  33198. };
  33199. /**
  33200. * Will keep this body still, in a sleep mode.
  33201. */
  33202. PhysicsImpostor.prototype.sleep = function () {
  33203. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  33204. };
  33205. /**
  33206. * Wake the body up.
  33207. */
  33208. PhysicsImpostor.prototype.wakeUp = function () {
  33209. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  33210. };
  33211. PhysicsImpostor.prototype.clone = function (newObject) {
  33212. if (!newObject)
  33213. return null;
  33214. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  33215. };
  33216. PhysicsImpostor.prototype.dispose = function () {
  33217. var _this = this;
  33218. //no dispose if no physics engine is available.
  33219. if (!this._physicsEngine) {
  33220. return;
  33221. }
  33222. this._joints.forEach(function (j) {
  33223. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  33224. });
  33225. //dispose the physics body
  33226. this._physicsEngine.removeImpostor(this);
  33227. if (this.parent) {
  33228. this.parent.forceUpdate();
  33229. }
  33230. else {
  33231. }
  33232. };
  33233. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  33234. this._deltaPosition.copyFrom(position);
  33235. };
  33236. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  33237. if (!this._deltaRotation) {
  33238. this._deltaRotation = new BABYLON.Quaternion();
  33239. }
  33240. this._deltaRotation.copyFrom(rotation);
  33241. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  33242. };
  33243. return PhysicsImpostor;
  33244. }());
  33245. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  33246. //Impostor types
  33247. PhysicsImpostor.NoImpostor = 0;
  33248. PhysicsImpostor.SphereImpostor = 1;
  33249. PhysicsImpostor.BoxImpostor = 2;
  33250. PhysicsImpostor.PlaneImpostor = 3;
  33251. PhysicsImpostor.MeshImpostor = 4;
  33252. PhysicsImpostor.CylinderImpostor = 7;
  33253. PhysicsImpostor.ParticleImpostor = 8;
  33254. PhysicsImpostor.HeightmapImpostor = 9;
  33255. BABYLON.PhysicsImpostor = PhysicsImpostor;
  33256. })(BABYLON || (BABYLON = {}));
  33257. //# sourceMappingURL=babylon.physicsImpostor.js.map
  33258. var BABYLON;
  33259. (function (BABYLON) {
  33260. var PhysicsEngine = (function () {
  33261. function PhysicsEngine(gravity, _physicsPlugin) {
  33262. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  33263. this._physicsPlugin = _physicsPlugin;
  33264. //new methods and parameters
  33265. this._impostors = [];
  33266. this._joints = [];
  33267. if (!this._physicsPlugin.isSupported()) {
  33268. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  33269. + "Please make sure it is included.");
  33270. }
  33271. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  33272. this.setGravity(gravity);
  33273. this.setTimeStep();
  33274. }
  33275. PhysicsEngine.prototype.setGravity = function (gravity) {
  33276. this.gravity = gravity;
  33277. this._physicsPlugin.setGravity(this.gravity);
  33278. };
  33279. /**
  33280. * Set the time step of the physics engine.
  33281. * default is 1/60.
  33282. * To slow it down, enter 1/600 for example.
  33283. * To speed it up, 1/30
  33284. * @param {number} newTimeStep the new timestep to apply to this world.
  33285. */
  33286. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  33287. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  33288. this._physicsPlugin.setTimeStep(newTimeStep);
  33289. };
  33290. PhysicsEngine.prototype.dispose = function () {
  33291. this._impostors.forEach(function (impostor) {
  33292. impostor.dispose();
  33293. });
  33294. this._physicsPlugin.dispose();
  33295. };
  33296. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  33297. return this._physicsPlugin.name;
  33298. };
  33299. /**
  33300. * Adding a new impostor for the impostor tracking.
  33301. * This will be done by the impostor itself.
  33302. * @param {PhysicsImpostor} impostor the impostor to add
  33303. */
  33304. PhysicsEngine.prototype.addImpostor = function (impostor) {
  33305. impostor.uniqueId = this._impostors.push(impostor);
  33306. //if no parent, generate the body
  33307. if (!impostor.parent) {
  33308. this._physicsPlugin.generatePhysicsBody(impostor);
  33309. }
  33310. };
  33311. /**
  33312. * Remove an impostor from the engine.
  33313. * This impostor and its mesh will not longer be updated by the physics engine.
  33314. * @param {PhysicsImpostor} impostor the impostor to remove
  33315. */
  33316. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  33317. var index = this._impostors.indexOf(impostor);
  33318. if (index > -1) {
  33319. var removed = this._impostors.splice(index, 1);
  33320. //Is it needed?
  33321. if (removed.length) {
  33322. //this will also remove it from the world.
  33323. removed[0].physicsBody = null;
  33324. }
  33325. }
  33326. };
  33327. /**
  33328. * Add a joint to the physics engine
  33329. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  33330. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  33331. * @param {PhysicsJoint} the joint that will connect both impostors.
  33332. */
  33333. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  33334. var impostorJoint = {
  33335. mainImpostor: mainImpostor,
  33336. connectedImpostor: connectedImpostor,
  33337. joint: joint
  33338. };
  33339. joint.physicsPlugin = this._physicsPlugin;
  33340. this._joints.push(impostorJoint);
  33341. this._physicsPlugin.generateJoint(impostorJoint);
  33342. };
  33343. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  33344. var matchingJoints = this._joints.filter(function (impostorJoint) {
  33345. return (impostorJoint.connectedImpostor === connectedImpostor
  33346. && impostorJoint.joint === joint
  33347. && impostorJoint.mainImpostor === mainImpostor);
  33348. });
  33349. if (matchingJoints.length) {
  33350. this._physicsPlugin.removeJoint(matchingJoints[0]);
  33351. }
  33352. };
  33353. /**
  33354. * Called by the scene. no need to call it.
  33355. */
  33356. PhysicsEngine.prototype._step = function (delta) {
  33357. var _this = this;
  33358. //check if any mesh has no body / requires an update
  33359. this._impostors.forEach(function (impostor) {
  33360. if (impostor.isBodyInitRequired()) {
  33361. _this._physicsPlugin.generatePhysicsBody(impostor);
  33362. }
  33363. });
  33364. if (delta > 0.1) {
  33365. delta = 0.1;
  33366. }
  33367. else if (delta <= 0) {
  33368. delta = 1.0 / 60.0;
  33369. }
  33370. this._physicsPlugin.executeStep(delta, this._impostors);
  33371. };
  33372. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  33373. return this._physicsPlugin;
  33374. };
  33375. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  33376. for (var i = 0; i < this._impostors.length; ++i) {
  33377. if (this._impostors[i].object === object) {
  33378. return this._impostors[i];
  33379. }
  33380. }
  33381. };
  33382. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  33383. for (var i = 0; i < this._impostors.length; ++i) {
  33384. if (this._impostors[i].physicsBody === body) {
  33385. return this._impostors[i];
  33386. }
  33387. }
  33388. };
  33389. return PhysicsEngine;
  33390. }());
  33391. // Statics, Legacy support.
  33392. /**
  33393. * @Deprecated
  33394. *
  33395. */
  33396. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  33397. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  33398. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  33399. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  33400. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  33401. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  33402. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  33403. PhysicsEngine.CapsuleImpostor = -1;
  33404. PhysicsEngine.ConeImpostor = -1;
  33405. PhysicsEngine.ConvexHullImpostor = -1;
  33406. PhysicsEngine.Epsilon = 0.001;
  33407. BABYLON.PhysicsEngine = PhysicsEngine;
  33408. })(BABYLON || (BABYLON = {}));
  33409. //# sourceMappingURL=babylon.physicsEngine.js.map
  33410. var BABYLON;
  33411. (function (BABYLON) {
  33412. var VertexData = (function () {
  33413. function VertexData() {
  33414. }
  33415. VertexData.prototype.set = function (data, kind) {
  33416. switch (kind) {
  33417. case BABYLON.VertexBuffer.PositionKind:
  33418. this.positions = data;
  33419. break;
  33420. case BABYLON.VertexBuffer.NormalKind:
  33421. this.normals = data;
  33422. break;
  33423. case BABYLON.VertexBuffer.UVKind:
  33424. this.uvs = data;
  33425. break;
  33426. case BABYLON.VertexBuffer.UV2Kind:
  33427. this.uvs2 = data;
  33428. break;
  33429. case BABYLON.VertexBuffer.UV3Kind:
  33430. this.uvs3 = data;
  33431. break;
  33432. case BABYLON.VertexBuffer.UV4Kind:
  33433. this.uvs4 = data;
  33434. break;
  33435. case BABYLON.VertexBuffer.UV5Kind:
  33436. this.uvs5 = data;
  33437. break;
  33438. case BABYLON.VertexBuffer.UV6Kind:
  33439. this.uvs6 = data;
  33440. break;
  33441. case BABYLON.VertexBuffer.ColorKind:
  33442. this.colors = data;
  33443. break;
  33444. case BABYLON.VertexBuffer.MatricesIndicesKind:
  33445. this.matricesIndices = data;
  33446. break;
  33447. case BABYLON.VertexBuffer.MatricesWeightsKind:
  33448. this.matricesWeights = data;
  33449. break;
  33450. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  33451. this.matricesIndicesExtra = data;
  33452. break;
  33453. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  33454. this.matricesWeightsExtra = data;
  33455. break;
  33456. }
  33457. };
  33458. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  33459. this._applyTo(mesh, updatable);
  33460. };
  33461. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  33462. this._applyTo(geometry, updatable);
  33463. };
  33464. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  33465. this._update(mesh);
  33466. };
  33467. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  33468. this._update(geometry);
  33469. };
  33470. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  33471. if (this.positions) {
  33472. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  33473. }
  33474. if (this.normals) {
  33475. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  33476. }
  33477. if (this.uvs) {
  33478. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  33479. }
  33480. if (this.uvs2) {
  33481. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  33482. }
  33483. if (this.uvs3) {
  33484. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  33485. }
  33486. if (this.uvs4) {
  33487. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  33488. }
  33489. if (this.uvs5) {
  33490. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  33491. }
  33492. if (this.uvs6) {
  33493. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  33494. }
  33495. if (this.colors) {
  33496. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  33497. }
  33498. if (this.matricesIndices) {
  33499. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  33500. }
  33501. if (this.matricesWeights) {
  33502. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  33503. }
  33504. if (this.matricesIndicesExtra) {
  33505. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  33506. }
  33507. if (this.matricesWeightsExtra) {
  33508. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  33509. }
  33510. if (this.indices) {
  33511. meshOrGeometry.setIndices(this.indices);
  33512. }
  33513. };
  33514. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  33515. if (this.positions) {
  33516. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  33517. }
  33518. if (this.normals) {
  33519. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  33520. }
  33521. if (this.uvs) {
  33522. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  33523. }
  33524. if (this.uvs2) {
  33525. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  33526. }
  33527. if (this.uvs3) {
  33528. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  33529. }
  33530. if (this.uvs4) {
  33531. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  33532. }
  33533. if (this.uvs5) {
  33534. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  33535. }
  33536. if (this.uvs6) {
  33537. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  33538. }
  33539. if (this.colors) {
  33540. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  33541. }
  33542. if (this.matricesIndices) {
  33543. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  33544. }
  33545. if (this.matricesWeights) {
  33546. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  33547. }
  33548. if (this.matricesIndicesExtra) {
  33549. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  33550. }
  33551. if (this.matricesWeightsExtra) {
  33552. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  33553. }
  33554. if (this.indices) {
  33555. meshOrGeometry.setIndices(this.indices);
  33556. }
  33557. };
  33558. VertexData.prototype.transform = function (matrix) {
  33559. var transformed = BABYLON.Vector3.Zero();
  33560. var index;
  33561. if (this.positions) {
  33562. var position = BABYLON.Vector3.Zero();
  33563. for (index = 0; index < this.positions.length; index += 3) {
  33564. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  33565. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  33566. this.positions[index] = transformed.x;
  33567. this.positions[index + 1] = transformed.y;
  33568. this.positions[index + 2] = transformed.z;
  33569. }
  33570. }
  33571. if (this.normals) {
  33572. var normal = BABYLON.Vector3.Zero();
  33573. for (index = 0; index < this.normals.length; index += 3) {
  33574. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  33575. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  33576. this.normals[index] = transformed.x;
  33577. this.normals[index + 1] = transformed.y;
  33578. this.normals[index + 2] = transformed.z;
  33579. }
  33580. }
  33581. };
  33582. VertexData.prototype.merge = function (other) {
  33583. if (other.indices) {
  33584. if (!this.indices) {
  33585. this.indices = [];
  33586. }
  33587. var offset = this.positions ? this.positions.length / 3 : 0;
  33588. for (var index = 0; index < other.indices.length; index++) {
  33589. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  33590. this.indices.push(other.indices[index] + offset);
  33591. }
  33592. }
  33593. this.positions = this._mergeElement(this.positions, other.positions);
  33594. this.normals = this._mergeElement(this.normals, other.normals);
  33595. this.uvs = this._mergeElement(this.uvs, other.uvs);
  33596. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  33597. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  33598. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  33599. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  33600. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  33601. this.colors = this._mergeElement(this.colors, other.colors);
  33602. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  33603. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  33604. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  33605. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  33606. };
  33607. VertexData.prototype._mergeElement = function (source, other) {
  33608. if (!other)
  33609. return source;
  33610. if (!source)
  33611. return other;
  33612. var len = other.length + source.length;
  33613. var isSrcTypedArray = source instanceof Float32Array;
  33614. var isOthTypedArray = other instanceof Float32Array;
  33615. // use non-loop method when the source is Float32Array
  33616. if (isSrcTypedArray) {
  33617. var ret32 = new Float32Array(len);
  33618. ret32.set(source);
  33619. ret32.set(other, source.length);
  33620. return ret32;
  33621. }
  33622. else if (!isOthTypedArray) {
  33623. return source.concat(other);
  33624. }
  33625. else {
  33626. var ret = source.slice(0); // copy source to a separate array
  33627. for (var i = 0, len = other.length; i < len; i++) {
  33628. ret.push(other[i]);
  33629. }
  33630. return ret;
  33631. }
  33632. };
  33633. VertexData.prototype.serialize = function () {
  33634. var serializationObject = this.serialize();
  33635. if (this.positions) {
  33636. serializationObject.positions = this.positions;
  33637. }
  33638. if (this.normals) {
  33639. serializationObject.normals = this.normals;
  33640. }
  33641. if (this.uvs) {
  33642. serializationObject.uvs = this.uvs;
  33643. }
  33644. if (this.uvs2) {
  33645. serializationObject.uvs2 = this.uvs2;
  33646. }
  33647. if (this.uvs3) {
  33648. serializationObject.uvs3 = this.uvs3;
  33649. }
  33650. if (this.uvs4) {
  33651. serializationObject.uvs4 = this.uvs4;
  33652. }
  33653. if (this.uvs5) {
  33654. serializationObject.uvs5 = this.uvs5;
  33655. }
  33656. if (this.uvs6) {
  33657. serializationObject.uvs6 = this.uvs6;
  33658. }
  33659. if (this.colors) {
  33660. serializationObject.colors = this.colors;
  33661. }
  33662. if (this.matricesIndices) {
  33663. serializationObject.matricesIndices = this.matricesIndices;
  33664. serializationObject.matricesIndices._isExpanded = true;
  33665. }
  33666. if (this.matricesWeights) {
  33667. serializationObject.matricesWeights = this.matricesWeights;
  33668. }
  33669. if (this.matricesIndicesExtra) {
  33670. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  33671. serializationObject.matricesIndicesExtra._isExpanded = true;
  33672. }
  33673. if (this.matricesWeightsExtra) {
  33674. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  33675. }
  33676. serializationObject.indices = this.indices;
  33677. return serializationObject;
  33678. };
  33679. // Statics
  33680. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  33681. return VertexData._ExtractFrom(mesh, copyWhenShared);
  33682. };
  33683. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  33684. return VertexData._ExtractFrom(geometry, copyWhenShared);
  33685. };
  33686. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  33687. var result = new VertexData();
  33688. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33689. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  33690. }
  33691. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33692. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  33693. }
  33694. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33695. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  33696. }
  33697. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  33698. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  33699. }
  33700. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  33701. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  33702. }
  33703. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  33704. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  33705. }
  33706. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  33707. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  33708. }
  33709. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  33710. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  33711. }
  33712. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  33713. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  33714. }
  33715. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33716. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  33717. }
  33718. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33719. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  33720. }
  33721. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  33722. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  33723. }
  33724. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33725. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  33726. }
  33727. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  33728. return result;
  33729. };
  33730. VertexData.CreateRibbon = function (options) {
  33731. var pathArray = options.pathArray;
  33732. var closeArray = options.closeArray || false;
  33733. var closePath = options.closePath || false;
  33734. var invertUV = options.invertUV || false;
  33735. var defaultOffset = Math.floor(pathArray[0].length / 2);
  33736. var offset = options.offset || defaultOffset;
  33737. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  33738. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33739. var positions = [];
  33740. var indices = [];
  33741. var normals = [];
  33742. var uvs = [];
  33743. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  33744. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  33745. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  33746. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  33747. var minlg; // minimal length among all paths from pathArray
  33748. var lg = []; // array of path lengths : nb of vertex per path
  33749. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  33750. var p; // path iterator
  33751. var i; // point iterator
  33752. var j; // point iterator
  33753. // if single path in pathArray
  33754. if (pathArray.length < 2) {
  33755. var ar1 = [];
  33756. var ar2 = [];
  33757. for (i = 0; i < pathArray[0].length - offset; i++) {
  33758. ar1.push(pathArray[0][i]);
  33759. ar2.push(pathArray[0][i + offset]);
  33760. }
  33761. pathArray = [ar1, ar2];
  33762. }
  33763. // positions and horizontal distances (u)
  33764. var idc = 0;
  33765. var closePathCorr = (closePath) ? 1 : 0;
  33766. var path;
  33767. var l;
  33768. minlg = pathArray[0].length;
  33769. var vectlg;
  33770. var dist;
  33771. for (p = 0; p < pathArray.length; p++) {
  33772. uTotalDistance[p] = 0;
  33773. us[p] = [0];
  33774. path = pathArray[p];
  33775. l = path.length;
  33776. minlg = (minlg < l) ? minlg : l;
  33777. j = 0;
  33778. while (j < l) {
  33779. positions.push(path[j].x, path[j].y, path[j].z);
  33780. if (j > 0) {
  33781. vectlg = path[j].subtract(path[j - 1]).length();
  33782. dist = vectlg + uTotalDistance[p];
  33783. us[p].push(dist);
  33784. uTotalDistance[p] = dist;
  33785. }
  33786. j++;
  33787. }
  33788. if (closePath) {
  33789. j--;
  33790. positions.push(path[0].x, path[0].y, path[0].z);
  33791. vectlg = path[j].subtract(path[0]).length();
  33792. dist = vectlg + uTotalDistance[p];
  33793. us[p].push(dist);
  33794. uTotalDistance[p] = dist;
  33795. }
  33796. lg[p] = l + closePathCorr;
  33797. idx[p] = idc;
  33798. idc += (l + closePathCorr);
  33799. }
  33800. // vertical distances (v)
  33801. var path1;
  33802. var path2;
  33803. var vertex1;
  33804. var vertex2;
  33805. for (i = 0; i < minlg + closePathCorr; i++) {
  33806. vTotalDistance[i] = 0;
  33807. vs[i] = [0];
  33808. for (p = 0; p < pathArray.length - 1; p++) {
  33809. path1 = pathArray[p];
  33810. path2 = pathArray[p + 1];
  33811. if (i === minlg) {
  33812. vertex1 = path1[0];
  33813. vertex2 = path2[0];
  33814. }
  33815. else {
  33816. vertex1 = path1[i];
  33817. vertex2 = path2[i];
  33818. }
  33819. vectlg = vertex2.subtract(vertex1).length();
  33820. dist = vectlg + vTotalDistance[i];
  33821. vs[i].push(dist);
  33822. vTotalDistance[i] = dist;
  33823. }
  33824. if (closeArray) {
  33825. path1 = pathArray[p];
  33826. path2 = pathArray[0];
  33827. if (i === minlg) {
  33828. vertex2 = path2[0];
  33829. }
  33830. vectlg = vertex2.subtract(vertex1).length();
  33831. dist = vectlg + vTotalDistance[i];
  33832. vTotalDistance[i] = dist;
  33833. }
  33834. }
  33835. // uvs
  33836. var u;
  33837. var v;
  33838. for (p = 0; p < pathArray.length; p++) {
  33839. for (i = 0; i < minlg + closePathCorr; i++) {
  33840. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  33841. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  33842. if (invertUV) {
  33843. uvs.push(v, u);
  33844. }
  33845. else {
  33846. uvs.push(u, v);
  33847. }
  33848. }
  33849. }
  33850. // indices
  33851. p = 0; // path index
  33852. var pi = 0; // positions array index
  33853. var l1 = lg[p] - 1; // path1 length
  33854. var l2 = lg[p + 1] - 1; // path2 length
  33855. var min = (l1 < l2) ? l1 : l2; // current path stop index
  33856. var shft = idx[1] - idx[0]; // shift
  33857. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  33858. while (pi <= min && p < path1nb) {
  33859. // 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
  33860. indices.push(pi, pi + shft, pi + 1);
  33861. indices.push(pi + shft + 1, pi + 1, pi + shft);
  33862. pi += 1;
  33863. if (pi === min) {
  33864. p++;
  33865. if (p === lg.length - 1) {
  33866. shft = idx[0] - idx[p];
  33867. l1 = lg[p] - 1;
  33868. l2 = lg[0] - 1;
  33869. }
  33870. else {
  33871. shft = idx[p + 1] - idx[p];
  33872. l1 = lg[p] - 1;
  33873. l2 = lg[p + 1] - 1;
  33874. }
  33875. pi = idx[p];
  33876. min = (l1 < l2) ? l1 + pi : l2 + pi;
  33877. }
  33878. }
  33879. // normals
  33880. VertexData.ComputeNormals(positions, indices, normals);
  33881. if (closePath) {
  33882. var indexFirst = 0;
  33883. var indexLast = 0;
  33884. for (p = 0; p < pathArray.length; p++) {
  33885. indexFirst = idx[p] * 3;
  33886. if (p + 1 < pathArray.length) {
  33887. indexLast = (idx[p + 1] - 1) * 3;
  33888. }
  33889. else {
  33890. indexLast = normals.length - 3;
  33891. }
  33892. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  33893. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  33894. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  33895. normals[indexLast] = normals[indexFirst];
  33896. normals[indexLast + 1] = normals[indexFirst + 1];
  33897. normals[indexLast + 2] = normals[indexFirst + 2];
  33898. }
  33899. }
  33900. // sides
  33901. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33902. // Result
  33903. var vertexData = new VertexData();
  33904. vertexData.indices = indices;
  33905. vertexData.positions = positions;
  33906. vertexData.normals = normals;
  33907. vertexData.uvs = uvs;
  33908. if (closePath) {
  33909. vertexData._idx = idx;
  33910. }
  33911. return vertexData;
  33912. };
  33913. VertexData.CreateBox = function (options) {
  33914. var normalsSource = [
  33915. new BABYLON.Vector3(0, 0, 1),
  33916. new BABYLON.Vector3(0, 0, -1),
  33917. new BABYLON.Vector3(1, 0, 0),
  33918. new BABYLON.Vector3(-1, 0, 0),
  33919. new BABYLON.Vector3(0, 1, 0),
  33920. new BABYLON.Vector3(0, -1, 0)
  33921. ];
  33922. var indices = [];
  33923. var positions = [];
  33924. var normals = [];
  33925. var uvs = [];
  33926. var width = options.width || options.size || 1;
  33927. var height = options.height || options.size || 1;
  33928. var depth = options.depth || options.size || 1;
  33929. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33930. var faceUV = options.faceUV || new Array(6);
  33931. var faceColors = options.faceColors;
  33932. var colors = [];
  33933. // default face colors and UV if undefined
  33934. for (var f = 0; f < 6; f++) {
  33935. if (faceUV[f] === undefined) {
  33936. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33937. }
  33938. if (faceColors && faceColors[f] === undefined) {
  33939. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33940. }
  33941. }
  33942. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  33943. // Create each face in turn.
  33944. for (var index = 0; index < normalsSource.length; index++) {
  33945. var normal = normalsSource[index];
  33946. // Get two vectors perpendicular to the face normal and to each other.
  33947. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  33948. var side2 = BABYLON.Vector3.Cross(normal, side1);
  33949. // Six indices (two triangles) per face.
  33950. var verticesLength = positions.length / 3;
  33951. indices.push(verticesLength);
  33952. indices.push(verticesLength + 1);
  33953. indices.push(verticesLength + 2);
  33954. indices.push(verticesLength);
  33955. indices.push(verticesLength + 2);
  33956. indices.push(verticesLength + 3);
  33957. // Four vertices per face.
  33958. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  33959. positions.push(vertex.x, vertex.y, vertex.z);
  33960. normals.push(normal.x, normal.y, normal.z);
  33961. uvs.push(faceUV[index].z, faceUV[index].w);
  33962. if (faceColors) {
  33963. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33964. }
  33965. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  33966. positions.push(vertex.x, vertex.y, vertex.z);
  33967. normals.push(normal.x, normal.y, normal.z);
  33968. uvs.push(faceUV[index].x, faceUV[index].w);
  33969. if (faceColors) {
  33970. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33971. }
  33972. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33973. positions.push(vertex.x, vertex.y, vertex.z);
  33974. normals.push(normal.x, normal.y, normal.z);
  33975. uvs.push(faceUV[index].x, faceUV[index].y);
  33976. if (faceColors) {
  33977. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33978. }
  33979. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33980. positions.push(vertex.x, vertex.y, vertex.z);
  33981. normals.push(normal.x, normal.y, normal.z);
  33982. uvs.push(faceUV[index].z, faceUV[index].y);
  33983. if (faceColors) {
  33984. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33985. }
  33986. }
  33987. // sides
  33988. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33989. // Result
  33990. var vertexData = new VertexData();
  33991. vertexData.indices = indices;
  33992. vertexData.positions = positions;
  33993. vertexData.normals = normals;
  33994. vertexData.uvs = uvs;
  33995. if (faceColors) {
  33996. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33997. vertexData.colors = totalColors;
  33998. }
  33999. return vertexData;
  34000. };
  34001. VertexData.CreateSphere = function (options) {
  34002. var segments = options.segments || 32;
  34003. var diameterX = options.diameterX || options.diameter || 1;
  34004. var diameterY = options.diameterY || options.diameter || 1;
  34005. var diameterZ = options.diameterZ || options.diameter || 1;
  34006. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34007. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  34008. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34009. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  34010. var totalZRotationSteps = 2 + segments;
  34011. var totalYRotationSteps = 2 * totalZRotationSteps;
  34012. var indices = [];
  34013. var positions = [];
  34014. var normals = [];
  34015. var uvs = [];
  34016. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  34017. var normalizedZ = zRotationStep / totalZRotationSteps;
  34018. var angleZ = normalizedZ * Math.PI * slice;
  34019. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  34020. var normalizedY = yRotationStep / totalYRotationSteps;
  34021. var angleY = normalizedY * Math.PI * 2 * arc;
  34022. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  34023. var rotationY = BABYLON.Matrix.RotationY(angleY);
  34024. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  34025. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  34026. var vertex = complete.multiply(radius);
  34027. var normal = complete.divide(radius).normalize();
  34028. positions.push(vertex.x, vertex.y, vertex.z);
  34029. normals.push(normal.x, normal.y, normal.z);
  34030. uvs.push(normalizedY, normalizedZ);
  34031. }
  34032. if (zRotationStep > 0) {
  34033. var verticesCount = positions.length / 3;
  34034. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  34035. indices.push((firstIndex));
  34036. indices.push((firstIndex + 1));
  34037. indices.push(firstIndex + totalYRotationSteps + 1);
  34038. indices.push((firstIndex + totalYRotationSteps + 1));
  34039. indices.push((firstIndex + 1));
  34040. indices.push((firstIndex + totalYRotationSteps + 2));
  34041. }
  34042. }
  34043. }
  34044. // Sides
  34045. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34046. // Result
  34047. var vertexData = new VertexData();
  34048. vertexData.indices = indices;
  34049. vertexData.positions = positions;
  34050. vertexData.normals = normals;
  34051. vertexData.uvs = uvs;
  34052. return vertexData;
  34053. };
  34054. // Cylinder and cone
  34055. VertexData.CreateCylinder = function (options) {
  34056. var height = options.height || 2;
  34057. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  34058. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  34059. var tessellation = options.tessellation || 24;
  34060. var subdivisions = options.subdivisions || 1;
  34061. var hasRings = options.hasRings;
  34062. var enclose = options.enclose;
  34063. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34064. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34065. var faceUV = options.faceUV || new Array(3);
  34066. var faceColors = options.faceColors;
  34067. // default face colors and UV if undefined
  34068. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  34069. var ringNb = (hasRings) ? subdivisions : 1;
  34070. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  34071. var f;
  34072. for (f = 0; f < surfaceNb; f++) {
  34073. if (faceColors && faceColors[f] === undefined) {
  34074. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34075. }
  34076. }
  34077. for (f = 0; f < surfaceNb; f++) {
  34078. if (faceUV && faceUV[f] === undefined) {
  34079. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34080. }
  34081. }
  34082. var indices = [];
  34083. var positions = [];
  34084. var normals = [];
  34085. var uvs = [];
  34086. var colors = [];
  34087. var angle_step = Math.PI * 2 * arc / tessellation;
  34088. var angle;
  34089. var h;
  34090. var radius;
  34091. var tan = (diameterBottom - diameterTop) / 2 / height;
  34092. var ringVertex = BABYLON.Vector3.Zero();
  34093. var ringNormal = BABYLON.Vector3.Zero();
  34094. var ringFirstVertex = BABYLON.Vector3.Zero();
  34095. var ringFirstNormal = BABYLON.Vector3.Zero();
  34096. var quadNormal = BABYLON.Vector3.Zero();
  34097. var Y = BABYLON.Axis.Y;
  34098. // positions, normals, uvs
  34099. var i;
  34100. var j;
  34101. var r;
  34102. var ringIdx = 1;
  34103. var s = 1; // surface index
  34104. var cs = 0;
  34105. var v = 0;
  34106. for (i = 0; i <= subdivisions; i++) {
  34107. h = i / subdivisions;
  34108. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  34109. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  34110. for (r = 0; r < ringIdx; r++) {
  34111. if (hasRings) {
  34112. s += r;
  34113. }
  34114. if (enclose) {
  34115. s += 2 * r;
  34116. }
  34117. for (j = 0; j <= tessellation; j++) {
  34118. angle = j * angle_step;
  34119. // position
  34120. ringVertex.x = Math.cos(-angle) * radius;
  34121. ringVertex.y = -height / 2 + h * height;
  34122. ringVertex.z = Math.sin(-angle) * radius;
  34123. // normal
  34124. if (diameterTop === 0 && i === subdivisions) {
  34125. // if no top cap, reuse former normals
  34126. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  34127. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  34128. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  34129. }
  34130. else {
  34131. ringNormal.x = ringVertex.x;
  34132. ringNormal.z = ringVertex.z;
  34133. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  34134. ringNormal.normalize();
  34135. }
  34136. // keep first ring vertex values for enclose
  34137. if (j === 0) {
  34138. ringFirstVertex.copyFrom(ringVertex);
  34139. ringFirstNormal.copyFrom(ringNormal);
  34140. }
  34141. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  34142. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  34143. if (hasRings) {
  34144. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  34145. }
  34146. else {
  34147. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  34148. }
  34149. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  34150. if (faceColors) {
  34151. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  34152. }
  34153. }
  34154. // if enclose, add four vertices and their dedicated normals
  34155. if (arc !== 1 && enclose) {
  34156. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  34157. positions.push(0, ringVertex.y, 0);
  34158. positions.push(0, ringVertex.y, 0);
  34159. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  34160. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  34161. quadNormal.normalize();
  34162. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  34163. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  34164. quadNormal.normalize();
  34165. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  34166. if (hasRings) {
  34167. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  34168. }
  34169. else {
  34170. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  34171. }
  34172. uvs.push(faceUV[s + 1].x, v);
  34173. uvs.push(faceUV[s + 1].z, v);
  34174. if (hasRings) {
  34175. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  34176. }
  34177. else {
  34178. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  34179. }
  34180. uvs.push(faceUV[s + 2].x, v);
  34181. uvs.push(faceUV[s + 2].z, v);
  34182. if (faceColors) {
  34183. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  34184. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  34185. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  34186. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  34187. }
  34188. }
  34189. if (cs !== s) {
  34190. cs = s;
  34191. }
  34192. }
  34193. }
  34194. // indices
  34195. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  34196. var s;
  34197. i = 0;
  34198. for (s = 0; s < subdivisions; s++) {
  34199. for (j = 0; j < tessellation; j++) {
  34200. var i0 = i * (e + 1) + j;
  34201. var i1 = (i + 1) * (e + 1) + j;
  34202. var i2 = i * (e + 1) + (j + 1);
  34203. var i3 = (i + 1) * (e + 1) + (j + 1);
  34204. indices.push(i0, i1, i2);
  34205. indices.push(i3, i2, i1);
  34206. }
  34207. if (arc !== 1 && enclose) {
  34208. indices.push(i0 + 2, i1 + 2, i2 + 2);
  34209. indices.push(i3 + 2, i2 + 2, i1 + 2);
  34210. indices.push(i0 + 4, i1 + 4, i2 + 4);
  34211. indices.push(i3 + 4, i2 + 4, i1 + 4);
  34212. }
  34213. i = (hasRings) ? (i + 2) : (i + 1);
  34214. }
  34215. // Caps
  34216. var createCylinderCap = function (isTop) {
  34217. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  34218. if (radius === 0) {
  34219. return;
  34220. }
  34221. // Cap positions, normals & uvs
  34222. var angle;
  34223. var circleVector;
  34224. var i;
  34225. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  34226. var c;
  34227. if (faceColors) {
  34228. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  34229. }
  34230. // cap center
  34231. var vbase = positions.length / 3;
  34232. var offset = isTop ? height / 2 : -height / 2;
  34233. var center = new BABYLON.Vector3(0, offset, 0);
  34234. positions.push(center.x, center.y, center.z);
  34235. normals.push(0, isTop ? 1 : -1, 0);
  34236. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  34237. if (faceColors) {
  34238. colors.push(c.r, c.g, c.b, c.a);
  34239. }
  34240. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  34241. for (i = 0; i <= tessellation; i++) {
  34242. angle = Math.PI * 2 * i * arc / tessellation;
  34243. var cos = Math.cos(-angle);
  34244. var sin = Math.sin(-angle);
  34245. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  34246. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  34247. positions.push(circleVector.x, circleVector.y, circleVector.z);
  34248. normals.push(0, isTop ? 1 : -1, 0);
  34249. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  34250. if (faceColors) {
  34251. colors.push(c.r, c.g, c.b, c.a);
  34252. }
  34253. }
  34254. // Cap indices
  34255. for (i = 0; i < tessellation; i++) {
  34256. if (!isTop) {
  34257. indices.push(vbase);
  34258. indices.push(vbase + (i + 1));
  34259. indices.push(vbase + (i + 2));
  34260. }
  34261. else {
  34262. indices.push(vbase);
  34263. indices.push(vbase + (i + 2));
  34264. indices.push(vbase + (i + 1));
  34265. }
  34266. }
  34267. };
  34268. // add caps to geometry
  34269. createCylinderCap(false);
  34270. createCylinderCap(true);
  34271. // Sides
  34272. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34273. var vertexData = new VertexData();
  34274. vertexData.indices = indices;
  34275. vertexData.positions = positions;
  34276. vertexData.normals = normals;
  34277. vertexData.uvs = uvs;
  34278. if (faceColors) {
  34279. vertexData.colors = colors;
  34280. }
  34281. return vertexData;
  34282. };
  34283. VertexData.CreateTorus = function (options) {
  34284. var indices = [];
  34285. var positions = [];
  34286. var normals = [];
  34287. var uvs = [];
  34288. var diameter = options.diameter || 1;
  34289. var thickness = options.thickness || 0.5;
  34290. var tessellation = options.tessellation || 16;
  34291. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34292. var stride = tessellation + 1;
  34293. for (var i = 0; i <= tessellation; i++) {
  34294. var u = i / tessellation;
  34295. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  34296. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  34297. for (var j = 0; j <= tessellation; j++) {
  34298. var v = 1 - j / tessellation;
  34299. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  34300. var dx = Math.cos(innerAngle);
  34301. var dy = Math.sin(innerAngle);
  34302. // Create a vertex.
  34303. var normal = new BABYLON.Vector3(dx, dy, 0);
  34304. var position = normal.scale(thickness / 2);
  34305. var textureCoordinate = new BABYLON.Vector2(u, v);
  34306. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  34307. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  34308. positions.push(position.x, position.y, position.z);
  34309. normals.push(normal.x, normal.y, normal.z);
  34310. uvs.push(textureCoordinate.x, textureCoordinate.y);
  34311. // And create indices for two triangles.
  34312. var nextI = (i + 1) % stride;
  34313. var nextJ = (j + 1) % stride;
  34314. indices.push(i * stride + j);
  34315. indices.push(i * stride + nextJ);
  34316. indices.push(nextI * stride + j);
  34317. indices.push(i * stride + nextJ);
  34318. indices.push(nextI * stride + nextJ);
  34319. indices.push(nextI * stride + j);
  34320. }
  34321. }
  34322. // Sides
  34323. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34324. // Result
  34325. var vertexData = new VertexData();
  34326. vertexData.indices = indices;
  34327. vertexData.positions = positions;
  34328. vertexData.normals = normals;
  34329. vertexData.uvs = uvs;
  34330. return vertexData;
  34331. };
  34332. VertexData.CreateLineSystem = function (options) {
  34333. var indices = [];
  34334. var positions = [];
  34335. var lines = options.lines;
  34336. var idx = 0;
  34337. for (var l = 0; l < lines.length; l++) {
  34338. var points = lines[l];
  34339. for (var index = 0; index < points.length; index++) {
  34340. positions.push(points[index].x, points[index].y, points[index].z);
  34341. if (index > 0) {
  34342. indices.push(idx - 1);
  34343. indices.push(idx);
  34344. }
  34345. idx++;
  34346. }
  34347. }
  34348. var vertexData = new VertexData();
  34349. vertexData.indices = indices;
  34350. vertexData.positions = positions;
  34351. return vertexData;
  34352. };
  34353. VertexData.CreateDashedLines = function (options) {
  34354. var dashSize = options.dashSize || 3;
  34355. var gapSize = options.gapSize || 1;
  34356. var dashNb = options.dashNb || 200;
  34357. var points = options.points;
  34358. var positions = new Array();
  34359. var indices = new Array();
  34360. var curvect = BABYLON.Vector3.Zero();
  34361. var lg = 0;
  34362. var nb = 0;
  34363. var shft = 0;
  34364. var dashshft = 0;
  34365. var curshft = 0;
  34366. var idx = 0;
  34367. var i = 0;
  34368. for (i = 0; i < points.length - 1; i++) {
  34369. points[i + 1].subtractToRef(points[i], curvect);
  34370. lg += curvect.length();
  34371. }
  34372. shft = lg / dashNb;
  34373. dashshft = dashSize * shft / (dashSize + gapSize);
  34374. for (i = 0; i < points.length - 1; i++) {
  34375. points[i + 1].subtractToRef(points[i], curvect);
  34376. nb = Math.floor(curvect.length() / shft);
  34377. curvect.normalize();
  34378. for (var j = 0; j < nb; j++) {
  34379. curshft = shft * j;
  34380. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  34381. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  34382. indices.push(idx, idx + 1);
  34383. idx += 2;
  34384. }
  34385. }
  34386. // Result
  34387. var vertexData = new VertexData();
  34388. vertexData.positions = positions;
  34389. vertexData.indices = indices;
  34390. return vertexData;
  34391. };
  34392. VertexData.CreateGround = function (options) {
  34393. var indices = [];
  34394. var positions = [];
  34395. var normals = [];
  34396. var uvs = [];
  34397. var row, col;
  34398. var width = options.width || 1;
  34399. var height = options.height || 1;
  34400. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  34401. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  34402. for (row = 0; row <= subdivisionsY; row++) {
  34403. for (col = 0; col <= subdivisionsX; col++) {
  34404. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  34405. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34406. positions.push(position.x, position.y, position.z);
  34407. normals.push(normal.x, normal.y, normal.z);
  34408. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  34409. }
  34410. }
  34411. for (row = 0; row < subdivisionsY; row++) {
  34412. for (col = 0; col < subdivisionsX; col++) {
  34413. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34414. indices.push(col + 1 + row * (subdivisionsX + 1));
  34415. indices.push(col + row * (subdivisionsX + 1));
  34416. indices.push(col + (row + 1) * (subdivisionsX + 1));
  34417. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  34418. indices.push(col + row * (subdivisionsX + 1));
  34419. }
  34420. }
  34421. // Result
  34422. var vertexData = new VertexData();
  34423. vertexData.indices = indices;
  34424. vertexData.positions = positions;
  34425. vertexData.normals = normals;
  34426. vertexData.uvs = uvs;
  34427. return vertexData;
  34428. };
  34429. VertexData.CreateTiledGround = function (options) {
  34430. var xmin = options.xmin || -1.0;
  34431. var zmin = options.zmin || -1.0;
  34432. var xmax = options.xmax || 1.0;
  34433. var zmax = options.zmax || 1.0;
  34434. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  34435. var precision = options.precision || { w: 1, h: 1 };
  34436. var indices = [];
  34437. var positions = [];
  34438. var normals = [];
  34439. var uvs = [];
  34440. var row, col, tileRow, tileCol;
  34441. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  34442. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  34443. precision.w = (precision.w < 1) ? 1 : precision.w;
  34444. precision.h = (precision.h < 1) ? 1 : precision.h;
  34445. var tileSize = {
  34446. 'w': (xmax - xmin) / subdivisions.w,
  34447. 'h': (zmax - zmin) / subdivisions.h
  34448. };
  34449. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  34450. // Indices
  34451. var base = positions.length / 3;
  34452. var rowLength = precision.w + 1;
  34453. for (row = 0; row < precision.h; row++) {
  34454. for (col = 0; col < precision.w; col++) {
  34455. var square = [
  34456. base + col + row * rowLength,
  34457. base + (col + 1) + row * rowLength,
  34458. base + (col + 1) + (row + 1) * rowLength,
  34459. base + col + (row + 1) * rowLength
  34460. ];
  34461. indices.push(square[1]);
  34462. indices.push(square[2]);
  34463. indices.push(square[3]);
  34464. indices.push(square[0]);
  34465. indices.push(square[1]);
  34466. indices.push(square[3]);
  34467. }
  34468. }
  34469. // Position, normals and uvs
  34470. var position = BABYLON.Vector3.Zero();
  34471. var normal = new BABYLON.Vector3(0, 1.0, 0);
  34472. for (row = 0; row <= precision.h; row++) {
  34473. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  34474. for (col = 0; col <= precision.w; col++) {
  34475. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  34476. position.y = 0;
  34477. positions.push(position.x, position.y, position.z);
  34478. normals.push(normal.x, normal.y, normal.z);
  34479. uvs.push(col / precision.w, row / precision.h);
  34480. }
  34481. }
  34482. }
  34483. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  34484. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  34485. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  34486. }
  34487. }
  34488. // Result
  34489. var vertexData = new VertexData();
  34490. vertexData.indices = indices;
  34491. vertexData.positions = positions;
  34492. vertexData.normals = normals;
  34493. vertexData.uvs = uvs;
  34494. return vertexData;
  34495. };
  34496. VertexData.CreateGroundFromHeightMap = function (options) {
  34497. var indices = [];
  34498. var positions = [];
  34499. var normals = [];
  34500. var uvs = [];
  34501. var row, col;
  34502. // Vertices
  34503. for (row = 0; row <= options.subdivisions; row++) {
  34504. for (col = 0; col <= options.subdivisions; col++) {
  34505. 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));
  34506. // Compute height
  34507. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  34508. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  34509. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  34510. var r = options.buffer[pos] / 255.0;
  34511. var g = options.buffer[pos + 1] / 255.0;
  34512. var b = options.buffer[pos + 2] / 255.0;
  34513. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  34514. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  34515. // Add vertex
  34516. positions.push(position.x, position.y, position.z);
  34517. normals.push(0, 0, 0);
  34518. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  34519. }
  34520. }
  34521. // Indices
  34522. for (row = 0; row < options.subdivisions; row++) {
  34523. for (col = 0; col < options.subdivisions; col++) {
  34524. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34525. indices.push(col + 1 + row * (options.subdivisions + 1));
  34526. indices.push(col + row * (options.subdivisions + 1));
  34527. indices.push(col + (row + 1) * (options.subdivisions + 1));
  34528. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  34529. indices.push(col + row * (options.subdivisions + 1));
  34530. }
  34531. }
  34532. // Normals
  34533. VertexData.ComputeNormals(positions, indices, normals);
  34534. // Result
  34535. var vertexData = new VertexData();
  34536. vertexData.indices = indices;
  34537. vertexData.positions = positions;
  34538. vertexData.normals = normals;
  34539. vertexData.uvs = uvs;
  34540. return vertexData;
  34541. };
  34542. VertexData.CreatePlane = function (options) {
  34543. var indices = [];
  34544. var positions = [];
  34545. var normals = [];
  34546. var uvs = [];
  34547. var width = options.width || options.size || 1;
  34548. var height = options.height || options.size || 1;
  34549. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34550. // Vertices
  34551. var halfWidth = width / 2.0;
  34552. var halfHeight = height / 2.0;
  34553. positions.push(-halfWidth, -halfHeight, 0);
  34554. normals.push(0, 0, -1.0);
  34555. uvs.push(0.0, 0.0);
  34556. positions.push(halfWidth, -halfHeight, 0);
  34557. normals.push(0, 0, -1.0);
  34558. uvs.push(1.0, 0.0);
  34559. positions.push(halfWidth, halfHeight, 0);
  34560. normals.push(0, 0, -1.0);
  34561. uvs.push(1.0, 1.0);
  34562. positions.push(-halfWidth, halfHeight, 0);
  34563. normals.push(0, 0, -1.0);
  34564. uvs.push(0.0, 1.0);
  34565. // Indices
  34566. indices.push(0);
  34567. indices.push(1);
  34568. indices.push(2);
  34569. indices.push(0);
  34570. indices.push(2);
  34571. indices.push(3);
  34572. // Sides
  34573. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34574. // Result
  34575. var vertexData = new VertexData();
  34576. vertexData.indices = indices;
  34577. vertexData.positions = positions;
  34578. vertexData.normals = normals;
  34579. vertexData.uvs = uvs;
  34580. return vertexData;
  34581. };
  34582. VertexData.CreateDisc = function (options) {
  34583. var positions = [];
  34584. var indices = [];
  34585. var normals = [];
  34586. var uvs = [];
  34587. var radius = options.radius || 0.5;
  34588. var tessellation = options.tessellation || 64;
  34589. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  34590. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34591. // positions and uvs
  34592. positions.push(0, 0, 0); // disc center first
  34593. uvs.push(0.5, 0.5);
  34594. var theta = Math.PI * 2 * arc;
  34595. var step = theta / tessellation;
  34596. for (var a = 0; a < theta; a += step) {
  34597. var x = Math.cos(a);
  34598. var y = Math.sin(a);
  34599. var u = (x + 1) / 2;
  34600. var v = (1 - y) / 2;
  34601. positions.push(radius * x, radius * y, 0);
  34602. uvs.push(u, v);
  34603. }
  34604. if (arc === 1) {
  34605. positions.push(positions[3], positions[4], positions[5]); // close the circle
  34606. uvs.push(uvs[2], uvs[3]);
  34607. }
  34608. //indices
  34609. var vertexNb = positions.length / 3;
  34610. for (var i = 1; i < vertexNb - 1; i++) {
  34611. indices.push(i + 1, 0, i);
  34612. }
  34613. // result
  34614. VertexData.ComputeNormals(positions, indices, normals);
  34615. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34616. var vertexData = new VertexData();
  34617. vertexData.indices = indices;
  34618. vertexData.positions = positions;
  34619. vertexData.normals = normals;
  34620. vertexData.uvs = uvs;
  34621. return vertexData;
  34622. };
  34623. VertexData.CreateIcoSphere = function (options) {
  34624. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34625. var radius = options.radius || 1;
  34626. var flat = (options.flat === undefined) ? true : options.flat;
  34627. var subdivisions = options.subdivisions || 4;
  34628. var radiusX = options.radiusX || radius;
  34629. var radiusY = options.radiusY || radius;
  34630. var radiusZ = options.radiusZ || radius;
  34631. var t = (1 + Math.sqrt(5)) / 2;
  34632. // 12 vertex x,y,z
  34633. var ico_vertices = [
  34634. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  34635. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  34636. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  34637. ];
  34638. // index of 3 vertex makes a face of icopshere
  34639. var ico_indices = [
  34640. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  34641. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  34642. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  34643. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  34644. ];
  34645. // vertex for uv have aliased position, not for UV
  34646. var vertices_unalias_id = [
  34647. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  34648. // vertex alias
  34649. 0,
  34650. 2,
  34651. 3,
  34652. 3,
  34653. 3,
  34654. 4,
  34655. 7,
  34656. 8,
  34657. 9,
  34658. 9,
  34659. 10,
  34660. 11 // 23: B + 12
  34661. ];
  34662. // uv as integer step (not pixels !)
  34663. var ico_vertexuv = [
  34664. 5, 1, 3, 1, 6, 4, 0, 0,
  34665. 5, 3, 4, 2, 2, 2, 4, 0,
  34666. 2, 0, 1, 1, 6, 0, 6, 2,
  34667. // vertex alias (for same vertex on different faces)
  34668. 0, 4,
  34669. 3, 3,
  34670. 4, 4,
  34671. 3, 1,
  34672. 4, 2,
  34673. 4, 4,
  34674. 0, 2,
  34675. 1, 1,
  34676. 2, 2,
  34677. 3, 3,
  34678. 1, 3,
  34679. 2, 4 // 23: B + 12
  34680. ];
  34681. // Vertices[0, 1, ...9, A, B] : position on UV plane
  34682. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  34683. // First island of uv mapping
  34684. // v = 4h 3+ 2
  34685. // v = 3h 9+ 4
  34686. // v = 2h 9+ 5 B
  34687. // v = 1h 9 1 0
  34688. // v = 0h 3 8 7 A
  34689. // u = 0 1 2 3 4 5 6 *a
  34690. // Second island of uv mapping
  34691. // v = 4h 0+ B+ 4+
  34692. // v = 3h A+ 2+
  34693. // v = 2h 7+ 6 3+
  34694. // v = 1h 8+ 3+
  34695. // v = 0h
  34696. // u = 0 1 2 3 4 5 6 *a
  34697. // Face layout on texture UV mapping
  34698. // ============
  34699. // \ 4 /\ 16 / ======
  34700. // \ / \ / /\ 11 /
  34701. // \/ 7 \/ / \ /
  34702. // ======= / 10 \/
  34703. // /\ 17 /\ =======
  34704. // / \ / \ \ 15 /\
  34705. // / 8 \/ 12 \ \ / \
  34706. // ============ \/ 6 \
  34707. // \ 18 /\ ============
  34708. // \ / \ \ 5 /\ 0 /
  34709. // \/ 13 \ \ / \ /
  34710. // ======= \/ 1 \/
  34711. // =============
  34712. // /\ 19 /\ 2 /\
  34713. // / \ / \ / \
  34714. // / 14 \/ 9 \/ 3 \
  34715. // ===================
  34716. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  34717. var ustep = 138 / 1024;
  34718. var vstep = 239 / 1024;
  34719. var uoffset = 60 / 1024;
  34720. var voffset = 26 / 1024;
  34721. // Second island should have margin, not to touch the first island
  34722. // avoid any borderline artefact in pixel rounding
  34723. var island_u_offset = -40 / 1024;
  34724. var island_v_offset = +20 / 1024;
  34725. // face is either island 0 or 1 :
  34726. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  34727. var island = [
  34728. 0, 0, 0, 0, 1,
  34729. 0, 0, 1, 1, 0,
  34730. 0, 0, 1, 1, 0,
  34731. 0, 1, 1, 1, 0 // 15 - 19
  34732. ];
  34733. var indices = [];
  34734. var positions = [];
  34735. var normals = [];
  34736. var uvs = [];
  34737. var current_indice = 0;
  34738. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  34739. var face_vertex_pos = new Array(3);
  34740. var face_vertex_uv = new Array(3);
  34741. var v012;
  34742. for (v012 = 0; v012 < 3; v012++) {
  34743. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  34744. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  34745. }
  34746. // create all with normals
  34747. for (var face = 0; face < 20; face++) {
  34748. // 3 vertex per face
  34749. for (v012 = 0; v012 < 3; v012++) {
  34750. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  34751. var v_id = ico_indices[3 * face + v012];
  34752. // vertex have 3D position (x,y,z)
  34753. 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]);
  34754. // Normalize to get normal, then scale to radius
  34755. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  34756. // uv Coordinates from vertex ID
  34757. 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);
  34758. }
  34759. // Subdivide the face (interpolate pos, norm, uv)
  34760. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  34761. // - norm is linear interpolation of vertex corner normal
  34762. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  34763. // - uv is linear interpolation
  34764. //
  34765. // Topology is as below for sub-divide by 2
  34766. // vertex shown as v0,v1,v2
  34767. // interp index is i1 to progress in range [v0,v1[
  34768. // interp index is i2 to progress in range [v0,v2[
  34769. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  34770. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34771. //
  34772. //
  34773. // i2 v2
  34774. // ^ ^
  34775. // / / \
  34776. // / / \
  34777. // / / \
  34778. // / / (0,1) \
  34779. // / #---------\
  34780. // / / \ (0,0)'/ \
  34781. // / / \ / \
  34782. // / / \ / \
  34783. // / / (0,0) \ / (1,0) \
  34784. // / #---------#---------\
  34785. // v0 v1
  34786. //
  34787. // --------------------> i1
  34788. //
  34789. // interp of (i1,i2):
  34790. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  34791. // along i1 : lerp(x0,x1, i1/(S-i2))
  34792. //
  34793. // centroid of triangle is needed to get help normal computation
  34794. // (c1,c2) are used for centroid location
  34795. var interp_vertex = function (i1, i2, c1, c2) {
  34796. // vertex is interpolated from
  34797. // - face_vertex_pos[0..2]
  34798. // - face_vertex_uv[0..2]
  34799. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  34800. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  34801. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  34802. pos_interp.normalize();
  34803. var vertex_normal;
  34804. if (flat) {
  34805. // in flat mode, recalculate normal as face centroid normal
  34806. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  34807. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  34808. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  34809. }
  34810. else {
  34811. // in smooth mode, recalculate normal from each single vertex position
  34812. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  34813. }
  34814. // Vertex normal need correction due to X,Y,Z radius scaling
  34815. vertex_normal.x /= radiusX;
  34816. vertex_normal.y /= radiusY;
  34817. vertex_normal.z /= radiusZ;
  34818. vertex_normal.normalize();
  34819. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  34820. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  34821. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  34822. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  34823. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  34824. uvs.push(uv_interp.x, uv_interp.y);
  34825. // push each vertex has member of a face
  34826. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  34827. indices.push(current_indice);
  34828. current_indice++;
  34829. };
  34830. for (var i2 = 0; i2 < subdivisions; i2++) {
  34831. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  34832. // face : (i1,i2) for /\ :
  34833. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  34834. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34835. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34836. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  34837. if (i1 + i2 + 1 < subdivisions) {
  34838. // face : (i1,i2)' for \/ :
  34839. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  34840. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34841. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34842. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  34843. }
  34844. }
  34845. }
  34846. }
  34847. // Sides
  34848. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34849. // Result
  34850. var vertexData = new VertexData();
  34851. vertexData.indices = indices;
  34852. vertexData.positions = positions;
  34853. vertexData.normals = normals;
  34854. vertexData.uvs = uvs;
  34855. return vertexData;
  34856. };
  34857. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  34858. VertexData.CreatePolyhedron = function (options) {
  34859. // provided polyhedron types :
  34860. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  34861. // 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)
  34862. var polyhedra = [];
  34863. 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]] };
  34864. 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]] };
  34865. polyhedra[2] = {
  34866. 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]],
  34867. 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]]
  34868. };
  34869. polyhedra[3] = {
  34870. 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]],
  34871. 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]]
  34872. };
  34873. polyhedra[4] = {
  34874. 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]],
  34875. 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]]
  34876. };
  34877. 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]] };
  34878. 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]] };
  34879. 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]] };
  34880. 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]] };
  34881. 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]] };
  34882. 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]] };
  34883. 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]] };
  34884. 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]] };
  34885. 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]] };
  34886. polyhedra[14] = {
  34887. 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]],
  34888. 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]]
  34889. };
  34890. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  34891. var size = options.size;
  34892. var sizeX = options.sizeX || size || 1;
  34893. var sizeY = options.sizeY || size || 1;
  34894. var sizeZ = options.sizeZ || size || 1;
  34895. var data = options.custom || polyhedra[type];
  34896. var nbfaces = data.face.length;
  34897. var faceUV = options.faceUV || new Array(nbfaces);
  34898. var faceColors = options.faceColors;
  34899. var flat = (options.flat === undefined) ? true : options.flat;
  34900. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34901. var positions = [];
  34902. var indices = [];
  34903. var normals = [];
  34904. var uvs = [];
  34905. var colors = [];
  34906. var index = 0;
  34907. var faceIdx = 0; // face cursor in the array "indexes"
  34908. var indexes = [];
  34909. var i = 0;
  34910. var f = 0;
  34911. var u, v, ang, x, y, tmp;
  34912. // default face colors and UV if undefined
  34913. if (flat) {
  34914. for (f = 0; f < nbfaces; f++) {
  34915. if (faceColors && faceColors[f] === undefined) {
  34916. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  34917. }
  34918. if (faceUV && faceUV[f] === undefined) {
  34919. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  34920. }
  34921. }
  34922. }
  34923. if (!flat) {
  34924. for (i = 0; i < data.vertex.length; i++) {
  34925. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  34926. uvs.push(0, 0);
  34927. }
  34928. for (f = 0; f < nbfaces; f++) {
  34929. for (i = 0; i < data.face[f].length - 2; i++) {
  34930. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  34931. }
  34932. }
  34933. }
  34934. else {
  34935. for (f = 0; f < nbfaces; f++) {
  34936. var fl = data.face[f].length; // number of vertices of the current face
  34937. ang = 2 * Math.PI / fl;
  34938. x = 0.5 * Math.tan(ang / 2);
  34939. y = 0.5;
  34940. // positions, uvs, colors
  34941. for (i = 0; i < fl; i++) {
  34942. // positions
  34943. 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);
  34944. indexes.push(index);
  34945. index++;
  34946. // uvs
  34947. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  34948. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  34949. uvs.push(u, v);
  34950. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  34951. y = x * Math.sin(ang) + y * Math.cos(ang);
  34952. x = tmp;
  34953. // colors
  34954. if (faceColors) {
  34955. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  34956. }
  34957. }
  34958. // indices from indexes
  34959. for (i = 0; i < fl - 2; i++) {
  34960. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  34961. }
  34962. faceIdx += fl;
  34963. }
  34964. }
  34965. VertexData.ComputeNormals(positions, indices, normals);
  34966. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34967. var vertexData = new VertexData();
  34968. vertexData.positions = positions;
  34969. vertexData.indices = indices;
  34970. vertexData.normals = normals;
  34971. vertexData.uvs = uvs;
  34972. if (faceColors && flat) {
  34973. vertexData.colors = colors;
  34974. }
  34975. return vertexData;
  34976. };
  34977. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34978. VertexData.CreateTorusKnot = function (options) {
  34979. var indices = [];
  34980. var positions = [];
  34981. var normals = [];
  34982. var uvs = [];
  34983. var radius = options.radius || 2;
  34984. var tube = options.tube || 0.5;
  34985. var radialSegments = options.radialSegments || 32;
  34986. var tubularSegments = options.tubularSegments || 32;
  34987. var p = options.p || 2;
  34988. var q = options.q || 3;
  34989. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34990. // Helper
  34991. var getPos = function (angle) {
  34992. var cu = Math.cos(angle);
  34993. var su = Math.sin(angle);
  34994. var quOverP = q / p * angle;
  34995. var cs = Math.cos(quOverP);
  34996. var tx = radius * (2 + cs) * 0.5 * cu;
  34997. var ty = radius * (2 + cs) * su * 0.5;
  34998. var tz = radius * Math.sin(quOverP) * 0.5;
  34999. return new BABYLON.Vector3(tx, ty, tz);
  35000. };
  35001. // Vertices
  35002. var i;
  35003. var j;
  35004. for (i = 0; i <= radialSegments; i++) {
  35005. var modI = i % radialSegments;
  35006. var u = modI / radialSegments * 2 * p * Math.PI;
  35007. var p1 = getPos(u);
  35008. var p2 = getPos(u + 0.01);
  35009. var tang = p2.subtract(p1);
  35010. var n = p2.add(p1);
  35011. var bitan = BABYLON.Vector3.Cross(tang, n);
  35012. n = BABYLON.Vector3.Cross(bitan, tang);
  35013. bitan.normalize();
  35014. n.normalize();
  35015. for (j = 0; j < tubularSegments; j++) {
  35016. var modJ = j % tubularSegments;
  35017. var v = modJ / tubularSegments * 2 * Math.PI;
  35018. var cx = -tube * Math.cos(v);
  35019. var cy = tube * Math.sin(v);
  35020. positions.push(p1.x + cx * n.x + cy * bitan.x);
  35021. positions.push(p1.y + cx * n.y + cy * bitan.y);
  35022. positions.push(p1.z + cx * n.z + cy * bitan.z);
  35023. uvs.push(i / radialSegments);
  35024. uvs.push(j / tubularSegments);
  35025. }
  35026. }
  35027. for (i = 0; i < radialSegments; i++) {
  35028. for (j = 0; j < tubularSegments; j++) {
  35029. var jNext = (j + 1) % tubularSegments;
  35030. var a = i * tubularSegments + j;
  35031. var b = (i + 1) * tubularSegments + j;
  35032. var c = (i + 1) * tubularSegments + jNext;
  35033. var d = i * tubularSegments + jNext;
  35034. indices.push(d);
  35035. indices.push(b);
  35036. indices.push(a);
  35037. indices.push(d);
  35038. indices.push(c);
  35039. indices.push(b);
  35040. }
  35041. }
  35042. // Normals
  35043. VertexData.ComputeNormals(positions, indices, normals);
  35044. // Sides
  35045. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  35046. // Result
  35047. var vertexData = new VertexData();
  35048. vertexData.indices = indices;
  35049. vertexData.positions = positions;
  35050. vertexData.normals = normals;
  35051. vertexData.uvs = uvs;
  35052. return vertexData;
  35053. };
  35054. // Tools
  35055. /**
  35056. * @param {any} - positions (number[] or Float32Array)
  35057. * @param {any} - indices (number[] or Uint16Array)
  35058. * @param {any} - normals (number[] or Float32Array)
  35059. * options (optional) :
  35060. * facetPositions : optional array of facet positions (vector3)
  35061. * facetNormals : optional array of facet normals (vector3)
  35062. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  35063. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  35064. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  35065. * bbSize : optional bounding box size data, required for facetPartitioning computation
  35066. * bInfo : optional bounding info, required for facetPartitioning computation
  35067. */
  35068. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  35069. // temporary scalar variables
  35070. var index = 0; // facet index
  35071. var p1p2x = 0.0; // p1p2 vector x coordinate
  35072. var p1p2y = 0.0; // p1p2 vector y coordinate
  35073. var p1p2z = 0.0; // p1p2 vector z coordinate
  35074. var p3p2x = 0.0; // p3p2 vector x coordinate
  35075. var p3p2y = 0.0; // p3p2 vector y coordinate
  35076. var p3p2z = 0.0; // p3p2 vector z coordinate
  35077. var faceNormalx = 0.0; // facet normal x coordinate
  35078. var faceNormaly = 0.0; // facet normal y coordinate
  35079. var faceNormalz = 0.0; // facet normal z coordinate
  35080. var length = 0.0; // facet normal length before normalization
  35081. var v1x = 0; // vector1 x index in the positions array
  35082. var v1y = 0; // vector1 y index in the positions array
  35083. var v1z = 0; // vector1 z index in the positions array
  35084. var v2x = 0; // vector2 x index in the positions array
  35085. var v2y = 0; // vector2 y index in the positions array
  35086. var v2z = 0; // vector2 z index in the positions array
  35087. var v3x = 0; // vector3 x index in the positions array
  35088. var v3y = 0; // vector3 y index in the positions array
  35089. var v3z = 0; // vector3 z index in the positions array
  35090. var computeFacetNormals = false;
  35091. var computeFacetPositions = false;
  35092. var computeFacetPartitioning = false;
  35093. if (options) {
  35094. computeFacetNormals = (options.facetNormals) ? true : false;
  35095. computeFacetPositions = (options.facetPositions) ? true : false;
  35096. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  35097. }
  35098. // facetPartitioning reinit if needed
  35099. if (computeFacetPartitioning) {
  35100. var ox = 0; // X partitioning index for facet position
  35101. var oy = 0; // Y partinioning index for facet position
  35102. var oz = 0; // Z partinioning index for facet position
  35103. var b1x = 0; // X partitioning index for facet v1 vertex
  35104. var b1y = 0; // Y partitioning index for facet v1 vertex
  35105. var b1z = 0; // z partitioning index for facet v1 vertex
  35106. var b2x = 0; // X partitioning index for facet v2 vertex
  35107. var b2y = 0; // Y partitioning index for facet v2 vertex
  35108. var b2z = 0; // Z partitioning index for facet v2 vertex
  35109. var b3x = 0; // X partitioning index for facet v3 vertex
  35110. var b3y = 0; // Y partitioning index for facet v3 vertex
  35111. var b3z = 0; // Z partitioning index for facet v3 vertex
  35112. var block_idx_o = 0; // facet barycenter block index
  35113. var block_idx_v1 = 0; // v1 vertex block index
  35114. var block_idx_v2 = 0; // v2 vertex block index
  35115. var block_idx_v3 = 0; // v3 vertex block index
  35116. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  35117. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  35118. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  35119. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  35120. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  35121. var subSq = options.subDiv.max * options.subDiv.max;
  35122. options.facetPartitioning.length = 0;
  35123. }
  35124. // reset the normals
  35125. for (index = 0; index < positions.length; index++) {
  35126. normals[index] = 0.0;
  35127. }
  35128. // Loop : 1 indice triplet = 1 facet
  35129. var nbFaces = indices.length / 3;
  35130. for (index = 0; index < nbFaces; index++) {
  35131. // get the indexes of the coordinates of each vertex of the facet
  35132. v1x = indices[index * 3] * 3;
  35133. v1y = v1x + 1;
  35134. v1z = v1x + 2;
  35135. v2x = indices[index * 3 + 1] * 3;
  35136. v2y = v2x + 1;
  35137. v2z = v2x + 2;
  35138. v3x = indices[index * 3 + 2] * 3;
  35139. v3y = v3x + 1;
  35140. v3z = v3x + 2;
  35141. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  35142. p1p2y = positions[v1y] - positions[v2y];
  35143. p1p2z = positions[v1z] - positions[v2z];
  35144. p3p2x = positions[v3x] - positions[v2x];
  35145. p3p2y = positions[v3y] - positions[v2y];
  35146. p3p2z = positions[v3z] - positions[v2z];
  35147. // compute the face normal with the cross product
  35148. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y;
  35149. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  35150. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  35151. // normalize this normal and store it in the array facetData
  35152. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35153. length = (length === 0) ? 1.0 : length;
  35154. faceNormalx /= length;
  35155. faceNormaly /= length;
  35156. faceNormalz /= length;
  35157. if (computeFacetNormals) {
  35158. options.facetNormals[index].x = faceNormalx;
  35159. options.facetNormals[index].y = faceNormaly;
  35160. options.facetNormals[index].z = faceNormalz;
  35161. }
  35162. if (computeFacetPositions) {
  35163. // compute and the facet barycenter coordinates in the array facetPositions
  35164. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  35165. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  35166. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  35167. }
  35168. if (computeFacetPartitioning) {
  35169. // store the facet indexes in arrays in the main facetPartitioning array :
  35170. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  35171. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  35172. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  35173. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  35174. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  35175. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  35176. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  35177. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  35178. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  35179. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  35180. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  35181. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  35182. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  35183. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  35184. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  35185. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  35186. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  35187. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  35188. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  35189. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  35190. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  35191. // push each facet index in each block containing the vertex
  35192. options.facetPartitioning[block_idx_v1].push(index);
  35193. if (block_idx_v2 != block_idx_v1) {
  35194. options.facetPartitioning[block_idx_v2].push(index);
  35195. }
  35196. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  35197. options.facetPartitioning[block_idx_v3].push(index);
  35198. }
  35199. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  35200. options.facetPartitioning[block_idx_o].push(index);
  35201. }
  35202. }
  35203. // compute the normals anyway
  35204. normals[v1x] += faceNormalx; // accumulate all the normals per face
  35205. normals[v1y] += faceNormaly;
  35206. normals[v1z] += faceNormalz;
  35207. normals[v2x] += faceNormalx;
  35208. normals[v2y] += faceNormaly;
  35209. normals[v2z] += faceNormalz;
  35210. normals[v3x] += faceNormalx;
  35211. normals[v3y] += faceNormaly;
  35212. normals[v3z] += faceNormalz;
  35213. }
  35214. // last normalization of each normal
  35215. for (index = 0; index < normals.length / 3; index++) {
  35216. faceNormalx = normals[index * 3];
  35217. faceNormaly = normals[index * 3 + 1];
  35218. faceNormalz = normals[index * 3 + 2];
  35219. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  35220. length = (length === 0) ? 1.0 : length;
  35221. faceNormalx /= length;
  35222. faceNormaly /= length;
  35223. faceNormalz /= length;
  35224. normals[index * 3] = faceNormalx;
  35225. normals[index * 3 + 1] = faceNormaly;
  35226. normals[index * 3 + 2] = faceNormalz;
  35227. }
  35228. };
  35229. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  35230. var li = indices.length;
  35231. var ln = normals.length;
  35232. var i;
  35233. var n;
  35234. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  35235. switch (sideOrientation) {
  35236. case BABYLON.Mesh.FRONTSIDE:
  35237. // nothing changed
  35238. break;
  35239. case BABYLON.Mesh.BACKSIDE:
  35240. var tmp;
  35241. // indices
  35242. for (i = 0; i < li; i += 3) {
  35243. tmp = indices[i];
  35244. indices[i] = indices[i + 2];
  35245. indices[i + 2] = tmp;
  35246. }
  35247. // normals
  35248. for (n = 0; n < ln; n++) {
  35249. normals[n] = -normals[n];
  35250. }
  35251. break;
  35252. case BABYLON.Mesh.DOUBLESIDE:
  35253. // positions
  35254. var lp = positions.length;
  35255. var l = lp / 3;
  35256. for (var p = 0; p < lp; p++) {
  35257. positions[lp + p] = positions[p];
  35258. }
  35259. // indices
  35260. for (i = 0; i < li; i += 3) {
  35261. indices[i + li] = indices[i + 2] + l;
  35262. indices[i + 1 + li] = indices[i + 1] + l;
  35263. indices[i + 2 + li] = indices[i] + l;
  35264. }
  35265. // normals
  35266. for (n = 0; n < ln; n++) {
  35267. normals[ln + n] = -normals[n];
  35268. }
  35269. // uvs
  35270. var lu = uvs.length;
  35271. for (var u = 0; u < lu; u++) {
  35272. uvs[u + lu] = uvs[u];
  35273. }
  35274. break;
  35275. }
  35276. };
  35277. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  35278. var vertexData = new VertexData();
  35279. // positions
  35280. var positions = parsedVertexData.positions;
  35281. if (positions) {
  35282. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  35283. }
  35284. // normals
  35285. var normals = parsedVertexData.normals;
  35286. if (normals) {
  35287. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  35288. }
  35289. // uvs
  35290. var uvs = parsedVertexData.uvs;
  35291. if (uvs) {
  35292. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  35293. }
  35294. // uv2s
  35295. var uv2s = parsedVertexData.uv2s;
  35296. if (uv2s) {
  35297. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  35298. }
  35299. // uv3s
  35300. var uv3s = parsedVertexData.uv3s;
  35301. if (uv3s) {
  35302. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  35303. }
  35304. // uv4s
  35305. var uv4s = parsedVertexData.uv4s;
  35306. if (uv4s) {
  35307. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  35308. }
  35309. // uv5s
  35310. var uv5s = parsedVertexData.uv5s;
  35311. if (uv5s) {
  35312. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  35313. }
  35314. // uv6s
  35315. var uv6s = parsedVertexData.uv6s;
  35316. if (uv6s) {
  35317. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  35318. }
  35319. // colors
  35320. var colors = parsedVertexData.colors;
  35321. if (colors) {
  35322. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  35323. }
  35324. // matricesIndices
  35325. var matricesIndices = parsedVertexData.matricesIndices;
  35326. if (matricesIndices) {
  35327. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  35328. }
  35329. // matricesWeights
  35330. var matricesWeights = parsedVertexData.matricesWeights;
  35331. if (matricesWeights) {
  35332. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  35333. }
  35334. // indices
  35335. var indices = parsedVertexData.indices;
  35336. if (indices) {
  35337. vertexData.indices = indices;
  35338. }
  35339. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  35340. };
  35341. return VertexData;
  35342. }());
  35343. BABYLON.VertexData = VertexData;
  35344. })(BABYLON || (BABYLON = {}));
  35345. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  35346. var BABYLON;
  35347. (function (BABYLON) {
  35348. var Tags = (function () {
  35349. function Tags() {
  35350. }
  35351. Tags.EnableFor = function (obj) {
  35352. obj._tags = obj._tags || {};
  35353. obj.hasTags = function () {
  35354. return Tags.HasTags(obj);
  35355. };
  35356. obj.addTags = function (tagsString) {
  35357. return Tags.AddTagsTo(obj, tagsString);
  35358. };
  35359. obj.removeTags = function (tagsString) {
  35360. return Tags.RemoveTagsFrom(obj, tagsString);
  35361. };
  35362. obj.matchesTagsQuery = function (tagsQuery) {
  35363. return Tags.MatchesQuery(obj, tagsQuery);
  35364. };
  35365. };
  35366. Tags.DisableFor = function (obj) {
  35367. delete obj._tags;
  35368. delete obj.hasTags;
  35369. delete obj.addTags;
  35370. delete obj.removeTags;
  35371. delete obj.matchesTagsQuery;
  35372. };
  35373. Tags.HasTags = function (obj) {
  35374. if (!obj._tags) {
  35375. return false;
  35376. }
  35377. return !BABYLON.Tools.IsEmpty(obj._tags);
  35378. };
  35379. Tags.GetTags = function (obj, asString) {
  35380. if (asString === void 0) { asString = true; }
  35381. if (!obj._tags) {
  35382. return null;
  35383. }
  35384. if (asString) {
  35385. var tagsArray = [];
  35386. for (var tag in obj._tags) {
  35387. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  35388. tagsArray.push(tag);
  35389. }
  35390. }
  35391. return tagsArray.join(" ");
  35392. }
  35393. else {
  35394. return obj._tags;
  35395. }
  35396. };
  35397. // the tags 'true' and 'false' are reserved and cannot be used as tags
  35398. // a tag cannot start with '||', '&&', and '!'
  35399. // it cannot contain whitespaces
  35400. Tags.AddTagsTo = function (obj, tagsString) {
  35401. if (!tagsString) {
  35402. return;
  35403. }
  35404. if (typeof tagsString !== "string") {
  35405. return;
  35406. }
  35407. var tags = tagsString.split(" ");
  35408. tags.forEach(function (tag, index, array) {
  35409. Tags._AddTagTo(obj, tag);
  35410. });
  35411. };
  35412. Tags._AddTagTo = function (obj, tag) {
  35413. tag = tag.trim();
  35414. if (tag === "" || tag === "true" || tag === "false") {
  35415. return;
  35416. }
  35417. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  35418. return;
  35419. }
  35420. Tags.EnableFor(obj);
  35421. obj._tags[tag] = true;
  35422. };
  35423. Tags.RemoveTagsFrom = function (obj, tagsString) {
  35424. if (!Tags.HasTags(obj)) {
  35425. return;
  35426. }
  35427. var tags = tagsString.split(" ");
  35428. for (var t in tags) {
  35429. Tags._RemoveTagFrom(obj, tags[t]);
  35430. }
  35431. };
  35432. Tags._RemoveTagFrom = function (obj, tag) {
  35433. delete obj._tags[tag];
  35434. };
  35435. Tags.MatchesQuery = function (obj, tagsQuery) {
  35436. if (tagsQuery === undefined) {
  35437. return true;
  35438. }
  35439. if (tagsQuery === "") {
  35440. return Tags.HasTags(obj);
  35441. }
  35442. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  35443. };
  35444. return Tags;
  35445. }());
  35446. BABYLON.Tags = Tags;
  35447. })(BABYLON || (BABYLON = {}));
  35448. //# sourceMappingURL=babylon.tags.js.map
  35449. var BABYLON;
  35450. (function (BABYLON) {
  35451. var Internals;
  35452. (function (Internals) {
  35453. var AndOrNotEvaluator = (function () {
  35454. function AndOrNotEvaluator() {
  35455. }
  35456. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  35457. if (!query.match(/\([^\(\)]*\)/g)) {
  35458. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  35459. }
  35460. else {
  35461. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  35462. // remove parenthesis
  35463. r = r.slice(1, r.length - 1);
  35464. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  35465. });
  35466. }
  35467. if (query === "true") {
  35468. return true;
  35469. }
  35470. if (query === "false") {
  35471. return false;
  35472. }
  35473. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  35474. };
  35475. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  35476. evaluateCallback = evaluateCallback || (function (r) {
  35477. return r === "true" ? true : false;
  35478. });
  35479. var result;
  35480. var or = parenthesisContent.split("||");
  35481. for (var i in or) {
  35482. if (or.hasOwnProperty(i)) {
  35483. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  35484. var and = ori.split("&&");
  35485. if (and.length > 1) {
  35486. for (var j = 0; j < and.length; ++j) {
  35487. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  35488. if (andj !== "true" && andj !== "false") {
  35489. if (andj[0] === "!") {
  35490. result = !evaluateCallback(andj.substring(1));
  35491. }
  35492. else {
  35493. result = evaluateCallback(andj);
  35494. }
  35495. }
  35496. else {
  35497. result = andj === "true" ? true : false;
  35498. }
  35499. if (!result) {
  35500. ori = "false";
  35501. break;
  35502. }
  35503. }
  35504. }
  35505. if (result || ori === "true") {
  35506. result = true;
  35507. break;
  35508. }
  35509. // result equals false (or undefined)
  35510. if (ori !== "true" && ori !== "false") {
  35511. if (ori[0] === "!") {
  35512. result = !evaluateCallback(ori.substring(1));
  35513. }
  35514. else {
  35515. result = evaluateCallback(ori);
  35516. }
  35517. }
  35518. else {
  35519. result = ori === "true" ? true : false;
  35520. }
  35521. }
  35522. }
  35523. // the whole parenthesis scope is replaced by 'true' or 'false'
  35524. return result ? "true" : "false";
  35525. };
  35526. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  35527. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  35528. // remove whitespaces
  35529. r = r.replace(/[\s]/g, function () { return ""; });
  35530. return r.length % 2 ? "!" : "";
  35531. });
  35532. booleanString = booleanString.trim();
  35533. if (booleanString === "!true") {
  35534. booleanString = "false";
  35535. }
  35536. else if (booleanString === "!false") {
  35537. booleanString = "true";
  35538. }
  35539. return booleanString;
  35540. };
  35541. return AndOrNotEvaluator;
  35542. }());
  35543. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  35544. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  35545. })(BABYLON || (BABYLON = {}));
  35546. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  35547. var BABYLON;
  35548. (function (BABYLON) {
  35549. var PostProcessRenderPass = (function () {
  35550. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  35551. this._enabled = true;
  35552. this._refCount = 0;
  35553. this._name = name;
  35554. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  35555. this.setRenderList(renderList);
  35556. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  35557. this._renderTexture.onAfterRenderObservable.add(afterRender);
  35558. this._scene = scene;
  35559. this._renderList = renderList;
  35560. }
  35561. // private
  35562. PostProcessRenderPass.prototype._incRefCount = function () {
  35563. if (this._refCount === 0) {
  35564. this._scene.customRenderTargets.push(this._renderTexture);
  35565. }
  35566. return ++this._refCount;
  35567. };
  35568. PostProcessRenderPass.prototype._decRefCount = function () {
  35569. this._refCount--;
  35570. if (this._refCount <= 0) {
  35571. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  35572. }
  35573. return this._refCount;
  35574. };
  35575. PostProcessRenderPass.prototype._update = function () {
  35576. this.setRenderList(this._renderList);
  35577. };
  35578. // public
  35579. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  35580. this._renderTexture.renderList = renderList;
  35581. };
  35582. PostProcessRenderPass.prototype.getRenderTexture = function () {
  35583. return this._renderTexture;
  35584. };
  35585. return PostProcessRenderPass;
  35586. }());
  35587. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  35588. })(BABYLON || (BABYLON = {}));
  35589. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  35590. var BABYLON;
  35591. (function (BABYLON) {
  35592. var PostProcessRenderEffect = (function () {
  35593. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  35594. this._engine = engine;
  35595. this._name = name;
  35596. this._singleInstance = singleInstance || true;
  35597. this._getPostProcess = getPostProcess;
  35598. this._cameras = [];
  35599. this._indicesForCamera = [];
  35600. this._postProcesses = {};
  35601. this._renderPasses = {};
  35602. this._renderEffectAsPasses = {};
  35603. }
  35604. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  35605. get: function () {
  35606. for (var index in this._postProcesses) {
  35607. if (!this._postProcesses[index].isSupported) {
  35608. return false;
  35609. }
  35610. }
  35611. return true;
  35612. },
  35613. enumerable: true,
  35614. configurable: true
  35615. });
  35616. PostProcessRenderEffect.prototype._update = function () {
  35617. for (var renderPassName in this._renderPasses) {
  35618. this._renderPasses[renderPassName]._update();
  35619. }
  35620. };
  35621. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  35622. this._renderPasses[renderPass._name] = renderPass;
  35623. this._linkParameters();
  35624. };
  35625. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  35626. delete this._renderPasses[renderPass._name];
  35627. this._linkParameters();
  35628. };
  35629. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  35630. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  35631. this._linkParameters();
  35632. };
  35633. PostProcessRenderEffect.prototype.getPass = function (passName) {
  35634. for (var renderPassName in this._renderPasses) {
  35635. if (renderPassName === passName) {
  35636. return this._renderPasses[passName];
  35637. }
  35638. }
  35639. };
  35640. PostProcessRenderEffect.prototype.emptyPasses = function () {
  35641. this._renderPasses = {};
  35642. this._linkParameters();
  35643. };
  35644. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  35645. var cameraKey;
  35646. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35647. for (var i = 0; i < _cam.length; i++) {
  35648. var camera = _cam[i];
  35649. var cameraName = camera.name;
  35650. if (this._singleInstance) {
  35651. cameraKey = 0;
  35652. }
  35653. else {
  35654. cameraKey = cameraName;
  35655. }
  35656. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  35657. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  35658. if (!this._indicesForCamera[cameraName]) {
  35659. this._indicesForCamera[cameraName] = [];
  35660. }
  35661. this._indicesForCamera[cameraName].push(index);
  35662. if (this._cameras.indexOf(camera) === -1) {
  35663. this._cameras[cameraName] = camera;
  35664. }
  35665. for (var passName in this._renderPasses) {
  35666. this._renderPasses[passName]._incRefCount();
  35667. }
  35668. }
  35669. this._linkParameters();
  35670. };
  35671. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  35672. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35673. for (var i = 0; i < _cam.length; i++) {
  35674. var camera = _cam[i];
  35675. var cameraName = camera.name;
  35676. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  35677. var index = this._cameras.indexOf(cameraName);
  35678. this._indicesForCamera.splice(index, 1);
  35679. this._cameras.splice(index, 1);
  35680. for (var passName in this._renderPasses) {
  35681. this._renderPasses[passName]._decRefCount();
  35682. }
  35683. }
  35684. };
  35685. PostProcessRenderEffect.prototype._enable = function (cameras) {
  35686. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35687. for (var i = 0; i < _cam.length; i++) {
  35688. var camera = _cam[i];
  35689. var cameraName = camera.name;
  35690. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  35691. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  35692. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  35693. }
  35694. }
  35695. for (var passName in this._renderPasses) {
  35696. this._renderPasses[passName]._incRefCount();
  35697. }
  35698. }
  35699. };
  35700. PostProcessRenderEffect.prototype._disable = function (cameras) {
  35701. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35702. for (var i = 0; i < _cam.length; i++) {
  35703. var camera = _cam[i];
  35704. var cameraName = camera.Name;
  35705. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  35706. for (var passName in this._renderPasses) {
  35707. this._renderPasses[passName]._decRefCount();
  35708. }
  35709. }
  35710. };
  35711. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  35712. if (this._singleInstance) {
  35713. return this._postProcesses[0];
  35714. }
  35715. else {
  35716. return this._postProcesses[camera.name];
  35717. }
  35718. };
  35719. PostProcessRenderEffect.prototype._linkParameters = function () {
  35720. var _this = this;
  35721. for (var index in this._postProcesses) {
  35722. if (this.applyParameters) {
  35723. this.applyParameters(this._postProcesses[index]);
  35724. }
  35725. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  35726. _this._linkTextures(effect);
  35727. });
  35728. }
  35729. };
  35730. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  35731. for (var renderPassName in this._renderPasses) {
  35732. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  35733. }
  35734. for (var renderEffectName in this._renderEffectAsPasses) {
  35735. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  35736. }
  35737. };
  35738. return PostProcessRenderEffect;
  35739. }());
  35740. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  35741. })(BABYLON || (BABYLON = {}));
  35742. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  35743. var BABYLON;
  35744. (function (BABYLON) {
  35745. var PostProcessRenderPipeline = (function () {
  35746. function PostProcessRenderPipeline(engine, name) {
  35747. this._engine = engine;
  35748. this._name = name;
  35749. this._renderEffects = {};
  35750. this._renderEffectsForIsolatedPass = {};
  35751. this._cameras = [];
  35752. }
  35753. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  35754. get: function () {
  35755. for (var renderEffectName in this._renderEffects) {
  35756. if (!this._renderEffects[renderEffectName].isSupported) {
  35757. return false;
  35758. }
  35759. }
  35760. return true;
  35761. },
  35762. enumerable: true,
  35763. configurable: true
  35764. });
  35765. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  35766. this._renderEffects[renderEffect._name] = renderEffect;
  35767. };
  35768. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  35769. var renderEffects = this._renderEffects[renderEffectName];
  35770. if (!renderEffects) {
  35771. return;
  35772. }
  35773. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  35774. };
  35775. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  35776. var renderEffects = this._renderEffects[renderEffectName];
  35777. if (!renderEffects) {
  35778. return;
  35779. }
  35780. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  35781. };
  35782. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  35783. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35784. var indicesToDelete = [];
  35785. var i;
  35786. for (i = 0; i < _cam.length; i++) {
  35787. var camera = _cam[i];
  35788. var cameraName = camera.name;
  35789. if (this._cameras.indexOf(camera) === -1) {
  35790. this._cameras[cameraName] = camera;
  35791. }
  35792. else if (unique) {
  35793. indicesToDelete.push(i);
  35794. }
  35795. }
  35796. for (i = 0; i < indicesToDelete.length; i++) {
  35797. cameras.splice(indicesToDelete[i], 1);
  35798. }
  35799. for (var renderEffectName in this._renderEffects) {
  35800. this._renderEffects[renderEffectName]._attachCameras(_cam);
  35801. }
  35802. };
  35803. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  35804. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35805. for (var renderEffectName in this._renderEffects) {
  35806. this._renderEffects[renderEffectName]._detachCameras(_cam);
  35807. }
  35808. for (var i = 0; i < _cam.length; i++) {
  35809. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  35810. }
  35811. };
  35812. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  35813. var _this = this;
  35814. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35815. var pass = null;
  35816. var renderEffectName;
  35817. for (renderEffectName in this._renderEffects) {
  35818. pass = this._renderEffects[renderEffectName].getPass(passName);
  35819. if (pass != null) {
  35820. break;
  35821. }
  35822. }
  35823. if (pass === null) {
  35824. return;
  35825. }
  35826. for (renderEffectName in this._renderEffects) {
  35827. this._renderEffects[renderEffectName]._disable(_cam);
  35828. }
  35829. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  35830. for (var i = 0; i < _cam.length; i++) {
  35831. var camera = _cam[i];
  35832. var cameraName = camera.name;
  35833. 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); });
  35834. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  35835. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  35836. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  35837. }
  35838. };
  35839. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  35840. var _this = this;
  35841. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  35842. for (var i = 0; i < _cam.length; i++) {
  35843. var camera = _cam[i];
  35844. var cameraName = camera.name;
  35845. 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); });
  35846. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  35847. }
  35848. for (var renderEffectName in this._renderEffects) {
  35849. this._renderEffects[renderEffectName]._enable(_cam);
  35850. }
  35851. };
  35852. PostProcessRenderPipeline.prototype._update = function () {
  35853. for (var renderEffectName in this._renderEffects) {
  35854. this._renderEffects[renderEffectName]._update();
  35855. }
  35856. for (var i = 0; i < this._cameras.length; i++) {
  35857. var cameraName = this._cameras[i].name;
  35858. if (this._renderEffectsForIsolatedPass[cameraName]) {
  35859. this._renderEffectsForIsolatedPass[cameraName]._update();
  35860. }
  35861. }
  35862. };
  35863. PostProcessRenderPipeline.prototype.dispose = function () {
  35864. // Must be implemented by children
  35865. };
  35866. return PostProcessRenderPipeline;
  35867. }());
  35868. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  35869. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  35870. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  35871. })(BABYLON || (BABYLON = {}));
  35872. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  35873. var BABYLON;
  35874. (function (BABYLON) {
  35875. var PostProcessRenderPipelineManager = (function () {
  35876. function PostProcessRenderPipelineManager() {
  35877. this._renderPipelines = {};
  35878. }
  35879. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  35880. this._renderPipelines[renderPipeline._name] = renderPipeline;
  35881. };
  35882. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  35883. var renderPipeline = this._renderPipelines[renderPipelineName];
  35884. if (!renderPipeline) {
  35885. return;
  35886. }
  35887. renderPipeline._attachCameras(cameras, unique);
  35888. };
  35889. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  35890. var renderPipeline = this._renderPipelines[renderPipelineName];
  35891. if (!renderPipeline) {
  35892. return;
  35893. }
  35894. renderPipeline._detachCameras(cameras);
  35895. };
  35896. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  35897. var renderPipeline = this._renderPipelines[renderPipelineName];
  35898. if (!renderPipeline) {
  35899. return;
  35900. }
  35901. renderPipeline._enableEffect(renderEffectName, cameras);
  35902. };
  35903. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  35904. var renderPipeline = this._renderPipelines[renderPipelineName];
  35905. if (!renderPipeline) {
  35906. return;
  35907. }
  35908. renderPipeline._disableEffect(renderEffectName, cameras);
  35909. };
  35910. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  35911. var renderPipeline = this._renderPipelines[renderPipelineName];
  35912. if (!renderPipeline) {
  35913. return;
  35914. }
  35915. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  35916. };
  35917. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  35918. var renderPipeline = this._renderPipelines[renderPipelineName];
  35919. if (!renderPipeline) {
  35920. return;
  35921. }
  35922. renderPipeline._disableDisplayOnlyPass(cameras);
  35923. };
  35924. PostProcessRenderPipelineManager.prototype.update = function () {
  35925. for (var renderPipelineName in this._renderPipelines) {
  35926. var pipeline = this._renderPipelines[renderPipelineName];
  35927. if (!pipeline.isSupported) {
  35928. pipeline.dispose();
  35929. delete this._renderPipelines[renderPipelineName];
  35930. }
  35931. else {
  35932. pipeline._update();
  35933. }
  35934. }
  35935. };
  35936. return PostProcessRenderPipelineManager;
  35937. }());
  35938. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  35939. })(BABYLON || (BABYLON = {}));
  35940. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  35941. var BABYLON;
  35942. (function (BABYLON) {
  35943. var BoundingBoxRenderer = (function () {
  35944. function BoundingBoxRenderer(scene) {
  35945. this.frontColor = new BABYLON.Color3(1, 1, 1);
  35946. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  35947. this.showBackLines = true;
  35948. this.renderList = new BABYLON.SmartArray(32);
  35949. this._vertexBuffers = {};
  35950. this._scene = scene;
  35951. }
  35952. BoundingBoxRenderer.prototype._prepareRessources = function () {
  35953. if (this._colorShader) {
  35954. return;
  35955. }
  35956. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  35957. attributes: [BABYLON.VertexBuffer.PositionKind],
  35958. uniforms: ["worldViewProjection", "color"]
  35959. });
  35960. var engine = this._scene.getEngine();
  35961. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  35962. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  35963. 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]);
  35964. };
  35965. BoundingBoxRenderer.prototype.reset = function () {
  35966. this.renderList.reset();
  35967. };
  35968. BoundingBoxRenderer.prototype.render = function () {
  35969. if (this.renderList.length === 0) {
  35970. return;
  35971. }
  35972. this._prepareRessources();
  35973. if (!this._colorShader.isReady()) {
  35974. return;
  35975. }
  35976. var engine = this._scene.getEngine();
  35977. engine.setDepthWrite(false);
  35978. this._colorShader._preBind();
  35979. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  35980. var boundingBox = this.renderList.data[boundingBoxIndex];
  35981. var min = boundingBox.minimum;
  35982. var max = boundingBox.maximum;
  35983. var diff = max.subtract(min);
  35984. var median = min.add(diff.scale(0.5));
  35985. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  35986. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  35987. .multiply(boundingBox.getWorldMatrix());
  35988. // VBOs
  35989. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  35990. if (this.showBackLines) {
  35991. // Back
  35992. engine.setDepthFunctionToGreaterOrEqual();
  35993. this._scene.resetCachedMaterial();
  35994. this._colorShader.setColor4("color", this.backColor.toColor4());
  35995. this._colorShader.bind(worldMatrix);
  35996. // Draw order
  35997. engine.draw(false, 0, 24);
  35998. }
  35999. // Front
  36000. engine.setDepthFunctionToLess();
  36001. this._scene.resetCachedMaterial();
  36002. this._colorShader.setColor4("color", this.frontColor.toColor4());
  36003. this._colorShader.bind(worldMatrix);
  36004. // Draw order
  36005. engine.draw(false, 0, 24);
  36006. }
  36007. this._colorShader.unbind();
  36008. engine.setDepthFunctionToLessOrEqual();
  36009. engine.setDepthWrite(true);
  36010. };
  36011. BoundingBoxRenderer.prototype.dispose = function () {
  36012. if (!this._colorShader) {
  36013. return;
  36014. }
  36015. this._colorShader.dispose();
  36016. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  36017. if (buffer) {
  36018. buffer.dispose();
  36019. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  36020. }
  36021. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  36022. };
  36023. return BoundingBoxRenderer;
  36024. }());
  36025. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  36026. })(BABYLON || (BABYLON = {}));
  36027. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  36028. var BABYLON;
  36029. (function (BABYLON) {
  36030. var Condition = (function () {
  36031. function Condition(actionManager) {
  36032. this._actionManager = actionManager;
  36033. }
  36034. Condition.prototype.isValid = function () {
  36035. return true;
  36036. };
  36037. Condition.prototype._getProperty = function (propertyPath) {
  36038. return this._actionManager._getProperty(propertyPath);
  36039. };
  36040. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  36041. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36042. };
  36043. Condition.prototype.serialize = function () {
  36044. };
  36045. Condition.prototype._serialize = function (serializedCondition) {
  36046. return {
  36047. type: 2,
  36048. children: [],
  36049. name: serializedCondition.name,
  36050. properties: serializedCondition.properties
  36051. };
  36052. };
  36053. return Condition;
  36054. }());
  36055. BABYLON.Condition = Condition;
  36056. var ValueCondition = (function (_super) {
  36057. __extends(ValueCondition, _super);
  36058. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  36059. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  36060. var _this = _super.call(this, actionManager) || this;
  36061. _this.propertyPath = propertyPath;
  36062. _this.value = value;
  36063. _this.operator = operator;
  36064. _this._target = target;
  36065. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  36066. _this._property = _this._getProperty(_this.propertyPath);
  36067. return _this;
  36068. }
  36069. Object.defineProperty(ValueCondition, "IsEqual", {
  36070. get: function () {
  36071. return ValueCondition._IsEqual;
  36072. },
  36073. enumerable: true,
  36074. configurable: true
  36075. });
  36076. Object.defineProperty(ValueCondition, "IsDifferent", {
  36077. get: function () {
  36078. return ValueCondition._IsDifferent;
  36079. },
  36080. enumerable: true,
  36081. configurable: true
  36082. });
  36083. Object.defineProperty(ValueCondition, "IsGreater", {
  36084. get: function () {
  36085. return ValueCondition._IsGreater;
  36086. },
  36087. enumerable: true,
  36088. configurable: true
  36089. });
  36090. Object.defineProperty(ValueCondition, "IsLesser", {
  36091. get: function () {
  36092. return ValueCondition._IsLesser;
  36093. },
  36094. enumerable: true,
  36095. configurable: true
  36096. });
  36097. // Methods
  36098. ValueCondition.prototype.isValid = function () {
  36099. switch (this.operator) {
  36100. case ValueCondition.IsGreater:
  36101. return this._effectiveTarget[this._property] > this.value;
  36102. case ValueCondition.IsLesser:
  36103. return this._effectiveTarget[this._property] < this.value;
  36104. case ValueCondition.IsEqual:
  36105. case ValueCondition.IsDifferent:
  36106. var check;
  36107. if (this.value.equals) {
  36108. check = this.value.equals(this._effectiveTarget[this._property]);
  36109. }
  36110. else {
  36111. check = this.value === this._effectiveTarget[this._property];
  36112. }
  36113. return this.operator === ValueCondition.IsEqual ? check : !check;
  36114. }
  36115. return false;
  36116. };
  36117. ValueCondition.prototype.serialize = function () {
  36118. return this._serialize({
  36119. name: "ValueCondition",
  36120. properties: [
  36121. BABYLON.Action._GetTargetProperty(this._target),
  36122. { name: "propertyPath", value: this.propertyPath },
  36123. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36124. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  36125. ]
  36126. });
  36127. };
  36128. ValueCondition.GetOperatorName = function (operator) {
  36129. switch (operator) {
  36130. case ValueCondition._IsEqual: return "IsEqual";
  36131. case ValueCondition._IsDifferent: return "IsDifferent";
  36132. case ValueCondition._IsGreater: return "IsGreater";
  36133. case ValueCondition._IsLesser: return "IsLesser";
  36134. default: return "";
  36135. }
  36136. };
  36137. return ValueCondition;
  36138. }(Condition));
  36139. // Statics
  36140. ValueCondition._IsEqual = 0;
  36141. ValueCondition._IsDifferent = 1;
  36142. ValueCondition._IsGreater = 2;
  36143. ValueCondition._IsLesser = 3;
  36144. BABYLON.ValueCondition = ValueCondition;
  36145. var PredicateCondition = (function (_super) {
  36146. __extends(PredicateCondition, _super);
  36147. function PredicateCondition(actionManager, predicate) {
  36148. var _this = _super.call(this, actionManager) || this;
  36149. _this.predicate = predicate;
  36150. return _this;
  36151. }
  36152. PredicateCondition.prototype.isValid = function () {
  36153. return this.predicate();
  36154. };
  36155. return PredicateCondition;
  36156. }(Condition));
  36157. BABYLON.PredicateCondition = PredicateCondition;
  36158. var StateCondition = (function (_super) {
  36159. __extends(StateCondition, _super);
  36160. function StateCondition(actionManager, target, value) {
  36161. var _this = _super.call(this, actionManager) || this;
  36162. _this.value = value;
  36163. _this._target = target;
  36164. return _this;
  36165. }
  36166. // Methods
  36167. StateCondition.prototype.isValid = function () {
  36168. return this._target.state === this.value;
  36169. };
  36170. StateCondition.prototype.serialize = function () {
  36171. return this._serialize({
  36172. name: "StateCondition",
  36173. properties: [
  36174. BABYLON.Action._GetTargetProperty(this._target),
  36175. { name: "value", value: this.value }
  36176. ]
  36177. });
  36178. };
  36179. return StateCondition;
  36180. }(Condition));
  36181. BABYLON.StateCondition = StateCondition;
  36182. })(BABYLON || (BABYLON = {}));
  36183. //# sourceMappingURL=babylon.condition.js.map
  36184. var BABYLON;
  36185. (function (BABYLON) {
  36186. var Action = (function () {
  36187. function Action(triggerOptions, condition) {
  36188. this.triggerOptions = triggerOptions;
  36189. if (triggerOptions.parameter) {
  36190. this.trigger = triggerOptions.trigger;
  36191. this._triggerParameter = triggerOptions.parameter;
  36192. }
  36193. else {
  36194. this.trigger = triggerOptions;
  36195. }
  36196. this._nextActiveAction = this;
  36197. this._condition = condition;
  36198. }
  36199. // Methods
  36200. Action.prototype._prepare = function () {
  36201. };
  36202. Action.prototype.getTriggerParameter = function () {
  36203. return this._triggerParameter;
  36204. };
  36205. Action.prototype._executeCurrent = function (evt) {
  36206. if (this._nextActiveAction._condition) {
  36207. var condition = this._nextActiveAction._condition;
  36208. var currentRenderId = this._actionManager.getScene().getRenderId();
  36209. // We cache the current evaluation for the current frame
  36210. if (condition._evaluationId === currentRenderId) {
  36211. if (!condition._currentResult) {
  36212. return;
  36213. }
  36214. }
  36215. else {
  36216. condition._evaluationId = currentRenderId;
  36217. if (!condition.isValid()) {
  36218. condition._currentResult = false;
  36219. return;
  36220. }
  36221. condition._currentResult = true;
  36222. }
  36223. }
  36224. this._nextActiveAction.execute(evt);
  36225. this.skipToNextActiveAction();
  36226. };
  36227. Action.prototype.execute = function (evt) {
  36228. };
  36229. Action.prototype.skipToNextActiveAction = function () {
  36230. if (this._nextActiveAction._child) {
  36231. if (!this._nextActiveAction._child._actionManager) {
  36232. this._nextActiveAction._child._actionManager = this._actionManager;
  36233. }
  36234. this._nextActiveAction = this._nextActiveAction._child;
  36235. }
  36236. else {
  36237. this._nextActiveAction = this;
  36238. }
  36239. };
  36240. Action.prototype.then = function (action) {
  36241. this._child = action;
  36242. action._actionManager = this._actionManager;
  36243. action._prepare();
  36244. return action;
  36245. };
  36246. Action.prototype._getProperty = function (propertyPath) {
  36247. return this._actionManager._getProperty(propertyPath);
  36248. };
  36249. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  36250. return this._actionManager._getEffectiveTarget(target, propertyPath);
  36251. };
  36252. Action.prototype.serialize = function (parent) {
  36253. };
  36254. // Called by BABYLON.Action objects in serialize(...). Internal use
  36255. Action.prototype._serialize = function (serializedAction, parent) {
  36256. var serializationObject = {
  36257. type: 1,
  36258. children: [],
  36259. name: serializedAction.name,
  36260. properties: serializedAction.properties || []
  36261. };
  36262. // Serialize child
  36263. if (this._child) {
  36264. this._child.serialize(serializationObject);
  36265. }
  36266. // Check if "this" has a condition
  36267. if (this._condition) {
  36268. var serializedCondition = this._condition.serialize();
  36269. serializedCondition.children.push(serializationObject);
  36270. if (parent) {
  36271. parent.children.push(serializedCondition);
  36272. }
  36273. return serializedCondition;
  36274. }
  36275. if (parent) {
  36276. parent.children.push(serializationObject);
  36277. }
  36278. return serializationObject;
  36279. };
  36280. return Action;
  36281. }());
  36282. Action._SerializeValueAsString = function (value) {
  36283. if (typeof value === "number") {
  36284. return value.toString();
  36285. }
  36286. if (typeof value === "boolean") {
  36287. return value ? "true" : "false";
  36288. }
  36289. if (value instanceof BABYLON.Vector2) {
  36290. return value.x + ", " + value.y;
  36291. }
  36292. if (value instanceof BABYLON.Vector3) {
  36293. return value.x + ", " + value.y + ", " + value.z;
  36294. }
  36295. if (value instanceof BABYLON.Color3) {
  36296. return value.r + ", " + value.g + ", " + value.b;
  36297. }
  36298. if (value instanceof BABYLON.Color4) {
  36299. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  36300. }
  36301. return value; // string
  36302. };
  36303. Action._GetTargetProperty = function (target) {
  36304. return {
  36305. name: "target",
  36306. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  36307. : target instanceof BABYLON.Light ? "LightProperties"
  36308. : target instanceof BABYLON.Camera ? "CameraProperties"
  36309. : "SceneProperties",
  36310. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  36311. };
  36312. };
  36313. BABYLON.Action = Action;
  36314. })(BABYLON || (BABYLON = {}));
  36315. //# sourceMappingURL=babylon.action.js.map
  36316. var BABYLON;
  36317. (function (BABYLON) {
  36318. /**
  36319. * ActionEvent is the event beint sent when an action is triggered.
  36320. */
  36321. var ActionEvent = (function () {
  36322. /**
  36323. * @constructor
  36324. * @param source The mesh or sprite that triggered the action.
  36325. * @param pointerX The X mouse cursor position at the time of the event
  36326. * @param pointerY The Y mouse cursor position at the time of the event
  36327. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  36328. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  36329. */
  36330. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  36331. this.source = source;
  36332. this.pointerX = pointerX;
  36333. this.pointerY = pointerY;
  36334. this.meshUnderPointer = meshUnderPointer;
  36335. this.sourceEvent = sourceEvent;
  36336. this.additionalData = additionalData;
  36337. }
  36338. /**
  36339. * Helper function to auto-create an ActionEvent from a source mesh.
  36340. * @param source The source mesh that triggered the event
  36341. * @param evt {Event} The original (browser) event
  36342. */
  36343. ActionEvent.CreateNew = function (source, evt, additionalData) {
  36344. var scene = source.getScene();
  36345. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36346. };
  36347. /**
  36348. * Helper function to auto-create an ActionEvent from a source mesh.
  36349. * @param source The source sprite that triggered the event
  36350. * @param scene Scene associated with the sprite
  36351. * @param evt {Event} The original (browser) event
  36352. */
  36353. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  36354. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  36355. };
  36356. /**
  36357. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  36358. * @param scene the scene where the event occurred
  36359. * @param evt {Event} The original (browser) event
  36360. */
  36361. ActionEvent.CreateNewFromScene = function (scene, evt) {
  36362. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  36363. };
  36364. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  36365. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  36366. };
  36367. return ActionEvent;
  36368. }());
  36369. BABYLON.ActionEvent = ActionEvent;
  36370. /**
  36371. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  36372. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  36373. */
  36374. var ActionManager = (function () {
  36375. function ActionManager(scene) {
  36376. // Members
  36377. this.actions = new Array();
  36378. this.hoverCursor = '';
  36379. this._scene = scene;
  36380. scene._actionManagers.push(this);
  36381. }
  36382. Object.defineProperty(ActionManager, "NothingTrigger", {
  36383. get: function () {
  36384. return ActionManager._NothingTrigger;
  36385. },
  36386. enumerable: true,
  36387. configurable: true
  36388. });
  36389. Object.defineProperty(ActionManager, "OnPickTrigger", {
  36390. get: function () {
  36391. return ActionManager._OnPickTrigger;
  36392. },
  36393. enumerable: true,
  36394. configurable: true
  36395. });
  36396. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  36397. get: function () {
  36398. return ActionManager._OnLeftPickTrigger;
  36399. },
  36400. enumerable: true,
  36401. configurable: true
  36402. });
  36403. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  36404. get: function () {
  36405. return ActionManager._OnRightPickTrigger;
  36406. },
  36407. enumerable: true,
  36408. configurable: true
  36409. });
  36410. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  36411. get: function () {
  36412. return ActionManager._OnCenterPickTrigger;
  36413. },
  36414. enumerable: true,
  36415. configurable: true
  36416. });
  36417. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  36418. get: function () {
  36419. return ActionManager._OnPickDownTrigger;
  36420. },
  36421. enumerable: true,
  36422. configurable: true
  36423. });
  36424. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  36425. get: function () {
  36426. return ActionManager._OnPickUpTrigger;
  36427. },
  36428. enumerable: true,
  36429. configurable: true
  36430. });
  36431. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  36432. /// This trigger will only be raised if you also declared a OnPickDown
  36433. get: function () {
  36434. return ActionManager._OnPickOutTrigger;
  36435. },
  36436. enumerable: true,
  36437. configurable: true
  36438. });
  36439. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  36440. get: function () {
  36441. return ActionManager._OnLongPressTrigger;
  36442. },
  36443. enumerable: true,
  36444. configurable: true
  36445. });
  36446. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  36447. get: function () {
  36448. return ActionManager._OnPointerOverTrigger;
  36449. },
  36450. enumerable: true,
  36451. configurable: true
  36452. });
  36453. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  36454. get: function () {
  36455. return ActionManager._OnPointerOutTrigger;
  36456. },
  36457. enumerable: true,
  36458. configurable: true
  36459. });
  36460. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  36461. get: function () {
  36462. return ActionManager._OnEveryFrameTrigger;
  36463. },
  36464. enumerable: true,
  36465. configurable: true
  36466. });
  36467. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  36468. get: function () {
  36469. return ActionManager._OnIntersectionEnterTrigger;
  36470. },
  36471. enumerable: true,
  36472. configurable: true
  36473. });
  36474. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  36475. get: function () {
  36476. return ActionManager._OnIntersectionExitTrigger;
  36477. },
  36478. enumerable: true,
  36479. configurable: true
  36480. });
  36481. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  36482. get: function () {
  36483. return ActionManager._OnKeyDownTrigger;
  36484. },
  36485. enumerable: true,
  36486. configurable: true
  36487. });
  36488. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  36489. get: function () {
  36490. return ActionManager._OnKeyUpTrigger;
  36491. },
  36492. enumerable: true,
  36493. configurable: true
  36494. });
  36495. // Methods
  36496. ActionManager.prototype.dispose = function () {
  36497. var index = this._scene._actionManagers.indexOf(this);
  36498. if (index > -1) {
  36499. this._scene._actionManagers.splice(index, 1);
  36500. }
  36501. };
  36502. ActionManager.prototype.getScene = function () {
  36503. return this._scene;
  36504. };
  36505. /**
  36506. * Does this action manager handles actions of any of the given triggers
  36507. * @param {number[]} triggers - the triggers to be tested
  36508. * @return {boolean} whether one (or more) of the triggers is handeled
  36509. */
  36510. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  36511. for (var index = 0; index < this.actions.length; index++) {
  36512. var action = this.actions[index];
  36513. if (triggers.indexOf(action.trigger) > -1) {
  36514. return true;
  36515. }
  36516. }
  36517. return false;
  36518. };
  36519. /**
  36520. * Does this action manager handles actions of a given trigger
  36521. * @param {number} trigger - the trigger to be tested
  36522. * @return {boolean} whether the trigger is handeled
  36523. */
  36524. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  36525. for (var index = 0; index < this.actions.length; index++) {
  36526. var action = this.actions[index];
  36527. if (action.trigger === trigger) {
  36528. return true;
  36529. }
  36530. }
  36531. return false;
  36532. };
  36533. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  36534. /**
  36535. * Does this action manager has pointer triggers
  36536. * @return {boolean} whether or not it has pointer triggers
  36537. */
  36538. get: function () {
  36539. for (var index = 0; index < this.actions.length; index++) {
  36540. var action = this.actions[index];
  36541. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  36542. return true;
  36543. }
  36544. }
  36545. return false;
  36546. },
  36547. enumerable: true,
  36548. configurable: true
  36549. });
  36550. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  36551. /**
  36552. * Does this action manager has pick triggers
  36553. * @return {boolean} whether or not it has pick triggers
  36554. */
  36555. get: function () {
  36556. for (var index = 0; index < this.actions.length; index++) {
  36557. var action = this.actions[index];
  36558. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  36559. return true;
  36560. }
  36561. }
  36562. return false;
  36563. },
  36564. enumerable: true,
  36565. configurable: true
  36566. });
  36567. /**
  36568. * Registers an action to this action manager
  36569. * @param {BABYLON.Action} action - the action to be registered
  36570. * @return {BABYLON.Action} the action amended (prepared) after registration
  36571. */
  36572. ActionManager.prototype.registerAction = function (action) {
  36573. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  36574. if (this.getScene().actionManager !== this) {
  36575. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  36576. return null;
  36577. }
  36578. }
  36579. this.actions.push(action);
  36580. action._actionManager = this;
  36581. action._prepare();
  36582. return action;
  36583. };
  36584. /**
  36585. * Process a specific trigger
  36586. * @param {number} trigger - the trigger to process
  36587. * @param evt {BABYLON.ActionEvent} the event details to be processed
  36588. */
  36589. ActionManager.prototype.processTrigger = function (trigger, evt) {
  36590. for (var index = 0; index < this.actions.length; index++) {
  36591. var action = this.actions[index];
  36592. if (action.trigger === trigger) {
  36593. if (trigger === ActionManager.OnKeyUpTrigger
  36594. || trigger === ActionManager.OnKeyDownTrigger) {
  36595. var parameter = action.getTriggerParameter();
  36596. if (parameter) {
  36597. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  36598. var actualkey = String.fromCharCode(unicode).toLowerCase();
  36599. if (actualkey !== parameter.toLowerCase()) {
  36600. continue;
  36601. }
  36602. }
  36603. }
  36604. action._executeCurrent(evt);
  36605. }
  36606. }
  36607. };
  36608. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  36609. var properties = propertyPath.split(".");
  36610. for (var index = 0; index < properties.length - 1; index++) {
  36611. target = target[properties[index]];
  36612. }
  36613. return target;
  36614. };
  36615. ActionManager.prototype._getProperty = function (propertyPath) {
  36616. var properties = propertyPath.split(".");
  36617. return properties[properties.length - 1];
  36618. };
  36619. ActionManager.prototype.serialize = function (name) {
  36620. var root = {
  36621. children: [],
  36622. name: name,
  36623. type: 3,
  36624. properties: [] // Empty for root but required
  36625. };
  36626. for (var i = 0; i < this.actions.length; i++) {
  36627. var triggerObject = {
  36628. type: 0,
  36629. children: [],
  36630. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  36631. properties: []
  36632. };
  36633. var triggerOptions = this.actions[i].triggerOptions;
  36634. if (triggerOptions && typeof triggerOptions !== "number") {
  36635. if (triggerOptions.parameter instanceof BABYLON.Node) {
  36636. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  36637. }
  36638. else {
  36639. var parameter = {};
  36640. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  36641. if (triggerOptions.parameter.mesh) {
  36642. parameter._meshId = triggerOptions.parameter.mesh.id;
  36643. }
  36644. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  36645. }
  36646. }
  36647. // Serialize child action, recursively
  36648. this.actions[i].serialize(triggerObject);
  36649. // Add serialized trigger
  36650. root.children.push(triggerObject);
  36651. }
  36652. return root;
  36653. };
  36654. ActionManager.Parse = function (parsedActions, object, scene) {
  36655. var actionManager = new BABYLON.ActionManager(scene);
  36656. if (object === null)
  36657. scene.actionManager = actionManager;
  36658. else
  36659. object.actionManager = actionManager;
  36660. // instanciate a new object
  36661. var instanciate = function (name, params) {
  36662. var newInstance = Object.create(BABYLON[name].prototype);
  36663. newInstance.constructor.apply(newInstance, params);
  36664. return newInstance;
  36665. };
  36666. var parseParameter = function (name, value, target, propertyPath) {
  36667. if (propertyPath === null) {
  36668. // String, boolean or float
  36669. var floatValue = parseFloat(value);
  36670. if (value === "true" || value === "false")
  36671. return value === "true";
  36672. else
  36673. return isNaN(floatValue) ? value : floatValue;
  36674. }
  36675. var effectiveTarget = propertyPath.split(".");
  36676. var values = value.split(",");
  36677. // Get effective Target
  36678. for (var i = 0; i < effectiveTarget.length; i++) {
  36679. target = target[effectiveTarget[i]];
  36680. }
  36681. // Return appropriate value with its type
  36682. if (typeof (target) === "boolean")
  36683. return values[0] === "true";
  36684. if (typeof (target) === "string")
  36685. return values[0];
  36686. // Parameters with multiple values such as Vector3 etc.
  36687. var split = new Array();
  36688. for (var i = 0; i < values.length; i++)
  36689. split.push(parseFloat(values[i]));
  36690. if (target instanceof BABYLON.Vector3)
  36691. return BABYLON.Vector3.FromArray(split);
  36692. if (target instanceof BABYLON.Vector4)
  36693. return BABYLON.Vector4.FromArray(split);
  36694. if (target instanceof BABYLON.Color3)
  36695. return BABYLON.Color3.FromArray(split);
  36696. if (target instanceof BABYLON.Color4)
  36697. return BABYLON.Color4.FromArray(split);
  36698. return parseFloat(values[0]);
  36699. };
  36700. // traverse graph per trigger
  36701. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  36702. if (combineArray === void 0) { combineArray = null; }
  36703. if (parsedAction.detached)
  36704. return;
  36705. var parameters = new Array();
  36706. var target = null;
  36707. var propertyPath = null;
  36708. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  36709. // Parameters
  36710. if (parsedAction.type === 2)
  36711. parameters.push(actionManager);
  36712. else
  36713. parameters.push(trigger);
  36714. if (combine) {
  36715. var actions = new Array();
  36716. for (var j = 0; j < parsedAction.combine.length; j++) {
  36717. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  36718. }
  36719. parameters.push(actions);
  36720. }
  36721. else {
  36722. for (var i = 0; i < parsedAction.properties.length; i++) {
  36723. var value = parsedAction.properties[i].value;
  36724. var name = parsedAction.properties[i].name;
  36725. var targetType = parsedAction.properties[i].targetType;
  36726. if (name === "target")
  36727. if (targetType !== null && targetType === "SceneProperties")
  36728. value = target = scene;
  36729. else
  36730. value = target = scene.getNodeByName(value);
  36731. else if (name === "parent")
  36732. value = scene.getNodeByName(value);
  36733. else if (name === "sound")
  36734. value = scene.getSoundByName(value);
  36735. else if (name !== "propertyPath") {
  36736. if (parsedAction.type === 2 && name === "operator")
  36737. value = BABYLON.ValueCondition[value];
  36738. else
  36739. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  36740. }
  36741. else {
  36742. propertyPath = value;
  36743. }
  36744. parameters.push(value);
  36745. }
  36746. }
  36747. if (combineArray === null) {
  36748. parameters.push(condition);
  36749. }
  36750. else {
  36751. parameters.push(null);
  36752. }
  36753. // If interpolate value action
  36754. if (parsedAction.name === "InterpolateValueAction") {
  36755. var param = parameters[parameters.length - 2];
  36756. parameters[parameters.length - 1] = param;
  36757. parameters[parameters.length - 2] = condition;
  36758. }
  36759. // Action or condition(s) and not CombineAction
  36760. var newAction = instanciate(parsedAction.name, parameters);
  36761. if (newAction instanceof BABYLON.Condition && condition !== null) {
  36762. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  36763. if (action)
  36764. action.then(nothing);
  36765. else
  36766. actionManager.registerAction(nothing);
  36767. action = nothing;
  36768. }
  36769. if (combineArray === null) {
  36770. if (newAction instanceof BABYLON.Condition) {
  36771. condition = newAction;
  36772. newAction = action;
  36773. }
  36774. else {
  36775. condition = null;
  36776. if (action)
  36777. action.then(newAction);
  36778. else
  36779. actionManager.registerAction(newAction);
  36780. }
  36781. }
  36782. else {
  36783. combineArray.push(newAction);
  36784. }
  36785. for (var i = 0; i < parsedAction.children.length; i++)
  36786. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  36787. };
  36788. // triggers
  36789. for (var i = 0; i < parsedActions.children.length; i++) {
  36790. var triggerParams;
  36791. var trigger = parsedActions.children[i];
  36792. if (trigger.properties.length > 0) {
  36793. var param = trigger.properties[0].value;
  36794. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  36795. if (value._meshId) {
  36796. value.mesh = scene.getMeshByID(value._meshId);
  36797. }
  36798. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  36799. }
  36800. else
  36801. triggerParams = BABYLON.ActionManager[trigger.name];
  36802. for (var j = 0; j < trigger.children.length; j++) {
  36803. if (!trigger.detached)
  36804. traverse(trigger.children[j], triggerParams, null, null);
  36805. }
  36806. }
  36807. };
  36808. ActionManager.GetTriggerName = function (trigger) {
  36809. switch (trigger) {
  36810. case 0: return "NothingTrigger";
  36811. case 1: return "OnPickTrigger";
  36812. case 2: return "OnLeftPickTrigger";
  36813. case 3: return "OnRightPickTrigger";
  36814. case 4: return "OnCenterPickTrigger";
  36815. case 5: return "OnPickDownTrigger";
  36816. case 6: return "OnPickUpTrigger";
  36817. case 7: return "OnLongPressTrigger";
  36818. case 8: return "OnPointerOverTrigger";
  36819. case 9: return "OnPointerOutTrigger";
  36820. case 10: return "OnEveryFrameTrigger";
  36821. case 11: return "OnIntersectionEnterTrigger";
  36822. case 12: return "OnIntersectionExitTrigger";
  36823. case 13: return "OnKeyDownTrigger";
  36824. case 14: return "OnKeyUpTrigger";
  36825. case 15: return "OnPickOutTrigger";
  36826. default: return "";
  36827. }
  36828. };
  36829. return ActionManager;
  36830. }());
  36831. // Statics
  36832. ActionManager._NothingTrigger = 0;
  36833. ActionManager._OnPickTrigger = 1;
  36834. ActionManager._OnLeftPickTrigger = 2;
  36835. ActionManager._OnRightPickTrigger = 3;
  36836. ActionManager._OnCenterPickTrigger = 4;
  36837. ActionManager._OnPickDownTrigger = 5;
  36838. ActionManager._OnPickUpTrigger = 6;
  36839. ActionManager._OnLongPressTrigger = 7;
  36840. ActionManager._OnPointerOverTrigger = 8;
  36841. ActionManager._OnPointerOutTrigger = 9;
  36842. ActionManager._OnEveryFrameTrigger = 10;
  36843. ActionManager._OnIntersectionEnterTrigger = 11;
  36844. ActionManager._OnIntersectionExitTrigger = 12;
  36845. ActionManager._OnKeyDownTrigger = 13;
  36846. ActionManager._OnKeyUpTrigger = 14;
  36847. ActionManager._OnPickOutTrigger = 15;
  36848. ActionManager.DragMovementThreshold = 10; // in pixels
  36849. ActionManager.LongPressDelay = 500; // in milliseconds
  36850. BABYLON.ActionManager = ActionManager;
  36851. })(BABYLON || (BABYLON = {}));
  36852. //# sourceMappingURL=babylon.actionManager.js.map
  36853. var BABYLON;
  36854. (function (BABYLON) {
  36855. var InterpolateValueAction = (function (_super) {
  36856. __extends(InterpolateValueAction, _super);
  36857. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  36858. if (duration === void 0) { duration = 1000; }
  36859. var _this = _super.call(this, triggerOptions, condition) || this;
  36860. _this.propertyPath = propertyPath;
  36861. _this.value = value;
  36862. _this.duration = duration;
  36863. _this.stopOtherAnimations = stopOtherAnimations;
  36864. _this.onInterpolationDone = onInterpolationDone;
  36865. _this._target = _this._effectiveTarget = target;
  36866. return _this;
  36867. }
  36868. InterpolateValueAction.prototype._prepare = function () {
  36869. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36870. this._property = this._getProperty(this.propertyPath);
  36871. };
  36872. InterpolateValueAction.prototype.execute = function () {
  36873. var scene = this._actionManager.getScene();
  36874. var keys = [
  36875. {
  36876. frame: 0,
  36877. value: this._effectiveTarget[this._property]
  36878. }, {
  36879. frame: 100,
  36880. value: this.value
  36881. }
  36882. ];
  36883. var dataType;
  36884. if (typeof this.value === "number") {
  36885. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  36886. }
  36887. else if (this.value instanceof BABYLON.Color3) {
  36888. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  36889. }
  36890. else if (this.value instanceof BABYLON.Vector3) {
  36891. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  36892. }
  36893. else if (this.value instanceof BABYLON.Matrix) {
  36894. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  36895. }
  36896. else if (this.value instanceof BABYLON.Quaternion) {
  36897. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  36898. }
  36899. else {
  36900. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  36901. return;
  36902. }
  36903. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36904. animation.setKeys(keys);
  36905. if (this.stopOtherAnimations) {
  36906. scene.stopAnimation(this._effectiveTarget);
  36907. }
  36908. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  36909. };
  36910. InterpolateValueAction.prototype.serialize = function (parent) {
  36911. return _super.prototype._serialize.call(this, {
  36912. name: "InterpolateValueAction",
  36913. properties: [
  36914. BABYLON.Action._GetTargetProperty(this._target),
  36915. { name: "propertyPath", value: this.propertyPath },
  36916. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  36917. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  36918. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  36919. ]
  36920. }, parent);
  36921. };
  36922. return InterpolateValueAction;
  36923. }(BABYLON.Action));
  36924. BABYLON.InterpolateValueAction = InterpolateValueAction;
  36925. })(BABYLON || (BABYLON = {}));
  36926. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  36927. var BABYLON;
  36928. (function (BABYLON) {
  36929. var SwitchBooleanAction = (function (_super) {
  36930. __extends(SwitchBooleanAction, _super);
  36931. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  36932. var _this = _super.call(this, triggerOptions, condition) || this;
  36933. _this.propertyPath = propertyPath;
  36934. _this._target = _this._effectiveTarget = target;
  36935. return _this;
  36936. }
  36937. SwitchBooleanAction.prototype._prepare = function () {
  36938. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36939. this._property = this._getProperty(this.propertyPath);
  36940. };
  36941. SwitchBooleanAction.prototype.execute = function () {
  36942. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  36943. };
  36944. SwitchBooleanAction.prototype.serialize = function (parent) {
  36945. return _super.prototype._serialize.call(this, {
  36946. name: "SwitchBooleanAction",
  36947. properties: [
  36948. BABYLON.Action._GetTargetProperty(this._target),
  36949. { name: "propertyPath", value: this.propertyPath }
  36950. ]
  36951. }, parent);
  36952. };
  36953. return SwitchBooleanAction;
  36954. }(BABYLON.Action));
  36955. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  36956. var SetStateAction = (function (_super) {
  36957. __extends(SetStateAction, _super);
  36958. function SetStateAction(triggerOptions, target, value, condition) {
  36959. var _this = _super.call(this, triggerOptions, condition) || this;
  36960. _this.value = value;
  36961. _this._target = target;
  36962. return _this;
  36963. }
  36964. SetStateAction.prototype.execute = function () {
  36965. this._target.state = this.value;
  36966. };
  36967. SetStateAction.prototype.serialize = function (parent) {
  36968. return _super.prototype._serialize.call(this, {
  36969. name: "SetStateAction",
  36970. properties: [
  36971. BABYLON.Action._GetTargetProperty(this._target),
  36972. { name: "value", value: this.value }
  36973. ]
  36974. }, parent);
  36975. };
  36976. return SetStateAction;
  36977. }(BABYLON.Action));
  36978. BABYLON.SetStateAction = SetStateAction;
  36979. var SetValueAction = (function (_super) {
  36980. __extends(SetValueAction, _super);
  36981. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  36982. var _this = _super.call(this, triggerOptions, condition) || this;
  36983. _this.propertyPath = propertyPath;
  36984. _this.value = value;
  36985. _this._target = _this._effectiveTarget = target;
  36986. return _this;
  36987. }
  36988. SetValueAction.prototype._prepare = function () {
  36989. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  36990. this._property = this._getProperty(this.propertyPath);
  36991. };
  36992. SetValueAction.prototype.execute = function () {
  36993. this._effectiveTarget[this._property] = this.value;
  36994. if (this._target.markAsDirty) {
  36995. this._target.markAsDirty(this._property);
  36996. }
  36997. };
  36998. SetValueAction.prototype.serialize = function (parent) {
  36999. return _super.prototype._serialize.call(this, {
  37000. name: "SetValueAction",
  37001. properties: [
  37002. BABYLON.Action._GetTargetProperty(this._target),
  37003. { name: "propertyPath", value: this.propertyPath },
  37004. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37005. ]
  37006. }, parent);
  37007. };
  37008. return SetValueAction;
  37009. }(BABYLON.Action));
  37010. BABYLON.SetValueAction = SetValueAction;
  37011. var IncrementValueAction = (function (_super) {
  37012. __extends(IncrementValueAction, _super);
  37013. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  37014. var _this = _super.call(this, triggerOptions, condition) || this;
  37015. _this.propertyPath = propertyPath;
  37016. _this.value = value;
  37017. _this._target = _this._effectiveTarget = target;
  37018. return _this;
  37019. }
  37020. IncrementValueAction.prototype._prepare = function () {
  37021. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  37022. this._property = this._getProperty(this.propertyPath);
  37023. if (typeof this._effectiveTarget[this._property] !== "number") {
  37024. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  37025. }
  37026. };
  37027. IncrementValueAction.prototype.execute = function () {
  37028. this._effectiveTarget[this._property] += this.value;
  37029. if (this._target.markAsDirty) {
  37030. this._target.markAsDirty(this._property);
  37031. }
  37032. };
  37033. IncrementValueAction.prototype.serialize = function (parent) {
  37034. return _super.prototype._serialize.call(this, {
  37035. name: "IncrementValueAction",
  37036. properties: [
  37037. BABYLON.Action._GetTargetProperty(this._target),
  37038. { name: "propertyPath", value: this.propertyPath },
  37039. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  37040. ]
  37041. }, parent);
  37042. };
  37043. return IncrementValueAction;
  37044. }(BABYLON.Action));
  37045. BABYLON.IncrementValueAction = IncrementValueAction;
  37046. var PlayAnimationAction = (function (_super) {
  37047. __extends(PlayAnimationAction, _super);
  37048. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  37049. var _this = _super.call(this, triggerOptions, condition) || this;
  37050. _this.from = from;
  37051. _this.to = to;
  37052. _this.loop = loop;
  37053. _this._target = target;
  37054. return _this;
  37055. }
  37056. PlayAnimationAction.prototype._prepare = function () {
  37057. };
  37058. PlayAnimationAction.prototype.execute = function () {
  37059. var scene = this._actionManager.getScene();
  37060. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  37061. };
  37062. PlayAnimationAction.prototype.serialize = function (parent) {
  37063. return _super.prototype._serialize.call(this, {
  37064. name: "PlayAnimationAction",
  37065. properties: [
  37066. BABYLON.Action._GetTargetProperty(this._target),
  37067. { name: "from", value: String(this.from) },
  37068. { name: "to", value: String(this.to) },
  37069. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  37070. ]
  37071. }, parent);
  37072. };
  37073. return PlayAnimationAction;
  37074. }(BABYLON.Action));
  37075. BABYLON.PlayAnimationAction = PlayAnimationAction;
  37076. var StopAnimationAction = (function (_super) {
  37077. __extends(StopAnimationAction, _super);
  37078. function StopAnimationAction(triggerOptions, target, condition) {
  37079. var _this = _super.call(this, triggerOptions, condition) || this;
  37080. _this._target = target;
  37081. return _this;
  37082. }
  37083. StopAnimationAction.prototype._prepare = function () {
  37084. };
  37085. StopAnimationAction.prototype.execute = function () {
  37086. var scene = this._actionManager.getScene();
  37087. scene.stopAnimation(this._target);
  37088. };
  37089. StopAnimationAction.prototype.serialize = function (parent) {
  37090. return _super.prototype._serialize.call(this, {
  37091. name: "StopAnimationAction",
  37092. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  37093. }, parent);
  37094. };
  37095. return StopAnimationAction;
  37096. }(BABYLON.Action));
  37097. BABYLON.StopAnimationAction = StopAnimationAction;
  37098. var DoNothingAction = (function (_super) {
  37099. __extends(DoNothingAction, _super);
  37100. function DoNothingAction(triggerOptions, condition) {
  37101. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  37102. return _super.call(this, triggerOptions, condition) || this;
  37103. }
  37104. DoNothingAction.prototype.execute = function () {
  37105. };
  37106. DoNothingAction.prototype.serialize = function (parent) {
  37107. return _super.prototype._serialize.call(this, {
  37108. name: "DoNothingAction",
  37109. properties: []
  37110. }, parent);
  37111. };
  37112. return DoNothingAction;
  37113. }(BABYLON.Action));
  37114. BABYLON.DoNothingAction = DoNothingAction;
  37115. var CombineAction = (function (_super) {
  37116. __extends(CombineAction, _super);
  37117. function CombineAction(triggerOptions, children, condition) {
  37118. var _this = _super.call(this, triggerOptions, condition) || this;
  37119. _this.children = children;
  37120. return _this;
  37121. }
  37122. CombineAction.prototype._prepare = function () {
  37123. for (var index = 0; index < this.children.length; index++) {
  37124. this.children[index]._actionManager = this._actionManager;
  37125. this.children[index]._prepare();
  37126. }
  37127. };
  37128. CombineAction.prototype.execute = function (evt) {
  37129. for (var index = 0; index < this.children.length; index++) {
  37130. this.children[index].execute(evt);
  37131. }
  37132. };
  37133. CombineAction.prototype.serialize = function (parent) {
  37134. var serializationObject = _super.prototype._serialize.call(this, {
  37135. name: "CombineAction",
  37136. properties: [],
  37137. combine: []
  37138. }, parent);
  37139. for (var i = 0; i < this.children.length; i++) {
  37140. serializationObject.combine.push(this.children[i].serialize(null));
  37141. }
  37142. return serializationObject;
  37143. };
  37144. return CombineAction;
  37145. }(BABYLON.Action));
  37146. BABYLON.CombineAction = CombineAction;
  37147. var ExecuteCodeAction = (function (_super) {
  37148. __extends(ExecuteCodeAction, _super);
  37149. function ExecuteCodeAction(triggerOptions, func, condition) {
  37150. var _this = _super.call(this, triggerOptions, condition) || this;
  37151. _this.func = func;
  37152. return _this;
  37153. }
  37154. ExecuteCodeAction.prototype.execute = function (evt) {
  37155. this.func(evt);
  37156. };
  37157. return ExecuteCodeAction;
  37158. }(BABYLON.Action));
  37159. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  37160. var SetParentAction = (function (_super) {
  37161. __extends(SetParentAction, _super);
  37162. function SetParentAction(triggerOptions, target, parent, condition) {
  37163. var _this = _super.call(this, triggerOptions, condition) || this;
  37164. _this._target = target;
  37165. _this._parent = parent;
  37166. return _this;
  37167. }
  37168. SetParentAction.prototype._prepare = function () {
  37169. };
  37170. SetParentAction.prototype.execute = function () {
  37171. if (this._target.parent === this._parent) {
  37172. return;
  37173. }
  37174. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  37175. invertParentWorldMatrix.invert();
  37176. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  37177. this._target.parent = this._parent;
  37178. };
  37179. SetParentAction.prototype.serialize = function (parent) {
  37180. return _super.prototype._serialize.call(this, {
  37181. name: "SetParentAction",
  37182. properties: [
  37183. BABYLON.Action._GetTargetProperty(this._target),
  37184. BABYLON.Action._GetTargetProperty(this._parent),
  37185. ]
  37186. }, parent);
  37187. };
  37188. return SetParentAction;
  37189. }(BABYLON.Action));
  37190. BABYLON.SetParentAction = SetParentAction;
  37191. var PlaySoundAction = (function (_super) {
  37192. __extends(PlaySoundAction, _super);
  37193. function PlaySoundAction(triggerOptions, sound, condition) {
  37194. var _this = _super.call(this, triggerOptions, condition) || this;
  37195. _this._sound = sound;
  37196. return _this;
  37197. }
  37198. PlaySoundAction.prototype._prepare = function () {
  37199. };
  37200. PlaySoundAction.prototype.execute = function () {
  37201. if (this._sound !== undefined)
  37202. this._sound.play();
  37203. };
  37204. PlaySoundAction.prototype.serialize = function (parent) {
  37205. return _super.prototype._serialize.call(this, {
  37206. name: "PlaySoundAction",
  37207. properties: [{ name: "sound", value: this._sound.name }]
  37208. }, parent);
  37209. };
  37210. return PlaySoundAction;
  37211. }(BABYLON.Action));
  37212. BABYLON.PlaySoundAction = PlaySoundAction;
  37213. var StopSoundAction = (function (_super) {
  37214. __extends(StopSoundAction, _super);
  37215. function StopSoundAction(triggerOptions, sound, condition) {
  37216. var _this = _super.call(this, triggerOptions, condition) || this;
  37217. _this._sound = sound;
  37218. return _this;
  37219. }
  37220. StopSoundAction.prototype._prepare = function () {
  37221. };
  37222. StopSoundAction.prototype.execute = function () {
  37223. if (this._sound !== undefined)
  37224. this._sound.stop();
  37225. };
  37226. StopSoundAction.prototype.serialize = function (parent) {
  37227. return _super.prototype._serialize.call(this, {
  37228. name: "StopSoundAction",
  37229. properties: [{ name: "sound", value: this._sound.name }]
  37230. }, parent);
  37231. };
  37232. return StopSoundAction;
  37233. }(BABYLON.Action));
  37234. BABYLON.StopSoundAction = StopSoundAction;
  37235. })(BABYLON || (BABYLON = {}));
  37236. //# sourceMappingURL=babylon.directActions.js.map
  37237. var BABYLON;
  37238. (function (BABYLON) {
  37239. var Geometry = (function () {
  37240. function Geometry(id, scene, vertexData, updatable, mesh) {
  37241. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37242. this._totalVertices = 0;
  37243. this._isDisposed = false;
  37244. this.id = id;
  37245. this._engine = scene.getEngine();
  37246. this._meshes = [];
  37247. this._scene = scene;
  37248. //Init vertex buffer cache
  37249. this._vertexBuffers = {};
  37250. this._indices = [];
  37251. // vertexData
  37252. if (vertexData) {
  37253. this.setAllVerticesData(vertexData, updatable);
  37254. }
  37255. else {
  37256. this._totalVertices = 0;
  37257. this._indices = [];
  37258. }
  37259. if (this._engine.getCaps().vertexArrayObject) {
  37260. this._vertexArrayObjects = {};
  37261. }
  37262. // applyToMesh
  37263. if (mesh) {
  37264. if (mesh instanceof BABYLON.LinesMesh) {
  37265. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  37266. this.updateExtend();
  37267. }
  37268. this.applyToMesh(mesh);
  37269. mesh.computeWorldMatrix(true);
  37270. }
  37271. }
  37272. Object.defineProperty(Geometry.prototype, "boundingBias", {
  37273. /**
  37274. * 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
  37275. * @returns The Bias Vector
  37276. */
  37277. get: function () {
  37278. return this._boundingBias;
  37279. },
  37280. set: function (value) {
  37281. if (this._boundingBias && this._boundingBias.equals(value)) {
  37282. return;
  37283. }
  37284. this._boundingBias = value.clone();
  37285. this.updateBoundingInfo(true, null);
  37286. },
  37287. enumerable: true,
  37288. configurable: true
  37289. });
  37290. Object.defineProperty(Geometry.prototype, "extend", {
  37291. get: function () {
  37292. return this._extend;
  37293. },
  37294. enumerable: true,
  37295. configurable: true
  37296. });
  37297. Geometry.prototype.getScene = function () {
  37298. return this._scene;
  37299. };
  37300. Geometry.prototype.getEngine = function () {
  37301. return this._engine;
  37302. };
  37303. Geometry.prototype.isReady = function () {
  37304. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  37305. };
  37306. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  37307. get: function () {
  37308. for (var index = 0; index < this._meshes.length; index++) {
  37309. if (!this._meshes[index].doNotSerialize) {
  37310. return false;
  37311. }
  37312. }
  37313. return true;
  37314. },
  37315. enumerable: true,
  37316. configurable: true
  37317. });
  37318. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  37319. vertexData.applyToGeometry(this, updatable);
  37320. this.notifyUpdate();
  37321. };
  37322. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  37323. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  37324. this.setVerticesBuffer(buffer);
  37325. };
  37326. Geometry.prototype.setVerticesBuffer = function (buffer) {
  37327. var kind = buffer.getKind();
  37328. if (this._vertexBuffers[kind]) {
  37329. this._vertexBuffers[kind].dispose();
  37330. }
  37331. this._vertexBuffers[kind] = buffer;
  37332. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37333. var data = buffer.getData();
  37334. var stride = buffer.getStrideSize();
  37335. this._totalVertices = data.length / stride;
  37336. this.updateExtend(data, stride);
  37337. var meshes = this._meshes;
  37338. var numOfMeshes = meshes.length;
  37339. for (var index = 0; index < numOfMeshes; index++) {
  37340. var mesh = meshes[index];
  37341. mesh._resetPointsArrayCache();
  37342. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37343. mesh._createGlobalSubMesh();
  37344. mesh.computeWorldMatrix(true);
  37345. }
  37346. }
  37347. this.notifyUpdate(kind);
  37348. if (this._vertexArrayObjects) {
  37349. this._disposeVertexArrayObjects();
  37350. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  37351. }
  37352. };
  37353. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  37354. var vertexBuffer = this.getVertexBuffer(kind);
  37355. if (!vertexBuffer) {
  37356. return;
  37357. }
  37358. vertexBuffer.updateDirectly(data, offset);
  37359. this.notifyUpdate(kind);
  37360. };
  37361. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  37362. var vertexBuffer = this.getVertexBuffer(kind);
  37363. if (!vertexBuffer) {
  37364. return;
  37365. }
  37366. vertexBuffer.update(data);
  37367. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37368. var stride = vertexBuffer.getStrideSize();
  37369. this._totalVertices = data.length / stride;
  37370. this.updateBoundingInfo(updateExtends, data);
  37371. }
  37372. this.notifyUpdate(kind);
  37373. };
  37374. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  37375. if (updateExtends) {
  37376. this.updateExtend(data);
  37377. }
  37378. var meshes = this._meshes;
  37379. var numOfMeshes = meshes.length;
  37380. for (var index = 0; index < numOfMeshes; index++) {
  37381. var mesh = meshes[index];
  37382. mesh._resetPointsArrayCache();
  37383. if (updateExtends) {
  37384. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37385. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  37386. var subMesh = mesh.subMeshes[subIndex];
  37387. subMesh.refreshBoundingInfo();
  37388. }
  37389. }
  37390. }
  37391. };
  37392. Geometry.prototype._bind = function (effect, indexToBind) {
  37393. if (indexToBind === void 0) { indexToBind = undefined; }
  37394. if (indexToBind === undefined) {
  37395. indexToBind = this._indexBuffer;
  37396. }
  37397. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  37398. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  37399. return;
  37400. }
  37401. // Using VAO
  37402. if (!this._vertexArrayObjects[effect.key]) {
  37403. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  37404. }
  37405. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  37406. };
  37407. Geometry.prototype.getTotalVertices = function () {
  37408. if (!this.isReady()) {
  37409. return 0;
  37410. }
  37411. return this._totalVertices;
  37412. };
  37413. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  37414. var vertexBuffer = this.getVertexBuffer(kind);
  37415. if (!vertexBuffer) {
  37416. return null;
  37417. }
  37418. var orig = vertexBuffer.getData();
  37419. if (!copyWhenShared || this._meshes.length === 1) {
  37420. return orig;
  37421. }
  37422. else {
  37423. var len = orig.length;
  37424. var copy = [];
  37425. for (var i = 0; i < len; i++) {
  37426. copy.push(orig[i]);
  37427. }
  37428. return copy;
  37429. }
  37430. };
  37431. Geometry.prototype.getVertexBuffer = function (kind) {
  37432. if (!this.isReady()) {
  37433. return null;
  37434. }
  37435. return this._vertexBuffers[kind];
  37436. };
  37437. Geometry.prototype.getVertexBuffers = function () {
  37438. if (!this.isReady()) {
  37439. return null;
  37440. }
  37441. return this._vertexBuffers;
  37442. };
  37443. Geometry.prototype.isVerticesDataPresent = function (kind) {
  37444. if (!this._vertexBuffers) {
  37445. if (this._delayInfo) {
  37446. return this._delayInfo.indexOf(kind) !== -1;
  37447. }
  37448. return false;
  37449. }
  37450. return this._vertexBuffers[kind] !== undefined;
  37451. };
  37452. Geometry.prototype.getVerticesDataKinds = function () {
  37453. var result = [];
  37454. var kind;
  37455. if (!this._vertexBuffers && this._delayInfo) {
  37456. for (kind in this._delayInfo) {
  37457. result.push(kind);
  37458. }
  37459. }
  37460. else {
  37461. for (kind in this._vertexBuffers) {
  37462. result.push(kind);
  37463. }
  37464. }
  37465. return result;
  37466. };
  37467. Geometry.prototype.setIndices = function (indices, totalVertices) {
  37468. if (this._indexBuffer) {
  37469. this._engine._releaseBuffer(this._indexBuffer);
  37470. }
  37471. this._disposeVertexArrayObjects();
  37472. this._indices = indices;
  37473. if (this._meshes.length !== 0 && this._indices) {
  37474. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37475. }
  37476. if (totalVertices !== undefined) {
  37477. this._totalVertices = totalVertices;
  37478. }
  37479. var meshes = this._meshes;
  37480. var numOfMeshes = meshes.length;
  37481. for (var index = 0; index < numOfMeshes; index++) {
  37482. meshes[index]._createGlobalSubMesh();
  37483. }
  37484. this.notifyUpdate();
  37485. };
  37486. Geometry.prototype.getTotalIndices = function () {
  37487. if (!this.isReady()) {
  37488. return 0;
  37489. }
  37490. return this._indices.length;
  37491. };
  37492. Geometry.prototype.getIndices = function (copyWhenShared) {
  37493. if (!this.isReady()) {
  37494. return null;
  37495. }
  37496. var orig = this._indices;
  37497. if (!copyWhenShared || this._meshes.length === 1) {
  37498. return orig;
  37499. }
  37500. else {
  37501. var len = orig.length;
  37502. var copy = [];
  37503. for (var i = 0; i < len; i++) {
  37504. copy.push(orig[i]);
  37505. }
  37506. return copy;
  37507. }
  37508. };
  37509. Geometry.prototype.getIndexBuffer = function () {
  37510. if (!this.isReady()) {
  37511. return null;
  37512. }
  37513. return this._indexBuffer;
  37514. };
  37515. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  37516. var meshes = this._meshes;
  37517. var index = meshes.indexOf(mesh);
  37518. if (index === -1) {
  37519. return;
  37520. }
  37521. meshes.splice(index, 1);
  37522. mesh._geometry = null;
  37523. if (meshes.length === 0 && shouldDispose) {
  37524. this.dispose();
  37525. }
  37526. };
  37527. Geometry.prototype.applyToMesh = function (mesh) {
  37528. if (mesh._geometry === this) {
  37529. return;
  37530. }
  37531. var previousGeometry = mesh._geometry;
  37532. if (previousGeometry) {
  37533. previousGeometry.releaseForMesh(mesh);
  37534. }
  37535. var meshes = this._meshes;
  37536. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  37537. mesh._geometry = this;
  37538. this._scene.pushGeometry(this);
  37539. meshes.push(mesh);
  37540. if (this.isReady()) {
  37541. this._applyToMesh(mesh);
  37542. }
  37543. else {
  37544. mesh._boundingInfo = this._boundingInfo;
  37545. }
  37546. };
  37547. Geometry.prototype.updateExtend = function (data, stride) {
  37548. if (data === void 0) { data = null; }
  37549. if (!data) {
  37550. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  37551. }
  37552. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  37553. };
  37554. Geometry.prototype._applyToMesh = function (mesh) {
  37555. var numOfMeshes = this._meshes.length;
  37556. // vertexBuffers
  37557. for (var kind in this._vertexBuffers) {
  37558. if (numOfMeshes === 1) {
  37559. this._vertexBuffers[kind].create();
  37560. }
  37561. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  37562. if (kind === BABYLON.VertexBuffer.PositionKind) {
  37563. mesh._resetPointsArrayCache();
  37564. if (!this._extend) {
  37565. this.updateExtend(this._vertexBuffers[kind].getData());
  37566. }
  37567. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37568. mesh._createGlobalSubMesh();
  37569. //bounding info was just created again, world matrix should be applied again.
  37570. mesh._updateBoundingInfo();
  37571. }
  37572. }
  37573. // indexBuffer
  37574. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  37575. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  37576. }
  37577. if (this._indexBuffer) {
  37578. this._indexBuffer.references = numOfMeshes;
  37579. }
  37580. };
  37581. Geometry.prototype.notifyUpdate = function (kind) {
  37582. if (this.onGeometryUpdated) {
  37583. this.onGeometryUpdated(this, kind);
  37584. }
  37585. };
  37586. Geometry.prototype.load = function (scene, onLoaded) {
  37587. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  37588. return;
  37589. }
  37590. if (this.isReady()) {
  37591. if (onLoaded) {
  37592. onLoaded();
  37593. }
  37594. return;
  37595. }
  37596. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  37597. this._queueLoad(scene, onLoaded);
  37598. };
  37599. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  37600. var _this = this;
  37601. scene._addPendingData(this);
  37602. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  37603. _this._delayLoadingFunction(JSON.parse(data), _this);
  37604. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  37605. _this._delayInfo = [];
  37606. scene._removePendingData(_this);
  37607. var meshes = _this._meshes;
  37608. var numOfMeshes = meshes.length;
  37609. for (var index = 0; index < numOfMeshes; index++) {
  37610. _this._applyToMesh(meshes[index]);
  37611. }
  37612. if (onLoaded) {
  37613. onLoaded();
  37614. }
  37615. }, function () { }, scene.database);
  37616. };
  37617. /**
  37618. * Invert the geometry to move from a right handed system to a left handed one.
  37619. */
  37620. Geometry.prototype.toLeftHanded = function () {
  37621. // Flip faces
  37622. var tIndices = this.getIndices(false);
  37623. if (tIndices != null && tIndices.length > 0) {
  37624. for (var i = 0; i < tIndices.length; i += 3) {
  37625. var tTemp = tIndices[i + 0];
  37626. tIndices[i + 0] = tIndices[i + 2];
  37627. tIndices[i + 2] = tTemp;
  37628. }
  37629. this.setIndices(tIndices);
  37630. }
  37631. // Negate position.z
  37632. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  37633. if (tPositions != null && tPositions.length > 0) {
  37634. for (var i = 0; i < tPositions.length; i += 3) {
  37635. tPositions[i + 2] = -tPositions[i + 2];
  37636. }
  37637. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  37638. }
  37639. // Negate normal.z
  37640. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  37641. if (tNormals != null && tNormals.length > 0) {
  37642. for (var i = 0; i < tNormals.length; i += 3) {
  37643. tNormals[i + 2] = -tNormals[i + 2];
  37644. }
  37645. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  37646. }
  37647. };
  37648. Geometry.prototype.isDisposed = function () {
  37649. return this._isDisposed;
  37650. };
  37651. Geometry.prototype._disposeVertexArrayObjects = function () {
  37652. if (this._vertexArrayObjects) {
  37653. for (var kind in this._vertexArrayObjects) {
  37654. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  37655. }
  37656. this._vertexArrayObjects = {};
  37657. }
  37658. };
  37659. Geometry.prototype.dispose = function () {
  37660. var meshes = this._meshes;
  37661. var numOfMeshes = meshes.length;
  37662. var index;
  37663. for (index = 0; index < numOfMeshes; index++) {
  37664. this.releaseForMesh(meshes[index]);
  37665. }
  37666. this._meshes = [];
  37667. this._disposeVertexArrayObjects();
  37668. for (var kind in this._vertexBuffers) {
  37669. this._vertexBuffers[kind].dispose();
  37670. }
  37671. this._vertexBuffers = {};
  37672. this._totalVertices = 0;
  37673. if (this._indexBuffer) {
  37674. this._engine._releaseBuffer(this._indexBuffer);
  37675. }
  37676. this._indexBuffer = null;
  37677. this._indices = [];
  37678. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  37679. this.delayLoadingFile = null;
  37680. this._delayLoadingFunction = null;
  37681. this._delayInfo = [];
  37682. this._boundingInfo = null;
  37683. this._scene.removeGeometry(this);
  37684. this._isDisposed = true;
  37685. };
  37686. Geometry.prototype.copy = function (id) {
  37687. var vertexData = new BABYLON.VertexData();
  37688. vertexData.indices = [];
  37689. var indices = this.getIndices();
  37690. for (var index = 0; index < indices.length; index++) {
  37691. vertexData.indices.push(indices[index]);
  37692. }
  37693. var updatable = false;
  37694. var stopChecking = false;
  37695. var kind;
  37696. for (kind in this._vertexBuffers) {
  37697. // using slice() to make a copy of the array and not just reference it
  37698. var data = this.getVerticesData(kind);
  37699. if (data instanceof Float32Array) {
  37700. vertexData.set(new Float32Array(data), kind);
  37701. }
  37702. else {
  37703. vertexData.set(data.slice(0), kind);
  37704. }
  37705. if (!stopChecking) {
  37706. updatable = this.getVertexBuffer(kind).isUpdatable();
  37707. stopChecking = !updatable;
  37708. }
  37709. }
  37710. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  37711. geometry.delayLoadState = this.delayLoadState;
  37712. geometry.delayLoadingFile = this.delayLoadingFile;
  37713. geometry._delayLoadingFunction = this._delayLoadingFunction;
  37714. for (kind in this._delayInfo) {
  37715. geometry._delayInfo = geometry._delayInfo || [];
  37716. geometry._delayInfo.push(kind);
  37717. }
  37718. // Bounding info
  37719. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  37720. return geometry;
  37721. };
  37722. Geometry.prototype.serialize = function () {
  37723. var serializationObject = {};
  37724. serializationObject.id = this.id;
  37725. if (BABYLON.Tags.HasTags(this)) {
  37726. serializationObject.tags = BABYLON.Tags.GetTags(this);
  37727. }
  37728. return serializationObject;
  37729. };
  37730. Geometry.prototype.serializeVerticeData = function () {
  37731. var serializationObject = this.serialize();
  37732. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37733. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37734. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  37735. serializationObject.positions._updatable = true;
  37736. }
  37737. }
  37738. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37739. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37740. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  37741. serializationObject.normals._updatable = true;
  37742. }
  37743. }
  37744. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37745. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37746. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  37747. serializationObject.uvs._updatable = true;
  37748. }
  37749. }
  37750. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37751. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  37752. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  37753. serializationObject.uv2s._updatable = true;
  37754. }
  37755. }
  37756. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37757. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  37758. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  37759. serializationObject.uv3s._updatable = true;
  37760. }
  37761. }
  37762. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37763. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  37764. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  37765. serializationObject.uv4s._updatable = true;
  37766. }
  37767. }
  37768. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37769. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  37770. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  37771. serializationObject.uv5s._updatable = true;
  37772. }
  37773. }
  37774. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37775. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  37776. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  37777. serializationObject.uv6s._updatable = true;
  37778. }
  37779. }
  37780. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37781. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  37782. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  37783. serializationObject.colors._updatable = true;
  37784. }
  37785. }
  37786. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37787. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  37788. serializationObject.matricesIndices._isExpanded = true;
  37789. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  37790. serializationObject.matricesIndices._updatable = true;
  37791. }
  37792. }
  37793. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37794. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  37795. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  37796. serializationObject.matricesWeights._updatable = true;
  37797. }
  37798. }
  37799. serializationObject.indices = this.getIndices();
  37800. return serializationObject;
  37801. };
  37802. // Statics
  37803. Geometry.ExtractFromMesh = function (mesh, id) {
  37804. var geometry = mesh._geometry;
  37805. if (!geometry) {
  37806. return null;
  37807. }
  37808. return geometry.copy(id);
  37809. };
  37810. /**
  37811. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  37812. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  37813. * Be aware Math.random() could cause collisions, but:
  37814. * "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"
  37815. */
  37816. Geometry.RandomId = function () {
  37817. return BABYLON.Tools.RandomId();
  37818. };
  37819. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  37820. var scene = mesh.getScene();
  37821. // Geometry
  37822. var geometryId = parsedGeometry.geometryId;
  37823. if (geometryId) {
  37824. var geometry = scene.getGeometryByID(geometryId);
  37825. if (geometry) {
  37826. geometry.applyToMesh(mesh);
  37827. }
  37828. }
  37829. else if (parsedGeometry instanceof ArrayBuffer) {
  37830. var binaryInfo = mesh._binaryInfo;
  37831. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  37832. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  37833. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  37834. }
  37835. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  37836. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  37837. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  37838. }
  37839. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  37840. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  37841. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  37842. }
  37843. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  37844. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  37845. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  37846. }
  37847. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  37848. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  37849. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  37850. }
  37851. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  37852. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  37853. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  37854. }
  37855. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  37856. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  37857. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  37858. }
  37859. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  37860. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  37861. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  37862. }
  37863. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  37864. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  37865. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  37866. }
  37867. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  37868. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  37869. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  37870. }
  37871. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  37872. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  37873. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  37874. }
  37875. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  37876. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  37877. mesh.setIndices(indicesData);
  37878. }
  37879. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  37880. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  37881. mesh.subMeshes = [];
  37882. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  37883. var materialIndex = subMeshesData[(i * 5) + 0];
  37884. var verticesStart = subMeshesData[(i * 5) + 1];
  37885. var verticesCount = subMeshesData[(i * 5) + 2];
  37886. var indexStart = subMeshesData[(i * 5) + 3];
  37887. var indexCount = subMeshesData[(i * 5) + 4];
  37888. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  37889. }
  37890. }
  37891. }
  37892. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  37893. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  37894. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  37895. if (parsedGeometry.uvs) {
  37896. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  37897. }
  37898. if (parsedGeometry.uvs2) {
  37899. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  37900. }
  37901. if (parsedGeometry.uvs3) {
  37902. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  37903. }
  37904. if (parsedGeometry.uvs4) {
  37905. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  37906. }
  37907. if (parsedGeometry.uvs5) {
  37908. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  37909. }
  37910. if (parsedGeometry.uvs6) {
  37911. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  37912. }
  37913. if (parsedGeometry.colors) {
  37914. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  37915. }
  37916. if (parsedGeometry.matricesIndices) {
  37917. if (!parsedGeometry.matricesIndices._isExpanded) {
  37918. var floatIndices = [];
  37919. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  37920. var matricesIndex = parsedGeometry.matricesIndices[i];
  37921. floatIndices.push(matricesIndex & 0x000000FF);
  37922. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  37923. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  37924. floatIndices.push(matricesIndex >> 24);
  37925. }
  37926. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  37927. }
  37928. else {
  37929. delete parsedGeometry.matricesIndices._isExpanded;
  37930. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  37931. }
  37932. }
  37933. if (parsedGeometry.matricesIndicesExtra) {
  37934. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  37935. var floatIndices = [];
  37936. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  37937. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  37938. floatIndices.push(matricesIndex & 0x000000FF);
  37939. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  37940. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  37941. floatIndices.push(matricesIndex >> 24);
  37942. }
  37943. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  37944. }
  37945. else {
  37946. delete parsedGeometry.matricesIndices._isExpanded;
  37947. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  37948. }
  37949. }
  37950. if (parsedGeometry.matricesWeights) {
  37951. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  37952. }
  37953. if (parsedGeometry.matricesWeightsExtra) {
  37954. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  37955. }
  37956. mesh.setIndices(parsedGeometry.indices);
  37957. }
  37958. // SubMeshes
  37959. if (parsedGeometry.subMeshes) {
  37960. mesh.subMeshes = [];
  37961. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  37962. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  37963. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  37964. }
  37965. }
  37966. // Flat shading
  37967. if (mesh._shouldGenerateFlatShading) {
  37968. mesh.convertToFlatShadedMesh();
  37969. delete mesh._shouldGenerateFlatShading;
  37970. }
  37971. // Update
  37972. mesh.computeWorldMatrix(true);
  37973. // Octree
  37974. if (scene['_selectionOctree']) {
  37975. scene['_selectionOctree'].addMesh(mesh);
  37976. }
  37977. };
  37978. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  37979. if (scene.getGeometryByID(parsedVertexData.id)) {
  37980. return null; // null since geometry could be something else than a box...
  37981. }
  37982. var geometry = new Geometry(parsedVertexData.id, scene);
  37983. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  37984. if (parsedVertexData.delayLoadingFile) {
  37985. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  37986. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  37987. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  37988. geometry._delayInfo = [];
  37989. if (parsedVertexData.hasUVs) {
  37990. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  37991. }
  37992. if (parsedVertexData.hasUVs2) {
  37993. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  37994. }
  37995. if (parsedVertexData.hasUVs3) {
  37996. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  37997. }
  37998. if (parsedVertexData.hasUVs4) {
  37999. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  38000. }
  38001. if (parsedVertexData.hasUVs5) {
  38002. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  38003. }
  38004. if (parsedVertexData.hasUVs6) {
  38005. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  38006. }
  38007. if (parsedVertexData.hasColors) {
  38008. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  38009. }
  38010. if (parsedVertexData.hasMatricesIndices) {
  38011. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38012. }
  38013. if (parsedVertexData.hasMatricesWeights) {
  38014. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38015. }
  38016. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  38017. }
  38018. else {
  38019. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  38020. }
  38021. scene.pushGeometry(geometry, true);
  38022. return geometry;
  38023. };
  38024. return Geometry;
  38025. }());
  38026. BABYLON.Geometry = Geometry;
  38027. /////// Primitives //////////////////////////////////////////////
  38028. (function (Geometry) {
  38029. var Primitives;
  38030. (function (Primitives) {
  38031. /// Abstract class
  38032. var _Primitive = (function (_super) {
  38033. __extends(_Primitive, _super);
  38034. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  38035. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  38036. _this._canBeRegenerated = _canBeRegenerated;
  38037. _this._beingRegenerated = true;
  38038. _this.regenerate();
  38039. _this._beingRegenerated = false;
  38040. return _this;
  38041. }
  38042. _Primitive.prototype.canBeRegenerated = function () {
  38043. return this._canBeRegenerated;
  38044. };
  38045. _Primitive.prototype.regenerate = function () {
  38046. if (!this._canBeRegenerated) {
  38047. return;
  38048. }
  38049. this._beingRegenerated = true;
  38050. this.setAllVerticesData(this._regenerateVertexData(), false);
  38051. this._beingRegenerated = false;
  38052. };
  38053. _Primitive.prototype.asNewGeometry = function (id) {
  38054. return _super.prototype.copy.call(this, id);
  38055. };
  38056. // overrides
  38057. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  38058. if (!this._beingRegenerated) {
  38059. return;
  38060. }
  38061. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  38062. };
  38063. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  38064. if (!this._beingRegenerated) {
  38065. return;
  38066. }
  38067. _super.prototype.setVerticesData.call(this, kind, data, false);
  38068. };
  38069. // to override
  38070. // protected
  38071. _Primitive.prototype._regenerateVertexData = function () {
  38072. throw new Error("Abstract method");
  38073. };
  38074. _Primitive.prototype.copy = function (id) {
  38075. throw new Error("Must be overriden in sub-classes.");
  38076. };
  38077. _Primitive.prototype.serialize = function () {
  38078. var serializationObject = _super.prototype.serialize.call(this);
  38079. serializationObject.canBeRegenerated = this.canBeRegenerated();
  38080. return serializationObject;
  38081. };
  38082. return _Primitive;
  38083. }(Geometry));
  38084. Primitives._Primitive = _Primitive;
  38085. var Ribbon = (function (_super) {
  38086. __extends(Ribbon, _super);
  38087. // Members
  38088. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  38089. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38090. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38091. _this.pathArray = pathArray;
  38092. _this.closeArray = closeArray;
  38093. _this.closePath = closePath;
  38094. _this.offset = offset;
  38095. _this.side = side;
  38096. return _this;
  38097. }
  38098. Ribbon.prototype._regenerateVertexData = function () {
  38099. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  38100. };
  38101. Ribbon.prototype.copy = function (id) {
  38102. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  38103. };
  38104. return Ribbon;
  38105. }(_Primitive));
  38106. Primitives.Ribbon = Ribbon;
  38107. var Box = (function (_super) {
  38108. __extends(Box, _super);
  38109. // Members
  38110. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  38111. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38112. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38113. _this.size = size;
  38114. _this.side = side;
  38115. return _this;
  38116. }
  38117. Box.prototype._regenerateVertexData = function () {
  38118. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  38119. };
  38120. Box.prototype.copy = function (id) {
  38121. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  38122. };
  38123. Box.prototype.serialize = function () {
  38124. var serializationObject = _super.prototype.serialize.call(this);
  38125. serializationObject.size = this.size;
  38126. return serializationObject;
  38127. };
  38128. Box.Parse = function (parsedBox, scene) {
  38129. if (scene.getGeometryByID(parsedBox.id)) {
  38130. return null; // null since geometry could be something else than a box...
  38131. }
  38132. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  38133. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  38134. scene.pushGeometry(box, true);
  38135. return box;
  38136. };
  38137. return Box;
  38138. }(_Primitive));
  38139. Primitives.Box = Box;
  38140. var Sphere = (function (_super) {
  38141. __extends(Sphere, _super);
  38142. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  38143. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38144. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38145. _this.segments = segments;
  38146. _this.diameter = diameter;
  38147. _this.side = side;
  38148. return _this;
  38149. }
  38150. Sphere.prototype._regenerateVertexData = function () {
  38151. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  38152. };
  38153. Sphere.prototype.copy = function (id) {
  38154. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  38155. };
  38156. Sphere.prototype.serialize = function () {
  38157. var serializationObject = _super.prototype.serialize.call(this);
  38158. serializationObject.segments = this.segments;
  38159. serializationObject.diameter = this.diameter;
  38160. return serializationObject;
  38161. };
  38162. Sphere.Parse = function (parsedSphere, scene) {
  38163. if (scene.getGeometryByID(parsedSphere.id)) {
  38164. return null; // null since geometry could be something else than a sphere...
  38165. }
  38166. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  38167. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  38168. scene.pushGeometry(sphere, true);
  38169. return sphere;
  38170. };
  38171. return Sphere;
  38172. }(_Primitive));
  38173. Primitives.Sphere = Sphere;
  38174. var Disc = (function (_super) {
  38175. __extends(Disc, _super);
  38176. // Members
  38177. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  38178. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38179. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38180. _this.radius = radius;
  38181. _this.tessellation = tessellation;
  38182. _this.side = side;
  38183. return _this;
  38184. }
  38185. Disc.prototype._regenerateVertexData = function () {
  38186. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  38187. };
  38188. Disc.prototype.copy = function (id) {
  38189. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  38190. };
  38191. return Disc;
  38192. }(_Primitive));
  38193. Primitives.Disc = Disc;
  38194. var Cylinder = (function (_super) {
  38195. __extends(Cylinder, _super);
  38196. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  38197. if (subdivisions === void 0) { subdivisions = 1; }
  38198. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38199. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38200. _this.height = height;
  38201. _this.diameterTop = diameterTop;
  38202. _this.diameterBottom = diameterBottom;
  38203. _this.tessellation = tessellation;
  38204. _this.subdivisions = subdivisions;
  38205. _this.side = side;
  38206. return _this;
  38207. }
  38208. Cylinder.prototype._regenerateVertexData = function () {
  38209. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  38210. };
  38211. Cylinder.prototype.copy = function (id) {
  38212. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  38213. };
  38214. Cylinder.prototype.serialize = function () {
  38215. var serializationObject = _super.prototype.serialize.call(this);
  38216. serializationObject.height = this.height;
  38217. serializationObject.diameterTop = this.diameterTop;
  38218. serializationObject.diameterBottom = this.diameterBottom;
  38219. serializationObject.tessellation = this.tessellation;
  38220. return serializationObject;
  38221. };
  38222. Cylinder.Parse = function (parsedCylinder, scene) {
  38223. if (scene.getGeometryByID(parsedCylinder.id)) {
  38224. return null; // null since geometry could be something else than a cylinder...
  38225. }
  38226. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  38227. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  38228. scene.pushGeometry(cylinder, true);
  38229. return cylinder;
  38230. };
  38231. return Cylinder;
  38232. }(_Primitive));
  38233. Primitives.Cylinder = Cylinder;
  38234. var Torus = (function (_super) {
  38235. __extends(Torus, _super);
  38236. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  38237. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38238. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38239. _this.diameter = diameter;
  38240. _this.thickness = thickness;
  38241. _this.tessellation = tessellation;
  38242. _this.side = side;
  38243. return _this;
  38244. }
  38245. Torus.prototype._regenerateVertexData = function () {
  38246. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  38247. };
  38248. Torus.prototype.copy = function (id) {
  38249. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  38250. };
  38251. Torus.prototype.serialize = function () {
  38252. var serializationObject = _super.prototype.serialize.call(this);
  38253. serializationObject.diameter = this.diameter;
  38254. serializationObject.thickness = this.thickness;
  38255. serializationObject.tessellation = this.tessellation;
  38256. return serializationObject;
  38257. };
  38258. Torus.Parse = function (parsedTorus, scene) {
  38259. if (scene.getGeometryByID(parsedTorus.id)) {
  38260. return null; // null since geometry could be something else than a torus...
  38261. }
  38262. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  38263. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  38264. scene.pushGeometry(torus, true);
  38265. return torus;
  38266. };
  38267. return Torus;
  38268. }(_Primitive));
  38269. Primitives.Torus = Torus;
  38270. var Ground = (function (_super) {
  38271. __extends(Ground, _super);
  38272. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  38273. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38274. _this.width = width;
  38275. _this.height = height;
  38276. _this.subdivisions = subdivisions;
  38277. return _this;
  38278. }
  38279. Ground.prototype._regenerateVertexData = function () {
  38280. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  38281. };
  38282. Ground.prototype.copy = function (id) {
  38283. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  38284. };
  38285. Ground.prototype.serialize = function () {
  38286. var serializationObject = _super.prototype.serialize.call(this);
  38287. serializationObject.width = this.width;
  38288. serializationObject.height = this.height;
  38289. serializationObject.subdivisions = this.subdivisions;
  38290. return serializationObject;
  38291. };
  38292. Ground.Parse = function (parsedGround, scene) {
  38293. if (scene.getGeometryByID(parsedGround.id)) {
  38294. return null; // null since geometry could be something else than a ground...
  38295. }
  38296. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  38297. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  38298. scene.pushGeometry(ground, true);
  38299. return ground;
  38300. };
  38301. return Ground;
  38302. }(_Primitive));
  38303. Primitives.Ground = Ground;
  38304. var TiledGround = (function (_super) {
  38305. __extends(TiledGround, _super);
  38306. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  38307. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38308. _this.xmin = xmin;
  38309. _this.zmin = zmin;
  38310. _this.xmax = xmax;
  38311. _this.zmax = zmax;
  38312. _this.subdivisions = subdivisions;
  38313. _this.precision = precision;
  38314. return _this;
  38315. }
  38316. TiledGround.prototype._regenerateVertexData = function () {
  38317. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  38318. };
  38319. TiledGround.prototype.copy = function (id) {
  38320. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  38321. };
  38322. return TiledGround;
  38323. }(_Primitive));
  38324. Primitives.TiledGround = TiledGround;
  38325. var Plane = (function (_super) {
  38326. __extends(Plane, _super);
  38327. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  38328. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38329. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38330. _this.size = size;
  38331. _this.side = side;
  38332. return _this;
  38333. }
  38334. Plane.prototype._regenerateVertexData = function () {
  38335. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  38336. };
  38337. Plane.prototype.copy = function (id) {
  38338. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  38339. };
  38340. Plane.prototype.serialize = function () {
  38341. var serializationObject = _super.prototype.serialize.call(this);
  38342. serializationObject.size = this.size;
  38343. return serializationObject;
  38344. };
  38345. Plane.Parse = function (parsedPlane, scene) {
  38346. if (scene.getGeometryByID(parsedPlane.id)) {
  38347. return null; // null since geometry could be something else than a ground...
  38348. }
  38349. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  38350. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  38351. scene.pushGeometry(plane, true);
  38352. return plane;
  38353. };
  38354. return Plane;
  38355. }(_Primitive));
  38356. Primitives.Plane = Plane;
  38357. var TorusKnot = (function (_super) {
  38358. __extends(TorusKnot, _super);
  38359. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  38360. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  38361. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  38362. _this.radius = radius;
  38363. _this.tube = tube;
  38364. _this.radialSegments = radialSegments;
  38365. _this.tubularSegments = tubularSegments;
  38366. _this.p = p;
  38367. _this.q = q;
  38368. _this.side = side;
  38369. return _this;
  38370. }
  38371. TorusKnot.prototype._regenerateVertexData = function () {
  38372. 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 });
  38373. };
  38374. TorusKnot.prototype.copy = function (id) {
  38375. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  38376. };
  38377. TorusKnot.prototype.serialize = function () {
  38378. var serializationObject = _super.prototype.serialize.call(this);
  38379. serializationObject.radius = this.radius;
  38380. serializationObject.tube = this.tube;
  38381. serializationObject.radialSegments = this.radialSegments;
  38382. serializationObject.tubularSegments = this.tubularSegments;
  38383. serializationObject.p = this.p;
  38384. serializationObject.q = this.q;
  38385. return serializationObject;
  38386. };
  38387. ;
  38388. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  38389. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  38390. return null; // null since geometry could be something else than a ground...
  38391. }
  38392. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  38393. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  38394. scene.pushGeometry(torusKnot, true);
  38395. return torusKnot;
  38396. };
  38397. return TorusKnot;
  38398. }(_Primitive));
  38399. Primitives.TorusKnot = TorusKnot;
  38400. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  38401. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  38402. })(BABYLON || (BABYLON = {}));
  38403. //# sourceMappingURL=babylon.geometry.js.map
  38404. var BABYLON;
  38405. (function (BABYLON) {
  38406. var GroundMesh = (function (_super) {
  38407. __extends(GroundMesh, _super);
  38408. function GroundMesh(name, scene) {
  38409. var _this = _super.call(this, name, scene) || this;
  38410. _this.generateOctree = false;
  38411. _this._worldInverse = new BABYLON.Matrix();
  38412. return _this;
  38413. }
  38414. GroundMesh.prototype.getClassName = function () {
  38415. return "GroundMesh";
  38416. };
  38417. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  38418. get: function () {
  38419. return Math.min(this._subdivisionsX, this._subdivisionsY);
  38420. },
  38421. enumerable: true,
  38422. configurable: true
  38423. });
  38424. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  38425. get: function () {
  38426. return this._subdivisionsX;
  38427. },
  38428. enumerable: true,
  38429. configurable: true
  38430. });
  38431. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  38432. get: function () {
  38433. return this._subdivisionsY;
  38434. },
  38435. enumerable: true,
  38436. configurable: true
  38437. });
  38438. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  38439. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  38440. this._subdivisionsX = chunksCount;
  38441. this._subdivisionsY = chunksCount;
  38442. this.subdivide(chunksCount);
  38443. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  38444. };
  38445. /**
  38446. * Returns a height (y) value in the Worl system :
  38447. * the ground altitude at the coordinates (x, z) expressed in the World system.
  38448. * Returns the ground y position if (x, z) are outside the ground surface.
  38449. */
  38450. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  38451. var world = this.getWorldMatrix();
  38452. var invMat = BABYLON.Tmp.Matrix[5];
  38453. world.invertToRef(invMat);
  38454. var tmpVect = BABYLON.Tmp.Vector3[8];
  38455. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  38456. x = tmpVect.x;
  38457. z = tmpVect.z;
  38458. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  38459. return this.position.y;
  38460. }
  38461. if (!this._heightQuads || this._heightQuads.length == 0) {
  38462. this._initHeightQuads();
  38463. this._computeHeightQuads();
  38464. }
  38465. var facet = this._getFacetAt(x, z);
  38466. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  38467. // return y in the World system
  38468. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  38469. return tmpVect.y;
  38470. };
  38471. /**
  38472. * Returns a normalized vector (Vector3) orthogonal to the ground
  38473. * at the ground coordinates (x, z) expressed in the World system.
  38474. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  38475. */
  38476. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  38477. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  38478. this.getNormalAtCoordinatesToRef(x, z, normal);
  38479. return normal;
  38480. };
  38481. /**
  38482. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  38483. * at the ground coordinates (x, z) expressed in the World system.
  38484. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  38485. * Returns the GroundMesh.
  38486. */
  38487. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  38488. var world = this.getWorldMatrix();
  38489. var tmpMat = BABYLON.Tmp.Matrix[5];
  38490. world.invertToRef(tmpMat);
  38491. var tmpVect = BABYLON.Tmp.Vector3[8];
  38492. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  38493. x = tmpVect.x;
  38494. z = tmpVect.z;
  38495. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  38496. return this;
  38497. }
  38498. if (!this._heightQuads || this._heightQuads.length == 0) {
  38499. this._initHeightQuads();
  38500. this._computeHeightQuads();
  38501. }
  38502. var facet = this._getFacetAt(x, z);
  38503. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  38504. return this;
  38505. };
  38506. /**
  38507. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  38508. * if the ground has been updated.
  38509. * This can be used in the render loop
  38510. */
  38511. GroundMesh.prototype.updateCoordinateHeights = function () {
  38512. if (!this._heightQuads || this._heightQuads.length == 0) {
  38513. this._initHeightQuads();
  38514. }
  38515. this._computeHeightQuads();
  38516. };
  38517. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  38518. GroundMesh.prototype._getFacetAt = function (x, z) {
  38519. // retrieve col and row from x, z coordinates in the ground local system
  38520. var subdivisionsX = this._subdivisionsX;
  38521. var subdivisionsY = this._subdivisionsY;
  38522. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  38523. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  38524. var quad = this._heightQuads[row * this._subdivisionsX + col];
  38525. var facet;
  38526. if (z < quad.slope.x * x + quad.slope.y) {
  38527. facet = quad.facet1;
  38528. }
  38529. else {
  38530. facet = quad.facet2;
  38531. }
  38532. return facet;
  38533. };
  38534. // Creates and populates the heightMap array with "facet" elements :
  38535. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  38536. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  38537. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  38538. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  38539. GroundMesh.prototype._initHeightQuads = function () {
  38540. var subdivisionsX = this._subdivisionsX;
  38541. var subdivisionsY = this._subdivisionsY;
  38542. this._heightQuads = new Array();
  38543. for (var row = 0; row < subdivisionsY; row++) {
  38544. for (var col = 0; col < subdivisionsX; col++) {
  38545. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
  38546. this._heightQuads[row * subdivisionsX + col] = quad;
  38547. }
  38548. }
  38549. };
  38550. // Compute each quad element values and update the the heightMap array :
  38551. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  38552. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  38553. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  38554. GroundMesh.prototype._computeHeightQuads = function () {
  38555. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38556. var v1 = BABYLON.Tmp.Vector3[3];
  38557. var v2 = BABYLON.Tmp.Vector3[2];
  38558. var v3 = BABYLON.Tmp.Vector3[1];
  38559. var v4 = BABYLON.Tmp.Vector3[0];
  38560. var v1v2 = BABYLON.Tmp.Vector3[4];
  38561. var v1v3 = BABYLON.Tmp.Vector3[5];
  38562. var v1v4 = BABYLON.Tmp.Vector3[6];
  38563. var norm1 = BABYLON.Tmp.Vector3[7];
  38564. var norm2 = BABYLON.Tmp.Vector3[8];
  38565. var i = 0;
  38566. var j = 0;
  38567. var k = 0;
  38568. var cd = 0; // 2D slope coefficient : z = cd * x + h
  38569. var h = 0;
  38570. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  38571. var d2 = 0;
  38572. var subdivisionsX = this._subdivisionsX;
  38573. var subdivisionsY = this._subdivisionsY;
  38574. for (var row = 0; row < subdivisionsY; row++) {
  38575. for (var col = 0; col < subdivisionsX; col++) {
  38576. i = col * 3;
  38577. j = row * (subdivisionsX + 1) * 3;
  38578. k = (row + 1) * (subdivisionsX + 1) * 3;
  38579. v1.x = positions[j + i];
  38580. v1.y = positions[j + i + 1];
  38581. v1.z = positions[j + i + 2];
  38582. v2.x = positions[j + i + 3];
  38583. v2.y = positions[j + i + 4];
  38584. v2.z = positions[j + i + 5];
  38585. v3.x = positions[k + i];
  38586. v3.y = positions[k + i + 1];
  38587. v3.z = positions[k + i + 2];
  38588. v4.x = positions[k + i + 3];
  38589. v4.y = positions[k + i + 4];
  38590. v4.z = positions[k + i + 5];
  38591. // 2D slope V1V4
  38592. cd = (v4.z - v1.z) / (v4.x - v1.x);
  38593. h = v1.z - cd * v1.x; // v1 belongs to the slope
  38594. // facet equations :
  38595. // we compute each facet normal vector
  38596. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  38597. // we compute the value d by applying the equation to v1 which belongs to the plane
  38598. // then we store the facet equation in a Vector4
  38599. v2.subtractToRef(v1, v1v2);
  38600. v3.subtractToRef(v1, v1v3);
  38601. v4.subtractToRef(v1, v1v4);
  38602. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  38603. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  38604. norm1.normalize();
  38605. norm2.normalize();
  38606. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  38607. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  38608. var quad = this._heightQuads[row * subdivisionsX + col];
  38609. quad.slope.copyFromFloats(cd, h);
  38610. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  38611. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  38612. }
  38613. }
  38614. };
  38615. return GroundMesh;
  38616. }(BABYLON.Mesh));
  38617. BABYLON.GroundMesh = GroundMesh;
  38618. })(BABYLON || (BABYLON = {}));
  38619. //# sourceMappingURL=babylon.groundMesh.js.map
  38620. var BABYLON;
  38621. (function (BABYLON) {
  38622. var LinesMesh = (function (_super) {
  38623. __extends(LinesMesh, _super);
  38624. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  38625. if (parent === void 0) { parent = null; }
  38626. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  38627. _this.color = new BABYLON.Color3(1, 1, 1);
  38628. _this.alpha = 1;
  38629. _this._positionBuffer = {};
  38630. if (source) {
  38631. _this.color = source.color.clone();
  38632. _this.alpha = source.alpha;
  38633. }
  38634. _this._intersectionThreshold = 0.1;
  38635. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  38636. attributes: [BABYLON.VertexBuffer.PositionKind],
  38637. uniforms: ["worldViewProjection", "color"],
  38638. needAlphaBlending: true
  38639. });
  38640. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  38641. return _this;
  38642. }
  38643. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  38644. /**
  38645. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38646. * This margin is expressed in world space coordinates, so its value may vary.
  38647. * Default value is 0.1
  38648. * @returns the intersection Threshold value.
  38649. */
  38650. get: function () {
  38651. return this._intersectionThreshold;
  38652. },
  38653. /**
  38654. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  38655. * This margin is expressed in world space coordinates, so its value may vary.
  38656. * @param value the new threshold to apply
  38657. */
  38658. set: function (value) {
  38659. if (this._intersectionThreshold === value) {
  38660. return;
  38661. }
  38662. this._intersectionThreshold = value;
  38663. if (this.geometry) {
  38664. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  38665. }
  38666. },
  38667. enumerable: true,
  38668. configurable: true
  38669. });
  38670. LinesMesh.prototype.getClassName = function () {
  38671. return "LinesMesh";
  38672. };
  38673. Object.defineProperty(LinesMesh.prototype, "material", {
  38674. get: function () {
  38675. return this._colorShader;
  38676. },
  38677. enumerable: true,
  38678. configurable: true
  38679. });
  38680. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  38681. get: function () {
  38682. return false;
  38683. },
  38684. enumerable: true,
  38685. configurable: true
  38686. });
  38687. LinesMesh.prototype.createInstance = function (name) {
  38688. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  38689. return null;
  38690. };
  38691. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  38692. var engine = this.getScene().getEngine();
  38693. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  38694. // VBOs
  38695. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  38696. // Color
  38697. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  38698. };
  38699. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  38700. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  38701. return;
  38702. }
  38703. var engine = this.getScene().getEngine();
  38704. // Draw order
  38705. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  38706. };
  38707. LinesMesh.prototype.dispose = function (doNotRecurse) {
  38708. this._colorShader.dispose();
  38709. _super.prototype.dispose.call(this, doNotRecurse);
  38710. };
  38711. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  38712. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  38713. };
  38714. return LinesMesh;
  38715. }(BABYLON.Mesh));
  38716. BABYLON.LinesMesh = LinesMesh;
  38717. })(BABYLON || (BABYLON = {}));
  38718. //# sourceMappingURL=babylon.linesMesh.js.map
  38719. var BABYLON;
  38720. (function (BABYLON) {
  38721. var DefaultLoadingScreen = (function () {
  38722. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  38723. if (_loadingText === void 0) { _loadingText = ""; }
  38724. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  38725. var _this = this;
  38726. this._renderingCanvas = _renderingCanvas;
  38727. this._loadingText = _loadingText;
  38728. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  38729. // Resize
  38730. this._resizeLoadingUI = function () {
  38731. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  38732. _this._loadingDiv.style.position = "absolute";
  38733. _this._loadingDiv.style.left = canvasRect.left + "px";
  38734. _this._loadingDiv.style.top = canvasRect.top + "px";
  38735. _this._loadingDiv.style.width = canvasRect.width + "px";
  38736. _this._loadingDiv.style.height = canvasRect.height + "px";
  38737. };
  38738. }
  38739. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  38740. var _this = this;
  38741. if (this._loadingDiv) {
  38742. // Do not add a loading screen if there is already one
  38743. return;
  38744. }
  38745. this._loadingDiv = document.createElement("div");
  38746. this._loadingDiv.id = "babylonjsLoadingDiv";
  38747. this._loadingDiv.style.opacity = "0";
  38748. this._loadingDiv.style.transition = "opacity 1.5s ease";
  38749. // Loading text
  38750. this._loadingTextDiv = document.createElement("div");
  38751. this._loadingTextDiv.style.position = "absolute";
  38752. this._loadingTextDiv.style.left = "0";
  38753. this._loadingTextDiv.style.top = "50%";
  38754. this._loadingTextDiv.style.marginTop = "80px";
  38755. this._loadingTextDiv.style.width = "100%";
  38756. this._loadingTextDiv.style.height = "20px";
  38757. this._loadingTextDiv.style.fontFamily = "Arial";
  38758. this._loadingTextDiv.style.fontSize = "14px";
  38759. this._loadingTextDiv.style.color = "white";
  38760. this._loadingTextDiv.style.textAlign = "center";
  38761. this._loadingTextDiv.innerHTML = "Loading";
  38762. this._loadingDiv.appendChild(this._loadingTextDiv);
  38763. //set the predefined text
  38764. this._loadingTextDiv.innerHTML = this._loadingText;
  38765. // Loading img
  38766. var imgBack = new Image();
  38767. 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==";
  38768. imgBack.style.position = "absolute";
  38769. imgBack.style.left = "50%";
  38770. imgBack.style.top = "50%";
  38771. imgBack.style.marginLeft = "-50px";
  38772. imgBack.style.marginTop = "-50px";
  38773. imgBack.style.transition = "transform 1.0s ease";
  38774. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  38775. var deg = 360;
  38776. var onTransitionEnd = function () {
  38777. deg += 360;
  38778. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  38779. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  38780. };
  38781. imgBack.addEventListener("transitionend", onTransitionEnd);
  38782. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  38783. this._loadingDiv.appendChild(imgBack);
  38784. // front image
  38785. var imgFront = new Image();
  38786. 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=";
  38787. imgFront.style.position = "absolute";
  38788. imgFront.style.left = "50%";
  38789. imgFront.style.top = "50%";
  38790. imgFront.style.marginLeft = "-50px";
  38791. imgFront.style.marginTop = "-50px";
  38792. this._loadingDiv.appendChild(imgFront);
  38793. this._resizeLoadingUI();
  38794. window.addEventListener("resize", this._resizeLoadingUI);
  38795. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  38796. document.body.appendChild(this._loadingDiv);
  38797. setTimeout(function () {
  38798. _this._loadingDiv.style.opacity = "1";
  38799. imgBack.style.transform = "rotateZ(360deg)";
  38800. imgBack.style.webkitTransform = "rotateZ(360deg)";
  38801. }, 0);
  38802. };
  38803. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  38804. var _this = this;
  38805. if (!this._loadingDiv) {
  38806. return;
  38807. }
  38808. var onTransitionEnd = function () {
  38809. if (!_this._loadingDiv) {
  38810. return;
  38811. }
  38812. document.body.removeChild(_this._loadingDiv);
  38813. window.removeEventListener("resize", _this._resizeLoadingUI);
  38814. _this._loadingDiv = null;
  38815. };
  38816. this._loadingDiv.style.opacity = "0";
  38817. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  38818. };
  38819. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  38820. set: function (text) {
  38821. this._loadingText = text;
  38822. if (this._loadingTextDiv) {
  38823. this._loadingTextDiv.innerHTML = this._loadingText;
  38824. }
  38825. },
  38826. enumerable: true,
  38827. configurable: true
  38828. });
  38829. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  38830. get: function () {
  38831. return this._loadingDivBackgroundColor;
  38832. },
  38833. set: function (color) {
  38834. this._loadingDivBackgroundColor = color;
  38835. if (!this._loadingDiv) {
  38836. return;
  38837. }
  38838. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  38839. },
  38840. enumerable: true,
  38841. configurable: true
  38842. });
  38843. return DefaultLoadingScreen;
  38844. }());
  38845. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  38846. })(BABYLON || (BABYLON = {}));
  38847. //# sourceMappingURL=babylon.loadingScreen.js.map
  38848. var BABYLON;
  38849. (function (BABYLON) {
  38850. var AudioEngine = (function () {
  38851. function AudioEngine() {
  38852. this._audioContext = null;
  38853. this._audioContextInitialized = false;
  38854. this.canUseWebAudio = false;
  38855. this.WarnedWebAudioUnsupported = false;
  38856. this.unlocked = false;
  38857. this.isMP3supported = false;
  38858. this.isOGGsupported = false;
  38859. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  38860. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  38861. this.canUseWebAudio = true;
  38862. }
  38863. var audioElem = document.createElement('audio');
  38864. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  38865. this.isMP3supported = true;
  38866. }
  38867. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  38868. this.isOGGsupported = true;
  38869. }
  38870. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  38871. this._unlockiOSaudio();
  38872. }
  38873. else {
  38874. this.unlocked = true;
  38875. }
  38876. }
  38877. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  38878. get: function () {
  38879. if (!this._audioContextInitialized) {
  38880. this._initializeAudioContext();
  38881. }
  38882. return this._audioContext;
  38883. },
  38884. enumerable: true,
  38885. configurable: true
  38886. });
  38887. AudioEngine.prototype._unlockiOSaudio = function () {
  38888. var _this = this;
  38889. var unlockaudio = function () {
  38890. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  38891. var source = _this.audioContext.createBufferSource();
  38892. source.buffer = buffer;
  38893. source.connect(_this.audioContext.destination);
  38894. source.start(0);
  38895. setTimeout(function () {
  38896. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  38897. _this.unlocked = true;
  38898. window.removeEventListener('touchend', unlockaudio, false);
  38899. if (_this.onAudioUnlocked) {
  38900. _this.onAudioUnlocked();
  38901. }
  38902. }
  38903. }, 0);
  38904. };
  38905. window.addEventListener('touchend', unlockaudio, false);
  38906. };
  38907. AudioEngine.prototype._initializeAudioContext = function () {
  38908. try {
  38909. if (this.canUseWebAudio) {
  38910. this._audioContext = new AudioContext();
  38911. // create a global volume gain node
  38912. this.masterGain = this._audioContext.createGain();
  38913. this.masterGain.gain.value = 1;
  38914. this.masterGain.connect(this._audioContext.destination);
  38915. this._audioContextInitialized = true;
  38916. }
  38917. }
  38918. catch (e) {
  38919. this.canUseWebAudio = false;
  38920. BABYLON.Tools.Error("Web Audio: " + e.message);
  38921. }
  38922. };
  38923. AudioEngine.prototype.dispose = function () {
  38924. if (this.canUseWebAudio && this._audioContextInitialized) {
  38925. if (this._connectedAnalyser) {
  38926. this._connectedAnalyser.stopDebugCanvas();
  38927. this._connectedAnalyser.dispose();
  38928. this.masterGain.disconnect();
  38929. this.masterGain.connect(this._audioContext.destination);
  38930. this._connectedAnalyser = null;
  38931. }
  38932. this.masterGain.gain.value = 1;
  38933. }
  38934. this.WarnedWebAudioUnsupported = false;
  38935. };
  38936. AudioEngine.prototype.getGlobalVolume = function () {
  38937. if (this.canUseWebAudio && this._audioContextInitialized) {
  38938. return this.masterGain.gain.value;
  38939. }
  38940. else {
  38941. return -1;
  38942. }
  38943. };
  38944. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  38945. if (this.canUseWebAudio && this._audioContextInitialized) {
  38946. this.masterGain.gain.value = newVolume;
  38947. }
  38948. };
  38949. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  38950. if (this._connectedAnalyser) {
  38951. this._connectedAnalyser.stopDebugCanvas();
  38952. }
  38953. if (this.canUseWebAudio && this._audioContextInitialized) {
  38954. this._connectedAnalyser = analyser;
  38955. this.masterGain.disconnect();
  38956. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  38957. }
  38958. };
  38959. return AudioEngine;
  38960. }());
  38961. BABYLON.AudioEngine = AudioEngine;
  38962. })(BABYLON || (BABYLON = {}));
  38963. //# sourceMappingURL=babylon.audioEngine.js.map
  38964. var BABYLON;
  38965. (function (BABYLON) {
  38966. var Sound = (function () {
  38967. /**
  38968. * Create a sound and attach it to a scene
  38969. * @param name Name of your sound
  38970. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  38971. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  38972. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  38973. */
  38974. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  38975. var _this = this;
  38976. this.autoplay = false;
  38977. this.loop = false;
  38978. this.useCustomAttenuation = false;
  38979. this.spatialSound = false;
  38980. this.refDistance = 1;
  38981. this.rolloffFactor = 1;
  38982. this.maxDistance = 100;
  38983. this.distanceModel = "linear";
  38984. this._panningModel = "equalpower";
  38985. this._playbackRate = 1;
  38986. this._streaming = false;
  38987. this._startTime = 0;
  38988. this._startOffset = 0;
  38989. this._position = BABYLON.Vector3.Zero();
  38990. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  38991. this._volume = 1;
  38992. this._isLoaded = false;
  38993. this._isReadyToPlay = false;
  38994. this.isPlaying = false;
  38995. this.isPaused = false;
  38996. this._isDirectional = false;
  38997. // Used if you'd like to create a directional sound.
  38998. // If not set, the sound will be omnidirectional
  38999. this._coneInnerAngle = 360;
  39000. this._coneOuterAngle = 360;
  39001. this._coneOuterGain = 0;
  39002. this._isOutputConnected = false;
  39003. this._urlType = "Unknown";
  39004. this.name = name;
  39005. this._scene = scene;
  39006. this._readyToPlayCallback = readyToPlayCallback;
  39007. // Default custom attenuation function is a linear attenuation
  39008. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  39009. if (currentDistance < maxDistance) {
  39010. return currentVolume * (1 - currentDistance / maxDistance);
  39011. }
  39012. else {
  39013. return 0;
  39014. }
  39015. };
  39016. if (options) {
  39017. this.autoplay = options.autoplay || false;
  39018. this.loop = options.loop || false;
  39019. // if volume === 0, we need another way to check this option
  39020. if (options.volume !== undefined) {
  39021. this._volume = options.volume;
  39022. }
  39023. this.spatialSound = options.spatialSound || false;
  39024. this.maxDistance = options.maxDistance || 100;
  39025. this.useCustomAttenuation = options.useCustomAttenuation || false;
  39026. this.rolloffFactor = options.rolloffFactor || 1;
  39027. this.refDistance = options.refDistance || 1;
  39028. this.distanceModel = options.distanceModel || "linear";
  39029. this._playbackRate = options.playbackRate || 1;
  39030. this._streaming = options.streaming || false;
  39031. }
  39032. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39033. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  39034. this._soundGain.gain.value = this._volume;
  39035. this._inputAudioNode = this._soundGain;
  39036. this._ouputAudioNode = this._soundGain;
  39037. if (this.spatialSound) {
  39038. this._createSpatialParameters();
  39039. }
  39040. this._scene.mainSoundTrack.AddSound(this);
  39041. var validParameter = true;
  39042. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  39043. if (urlOrArrayBuffer) {
  39044. if (typeof (urlOrArrayBuffer) === "string")
  39045. this._urlType = "String";
  39046. if (Array.isArray(urlOrArrayBuffer))
  39047. this._urlType = "Array";
  39048. if (urlOrArrayBuffer instanceof ArrayBuffer)
  39049. this._urlType = "ArrayBuffer";
  39050. var urls = [];
  39051. var codecSupportedFound = false;
  39052. switch (this._urlType) {
  39053. case "ArrayBuffer":
  39054. if (urlOrArrayBuffer.byteLength > 0) {
  39055. codecSupportedFound = true;
  39056. this._soundLoaded(urlOrArrayBuffer);
  39057. }
  39058. break;
  39059. case "String":
  39060. urls.push(urlOrArrayBuffer);
  39061. case "Array":
  39062. if (urls.length === 0)
  39063. urls = urlOrArrayBuffer;
  39064. // If we found a supported format, we load it immediately and stop the loop
  39065. for (var i = 0; i < urls.length; i++) {
  39066. var url = urls[i];
  39067. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  39068. codecSupportedFound = true;
  39069. }
  39070. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  39071. codecSupportedFound = true;
  39072. }
  39073. if (url.indexOf(".wav", url.length - 4) !== -1) {
  39074. codecSupportedFound = true;
  39075. }
  39076. if (codecSupportedFound) {
  39077. // Loading sound using XHR2
  39078. if (!this._streaming) {
  39079. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  39080. }
  39081. else {
  39082. this._htmlAudioElement = new Audio(url);
  39083. this._htmlAudioElement.controls = false;
  39084. this._htmlAudioElement.loop = this.loop;
  39085. this._htmlAudioElement.crossOrigin = "anonymous";
  39086. this._htmlAudioElement.preload = "auto";
  39087. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  39088. _this._isReadyToPlay = true;
  39089. if (_this.autoplay) {
  39090. _this.play();
  39091. }
  39092. if (_this._readyToPlayCallback) {
  39093. _this._readyToPlayCallback();
  39094. }
  39095. });
  39096. document.body.appendChild(this._htmlAudioElement);
  39097. }
  39098. break;
  39099. }
  39100. }
  39101. break;
  39102. default:
  39103. validParameter = false;
  39104. break;
  39105. }
  39106. if (!validParameter) {
  39107. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  39108. }
  39109. else {
  39110. if (!codecSupportedFound) {
  39111. this._isReadyToPlay = true;
  39112. // Simulating a ready to play event to avoid breaking code path
  39113. if (this._readyToPlayCallback) {
  39114. window.setTimeout(function () {
  39115. _this._readyToPlayCallback();
  39116. }, 1000);
  39117. }
  39118. }
  39119. }
  39120. }
  39121. }
  39122. else {
  39123. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  39124. this._scene.mainSoundTrack.AddSound(this);
  39125. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  39126. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  39127. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  39128. }
  39129. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  39130. if (this._readyToPlayCallback) {
  39131. window.setTimeout(function () {
  39132. _this._readyToPlayCallback();
  39133. }, 1000);
  39134. }
  39135. }
  39136. }
  39137. Sound.prototype.dispose = function () {
  39138. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  39139. if (this.isPlaying) {
  39140. this.stop();
  39141. }
  39142. this._isReadyToPlay = false;
  39143. if (this.soundTrackId === -1) {
  39144. this._scene.mainSoundTrack.RemoveSound(this);
  39145. }
  39146. else {
  39147. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  39148. }
  39149. if (this._soundGain) {
  39150. this._soundGain.disconnect();
  39151. this._soundGain = null;
  39152. }
  39153. if (this._soundPanner) {
  39154. this._soundPanner.disconnect();
  39155. this._soundPanner = null;
  39156. }
  39157. if (this._soundSource) {
  39158. this._soundSource.disconnect();
  39159. this._soundSource = null;
  39160. }
  39161. this._audioBuffer = null;
  39162. if (this._htmlAudioElement) {
  39163. this._htmlAudioElement.pause();
  39164. this._htmlAudioElement.src = "";
  39165. document.body.removeChild(this._htmlAudioElement);
  39166. }
  39167. if (this._connectedMesh) {
  39168. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39169. this._connectedMesh = null;
  39170. }
  39171. }
  39172. };
  39173. Sound.prototype.isReady = function () {
  39174. return this._isReadyToPlay;
  39175. };
  39176. Sound.prototype._soundLoaded = function (audioData) {
  39177. var _this = this;
  39178. this._isLoaded = true;
  39179. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  39180. _this._audioBuffer = buffer;
  39181. _this._isReadyToPlay = true;
  39182. if (_this.autoplay) {
  39183. _this.play();
  39184. }
  39185. if (_this._readyToPlayCallback) {
  39186. _this._readyToPlayCallback();
  39187. }
  39188. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  39189. };
  39190. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  39191. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39192. this._audioBuffer = audioBuffer;
  39193. this._isReadyToPlay = true;
  39194. }
  39195. };
  39196. Sound.prototype.updateOptions = function (options) {
  39197. if (options) {
  39198. this.loop = options.loop || this.loop;
  39199. this.maxDistance = options.maxDistance || this.maxDistance;
  39200. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  39201. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  39202. this.refDistance = options.refDistance || this.refDistance;
  39203. this.distanceModel = options.distanceModel || this.distanceModel;
  39204. this._playbackRate = options.playbackRate || this._playbackRate;
  39205. this._updateSpatialParameters();
  39206. if (this.isPlaying) {
  39207. if (this._streaming) {
  39208. this._htmlAudioElement.playbackRate = this._playbackRate;
  39209. }
  39210. else {
  39211. this._soundSource.playbackRate.value = this._playbackRate;
  39212. }
  39213. }
  39214. }
  39215. };
  39216. Sound.prototype._createSpatialParameters = function () {
  39217. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39218. if (this._scene.headphone) {
  39219. this._panningModel = "HRTF";
  39220. }
  39221. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  39222. this._updateSpatialParameters();
  39223. this._soundPanner.connect(this._ouputAudioNode);
  39224. this._inputAudioNode = this._soundPanner;
  39225. }
  39226. };
  39227. Sound.prototype._updateSpatialParameters = function () {
  39228. if (this.spatialSound) {
  39229. if (this.useCustomAttenuation) {
  39230. // Tricks to disable in a way embedded Web Audio attenuation
  39231. this._soundPanner.distanceModel = "linear";
  39232. this._soundPanner.maxDistance = Number.MAX_VALUE;
  39233. this._soundPanner.refDistance = 1;
  39234. this._soundPanner.rolloffFactor = 1;
  39235. this._soundPanner.panningModel = this._panningModel;
  39236. }
  39237. else {
  39238. this._soundPanner.distanceModel = this.distanceModel;
  39239. this._soundPanner.maxDistance = this.maxDistance;
  39240. this._soundPanner.refDistance = this.refDistance;
  39241. this._soundPanner.rolloffFactor = this.rolloffFactor;
  39242. this._soundPanner.panningModel = this._panningModel;
  39243. }
  39244. }
  39245. };
  39246. Sound.prototype.switchPanningModelToHRTF = function () {
  39247. this._panningModel = "HRTF";
  39248. this._switchPanningModel();
  39249. };
  39250. Sound.prototype.switchPanningModelToEqualPower = function () {
  39251. this._panningModel = "equalpower";
  39252. this._switchPanningModel();
  39253. };
  39254. Sound.prototype._switchPanningModel = function () {
  39255. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  39256. this._soundPanner.panningModel = this._panningModel;
  39257. }
  39258. };
  39259. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  39260. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39261. if (this._isOutputConnected) {
  39262. this._ouputAudioNode.disconnect();
  39263. }
  39264. this._ouputAudioNode.connect(soundTrackAudioNode);
  39265. this._isOutputConnected = true;
  39266. }
  39267. };
  39268. /**
  39269. * Transform this sound into a directional source
  39270. * @param coneInnerAngle Size of the inner cone in degree
  39271. * @param coneOuterAngle Size of the outer cone in degree
  39272. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  39273. */
  39274. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  39275. if (coneOuterAngle < coneInnerAngle) {
  39276. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  39277. return;
  39278. }
  39279. this._coneInnerAngle = coneInnerAngle;
  39280. this._coneOuterAngle = coneOuterAngle;
  39281. this._coneOuterGain = coneOuterGain;
  39282. this._isDirectional = true;
  39283. if (this.isPlaying && this.loop) {
  39284. this.stop();
  39285. this.play();
  39286. }
  39287. };
  39288. Sound.prototype.setPosition = function (newPosition) {
  39289. this._position = newPosition;
  39290. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  39291. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39292. }
  39293. };
  39294. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  39295. this._localDirection = newLocalDirection;
  39296. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  39297. this._updateDirection();
  39298. }
  39299. };
  39300. Sound.prototype._updateDirection = function () {
  39301. var mat = this._connectedMesh.getWorldMatrix();
  39302. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  39303. direction.normalize();
  39304. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  39305. };
  39306. Sound.prototype.updateDistanceFromListener = function () {
  39307. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  39308. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  39309. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  39310. }
  39311. };
  39312. Sound.prototype.setAttenuationFunction = function (callback) {
  39313. this._customAttenuationFunction = callback;
  39314. };
  39315. /**
  39316. * Play the sound
  39317. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  39318. * @param offset (optional) Start the sound setting it at a specific time
  39319. */
  39320. Sound.prototype.play = function (time, offset) {
  39321. var _this = this;
  39322. if (this._isReadyToPlay && this._scene.audioEnabled) {
  39323. try {
  39324. if (this._startOffset < 0) {
  39325. time = -this._startOffset;
  39326. this._startOffset = 0;
  39327. }
  39328. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39329. if (!this._soundSource || !this._streamingSource) {
  39330. if (this.spatialSound) {
  39331. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  39332. if (this._isDirectional) {
  39333. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  39334. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  39335. this._soundPanner.coneOuterGain = this._coneOuterGain;
  39336. if (this._connectedMesh) {
  39337. this._updateDirection();
  39338. }
  39339. else {
  39340. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  39341. }
  39342. }
  39343. }
  39344. }
  39345. if (this._streaming) {
  39346. if (!this._streamingSource) {
  39347. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  39348. this._htmlAudioElement.onended = function () { _this._onended(); };
  39349. this._htmlAudioElement.playbackRate = this._playbackRate;
  39350. }
  39351. this._streamingSource.disconnect();
  39352. this._streamingSource.connect(this._inputAudioNode);
  39353. this._htmlAudioElement.play();
  39354. }
  39355. else {
  39356. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  39357. this._soundSource.buffer = this._audioBuffer;
  39358. this._soundSource.connect(this._inputAudioNode);
  39359. this._soundSource.loop = this.loop;
  39360. this._soundSource.playbackRate.value = this._playbackRate;
  39361. this._soundSource.onended = function () { _this._onended(); };
  39362. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  39363. }
  39364. this._startTime = startTime;
  39365. this.isPlaying = true;
  39366. this.isPaused = false;
  39367. }
  39368. catch (ex) {
  39369. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  39370. }
  39371. }
  39372. };
  39373. Sound.prototype._onended = function () {
  39374. this.isPlaying = false;
  39375. if (this.onended) {
  39376. this.onended();
  39377. }
  39378. };
  39379. /**
  39380. * Stop the sound
  39381. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  39382. */
  39383. Sound.prototype.stop = function (time) {
  39384. if (this.isPlaying) {
  39385. if (this._streaming) {
  39386. this._htmlAudioElement.pause();
  39387. // Test needed for Firefox or it will generate an Invalid State Error
  39388. if (this._htmlAudioElement.currentTime > 0) {
  39389. this._htmlAudioElement.currentTime = 0;
  39390. }
  39391. }
  39392. else {
  39393. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  39394. this._soundSource.stop(stopTime);
  39395. this._soundSource.onended = null;
  39396. if (!this.isPaused) {
  39397. this._startOffset = 0;
  39398. }
  39399. }
  39400. this.isPlaying = false;
  39401. }
  39402. };
  39403. Sound.prototype.pause = function () {
  39404. if (this.isPlaying) {
  39405. this.isPaused = true;
  39406. if (this._streaming) {
  39407. this._htmlAudioElement.pause();
  39408. }
  39409. else {
  39410. this.stop(0);
  39411. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  39412. }
  39413. }
  39414. };
  39415. Sound.prototype.setVolume = function (newVolume, time) {
  39416. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39417. if (time) {
  39418. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  39419. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  39420. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  39421. }
  39422. else {
  39423. this._soundGain.gain.value = newVolume;
  39424. }
  39425. }
  39426. this._volume = newVolume;
  39427. };
  39428. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  39429. this._playbackRate = newPlaybackRate;
  39430. if (this.isPlaying) {
  39431. if (this._streaming) {
  39432. this._htmlAudioElement.playbackRate = this._playbackRate;
  39433. }
  39434. else {
  39435. this._soundSource.playbackRate.value = this._playbackRate;
  39436. }
  39437. }
  39438. };
  39439. Sound.prototype.getVolume = function () {
  39440. return this._volume;
  39441. };
  39442. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  39443. var _this = this;
  39444. if (this._connectedMesh) {
  39445. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39446. this._registerFunc = null;
  39447. }
  39448. this._connectedMesh = meshToConnectTo;
  39449. if (!this.spatialSound) {
  39450. this.spatialSound = true;
  39451. this._createSpatialParameters();
  39452. if (this.isPlaying && this.loop) {
  39453. this.stop();
  39454. this.play();
  39455. }
  39456. }
  39457. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  39458. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  39459. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  39460. };
  39461. Sound.prototype.detachFromMesh = function () {
  39462. if (this._connectedMesh) {
  39463. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  39464. this._registerFunc = null;
  39465. this._connectedMesh = null;
  39466. }
  39467. };
  39468. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  39469. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  39470. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  39471. this._updateDirection();
  39472. }
  39473. };
  39474. Sound.prototype.clone = function () {
  39475. var _this = this;
  39476. if (!this._streaming) {
  39477. var setBufferAndRun = function () {
  39478. if (_this._isReadyToPlay) {
  39479. clonedSound._audioBuffer = _this.getAudioBuffer();
  39480. clonedSound._isReadyToPlay = true;
  39481. if (clonedSound.autoplay) {
  39482. clonedSound.play();
  39483. }
  39484. }
  39485. else {
  39486. window.setTimeout(setBufferAndRun, 300);
  39487. }
  39488. };
  39489. var currentOptions = {
  39490. autoplay: this.autoplay, loop: this.loop,
  39491. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  39492. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  39493. refDistance: this.refDistance, distanceModel: this.distanceModel
  39494. };
  39495. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  39496. if (this.useCustomAttenuation) {
  39497. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  39498. }
  39499. clonedSound.setPosition(this._position);
  39500. clonedSound.setPlaybackRate(this._playbackRate);
  39501. setBufferAndRun();
  39502. return clonedSound;
  39503. }
  39504. else {
  39505. return null;
  39506. }
  39507. };
  39508. Sound.prototype.getAudioBuffer = function () {
  39509. return this._audioBuffer;
  39510. };
  39511. Sound.prototype.serialize = function () {
  39512. var serializationObject = {
  39513. name: this.name,
  39514. url: this.name,
  39515. autoplay: this.autoplay,
  39516. loop: this.loop,
  39517. volume: this._volume,
  39518. spatialSound: this.spatialSound,
  39519. maxDistance: this.maxDistance,
  39520. rolloffFactor: this.rolloffFactor,
  39521. refDistance: this.refDistance,
  39522. distanceModel: this.distanceModel,
  39523. playbackRate: this._playbackRate,
  39524. panningModel: this._panningModel,
  39525. soundTrackId: this.soundTrackId
  39526. };
  39527. if (this.spatialSound) {
  39528. if (this._connectedMesh)
  39529. serializationObject.connectedMeshId = this._connectedMesh.id;
  39530. serializationObject.position = this._position.asArray();
  39531. serializationObject.refDistance = this.refDistance;
  39532. serializationObject.distanceModel = this.distanceModel;
  39533. serializationObject.isDirectional = this._isDirectional;
  39534. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  39535. serializationObject.coneInnerAngle = this._coneInnerAngle;
  39536. serializationObject.coneOuterAngle = this._coneOuterAngle;
  39537. serializationObject.coneOuterGain = this._coneOuterGain;
  39538. }
  39539. return serializationObject;
  39540. };
  39541. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  39542. var soundName = parsedSound.name;
  39543. var soundUrl;
  39544. if (parsedSound.url) {
  39545. soundUrl = rootUrl + parsedSound.url;
  39546. }
  39547. else {
  39548. soundUrl = rootUrl + soundName;
  39549. }
  39550. var options = {
  39551. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  39552. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  39553. rolloffFactor: parsedSound.rolloffFactor,
  39554. refDistance: parsedSound.refDistance,
  39555. distanceModel: parsedSound.distanceModel,
  39556. playbackRate: parsedSound.playbackRate
  39557. };
  39558. var newSound;
  39559. if (!sourceSound) {
  39560. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  39561. scene._addPendingData(newSound);
  39562. }
  39563. else {
  39564. var setBufferAndRun = function () {
  39565. if (sourceSound._isReadyToPlay) {
  39566. newSound._audioBuffer = sourceSound.getAudioBuffer();
  39567. newSound._isReadyToPlay = true;
  39568. if (newSound.autoplay) {
  39569. newSound.play();
  39570. }
  39571. }
  39572. else {
  39573. window.setTimeout(setBufferAndRun, 300);
  39574. }
  39575. };
  39576. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  39577. setBufferAndRun();
  39578. }
  39579. if (parsedSound.position) {
  39580. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  39581. newSound.setPosition(soundPosition);
  39582. }
  39583. if (parsedSound.isDirectional) {
  39584. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  39585. if (parsedSound.localDirectionToMesh) {
  39586. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  39587. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  39588. }
  39589. }
  39590. if (parsedSound.connectedMeshId) {
  39591. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  39592. if (connectedMesh) {
  39593. newSound.attachToMesh(connectedMesh);
  39594. }
  39595. }
  39596. return newSound;
  39597. };
  39598. return Sound;
  39599. }());
  39600. BABYLON.Sound = Sound;
  39601. })(BABYLON || (BABYLON = {}));
  39602. //# sourceMappingURL=babylon.sound.js.map
  39603. var BABYLON;
  39604. (function (BABYLON) {
  39605. var SoundTrack = (function () {
  39606. function SoundTrack(scene, options) {
  39607. this.id = -1;
  39608. this._isMainTrack = false;
  39609. this._isInitialized = false;
  39610. this._scene = scene;
  39611. this.soundCollection = new Array();
  39612. this._options = options;
  39613. if (!this._isMainTrack) {
  39614. this._scene.soundTracks.push(this);
  39615. this.id = this._scene.soundTracks.length - 1;
  39616. }
  39617. }
  39618. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  39619. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39620. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  39621. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  39622. if (this._options) {
  39623. if (this._options.volume) {
  39624. this._outputAudioNode.gain.value = this._options.volume;
  39625. }
  39626. if (this._options.mainTrack) {
  39627. this._isMainTrack = this._options.mainTrack;
  39628. }
  39629. }
  39630. this._isInitialized = true;
  39631. }
  39632. };
  39633. SoundTrack.prototype.dispose = function () {
  39634. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39635. if (this._connectedAnalyser) {
  39636. this._connectedAnalyser.stopDebugCanvas();
  39637. }
  39638. while (this.soundCollection.length) {
  39639. this.soundCollection[0].dispose();
  39640. }
  39641. if (this._outputAudioNode) {
  39642. this._outputAudioNode.disconnect();
  39643. }
  39644. this._outputAudioNode = null;
  39645. }
  39646. };
  39647. SoundTrack.prototype.AddSound = function (sound) {
  39648. if (!this._isInitialized) {
  39649. this._initializeSoundTrackAudioGraph();
  39650. }
  39651. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39652. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  39653. }
  39654. if (sound.soundTrackId) {
  39655. if (sound.soundTrackId === -1) {
  39656. this._scene.mainSoundTrack.RemoveSound(sound);
  39657. }
  39658. else {
  39659. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  39660. }
  39661. }
  39662. this.soundCollection.push(sound);
  39663. sound.soundTrackId = this.id;
  39664. };
  39665. SoundTrack.prototype.RemoveSound = function (sound) {
  39666. var index = this.soundCollection.indexOf(sound);
  39667. if (index !== -1) {
  39668. this.soundCollection.splice(index, 1);
  39669. }
  39670. };
  39671. SoundTrack.prototype.setVolume = function (newVolume) {
  39672. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39673. this._outputAudioNode.gain.value = newVolume;
  39674. }
  39675. };
  39676. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  39677. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39678. for (var i = 0; i < this.soundCollection.length; i++) {
  39679. this.soundCollection[i].switchPanningModelToHRTF();
  39680. }
  39681. }
  39682. };
  39683. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  39684. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39685. for (var i = 0; i < this.soundCollection.length; i++) {
  39686. this.soundCollection[i].switchPanningModelToEqualPower();
  39687. }
  39688. }
  39689. };
  39690. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  39691. if (this._connectedAnalyser) {
  39692. this._connectedAnalyser.stopDebugCanvas();
  39693. }
  39694. this._connectedAnalyser = analyser;
  39695. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  39696. this._outputAudioNode.disconnect();
  39697. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  39698. }
  39699. };
  39700. return SoundTrack;
  39701. }());
  39702. BABYLON.SoundTrack = SoundTrack;
  39703. })(BABYLON || (BABYLON = {}));
  39704. //# sourceMappingURL=babylon.soundtrack.js.map
  39705. var BABYLON;
  39706. (function (BABYLON) {
  39707. /**
  39708. * Special Glow Blur post process only blurring the alpha channel
  39709. * It enforces keeping the most luminous color in the color channel.
  39710. */
  39711. var GlowBlurPostProcess = (function (_super) {
  39712. __extends(GlowBlurPostProcess, _super);
  39713. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  39714. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  39715. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  39716. _this.direction = direction;
  39717. _this.blurWidth = blurWidth;
  39718. _this.onApplyObservable.add(function (effect) {
  39719. effect.setFloat2("screenSize", _this.width, _this.height);
  39720. effect.setVector2("direction", _this.direction);
  39721. effect.setFloat("blurWidth", _this.blurWidth);
  39722. });
  39723. return _this;
  39724. }
  39725. return GlowBlurPostProcess;
  39726. }(BABYLON.PostProcess));
  39727. /**
  39728. * The highlight layer Helps adding a glow effect around a mesh.
  39729. *
  39730. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  39731. * glowy meshes to your scene.
  39732. *
  39733. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  39734. */
  39735. var HighlightLayer = (function () {
  39736. /**
  39737. * Instantiates a new highlight Layer and references it to the scene..
  39738. * @param name The name of the layer
  39739. * @param scene The scene to use the layer in
  39740. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  39741. */
  39742. function HighlightLayer(name, scene, options) {
  39743. this._vertexBuffers = {};
  39744. this._mainTextureDesiredSize = { width: 0, height: 0 };
  39745. this._meshes = {};
  39746. this._maxSize = 0;
  39747. this._shouldRender = false;
  39748. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  39749. this._excludedMeshes = {};
  39750. /**
  39751. * Specifies whether or not the inner glow is ACTIVE in the layer.
  39752. */
  39753. this.innerGlow = true;
  39754. /**
  39755. * Specifies whether or not the outer glow is ACTIVE in the layer.
  39756. */
  39757. this.outerGlow = true;
  39758. /**
  39759. * Specifies wether the highlight layer is enabled or not.
  39760. */
  39761. this.isEnabled = true;
  39762. /**
  39763. * An event triggered when the highlight layer has been disposed.
  39764. * @type {BABYLON.Observable}
  39765. */
  39766. this.onDisposeObservable = new BABYLON.Observable();
  39767. /**
  39768. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  39769. * @type {BABYLON.Observable}
  39770. */
  39771. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  39772. /**
  39773. * An event triggered when the highlight layer is being blurred.
  39774. * @type {BABYLON.Observable}
  39775. */
  39776. this.onBeforeBlurObservable = new BABYLON.Observable();
  39777. /**
  39778. * An event triggered when the highlight layer has been blurred.
  39779. * @type {BABYLON.Observable}
  39780. */
  39781. this.onAfterBlurObservable = new BABYLON.Observable();
  39782. /**
  39783. * An event triggered when the glowing blurred texture is being merged in the scene.
  39784. * @type {BABYLON.Observable}
  39785. */
  39786. this.onBeforeComposeObservable = new BABYLON.Observable();
  39787. /**
  39788. * An event triggered when the glowing blurred texture has been merged in the scene.
  39789. * @type {BABYLON.Observable}
  39790. */
  39791. this.onAfterComposeObservable = new BABYLON.Observable();
  39792. /**
  39793. * An event triggered when the highlight layer changes its size.
  39794. * @type {BABYLON.Observable}
  39795. */
  39796. this.onSizeChangedObservable = new BABYLON.Observable();
  39797. this._scene = scene;
  39798. var engine = scene.getEngine();
  39799. this._engine = engine;
  39800. this._maxSize = this._engine.getCaps().maxTextureSize;
  39801. this._scene.highlightLayers.push(this);
  39802. // Warn on stencil.
  39803. if (!this._engine.isStencilEnable) {
  39804. 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 }");
  39805. }
  39806. // Adapt options
  39807. this._options = options || {
  39808. mainTextureRatio: 0.25,
  39809. blurTextureSizeRatio: 0.5,
  39810. blurHorizontalSize: 1,
  39811. blurVerticalSize: 1,
  39812. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  39813. };
  39814. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  39815. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  39816. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  39817. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  39818. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  39819. // VBO
  39820. var vertices = [];
  39821. vertices.push(1, 1);
  39822. vertices.push(-1, 1);
  39823. vertices.push(-1, -1);
  39824. vertices.push(1, -1);
  39825. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  39826. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  39827. // Indices
  39828. var indices = [];
  39829. indices.push(0);
  39830. indices.push(1);
  39831. indices.push(2);
  39832. indices.push(0);
  39833. indices.push(2);
  39834. indices.push(3);
  39835. this._indexBuffer = engine.createIndexBuffer(indices);
  39836. // Effect
  39837. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  39838. // Render target
  39839. this.setMainTextureSize();
  39840. // Create Textures and post processes
  39841. this.createTextureAndPostProcesses();
  39842. }
  39843. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  39844. /**
  39845. * Gets the horizontal size of the blur.
  39846. */
  39847. get: function () {
  39848. return this._horizontalBlurPostprocess.blurWidth;
  39849. },
  39850. /**
  39851. * Specifies the horizontal size of the blur.
  39852. */
  39853. set: function (value) {
  39854. this._horizontalBlurPostprocess.blurWidth = value;
  39855. },
  39856. enumerable: true,
  39857. configurable: true
  39858. });
  39859. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  39860. /**
  39861. * Gets the vertical size of the blur.
  39862. */
  39863. get: function () {
  39864. return this._verticalBlurPostprocess.blurWidth;
  39865. },
  39866. /**
  39867. * Specifies the vertical size of the blur.
  39868. */
  39869. set: function (value) {
  39870. this._verticalBlurPostprocess.blurWidth = value;
  39871. },
  39872. enumerable: true,
  39873. configurable: true
  39874. });
  39875. Object.defineProperty(HighlightLayer.prototype, "camera", {
  39876. /**
  39877. * Gets the camera attached to the layer.
  39878. */
  39879. get: function () {
  39880. return this._options.camera;
  39881. },
  39882. enumerable: true,
  39883. configurable: true
  39884. });
  39885. /**
  39886. * Creates the render target textures and post processes used in the highlight layer.
  39887. */
  39888. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  39889. var _this = this;
  39890. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  39891. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  39892. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  39893. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  39894. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  39895. width: this._mainTextureDesiredSize.width,
  39896. height: this._mainTextureDesiredSize.height
  39897. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  39898. this._mainTexture.activeCamera = this._options.camera;
  39899. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39900. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39901. this._mainTexture.anisotropicFilteringLevel = 1;
  39902. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  39903. this._mainTexture.renderParticles = false;
  39904. this._mainTexture.renderList = null;
  39905. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  39906. width: blurTextureWidth,
  39907. height: blurTextureHeight
  39908. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  39909. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39910. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  39911. this._blurTexture.anisotropicFilteringLevel = 16;
  39912. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  39913. this._blurTexture.renderParticles = false;
  39914. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39915. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  39916. effect.setTexture("textureSampler", _this._mainTexture);
  39917. });
  39918. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  39919. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39920. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  39921. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39922. });
  39923. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39924. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  39925. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39926. });
  39927. }
  39928. else {
  39929. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39930. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  39931. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39932. });
  39933. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  39934. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  39935. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  39936. });
  39937. }
  39938. this._mainTexture.onAfterUnbindObservable.add(function () {
  39939. _this.onBeforeBlurObservable.notifyObservers(_this);
  39940. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  39941. _this.onAfterBlurObservable.notifyObservers(_this);
  39942. });
  39943. // Custom render function
  39944. var renderSubMesh = function (subMesh) {
  39945. var mesh = subMesh.getRenderingMesh();
  39946. var scene = _this._scene;
  39947. var engine = scene.getEngine();
  39948. // Culling
  39949. engine.setState(subMesh.getMaterial().backFaceCulling);
  39950. // Managing instances
  39951. var batch = mesh._getInstancesRenderList(subMesh._id);
  39952. if (batch.mustReturn) {
  39953. return;
  39954. }
  39955. // Excluded Mesh
  39956. if (_this._excludedMeshes[mesh.uniqueId]) {
  39957. return;
  39958. }
  39959. ;
  39960. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  39961. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  39962. var material = subMesh.getMaterial();
  39963. var emissiveTexture = null;
  39964. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  39965. emissiveTexture = material.emissiveTexture;
  39966. }
  39967. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  39968. engine.enableEffect(_this._glowMapGenerationEffect);
  39969. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  39970. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  39971. if (highlightLayerMesh) {
  39972. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  39973. }
  39974. else {
  39975. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  39976. }
  39977. // Alpha test
  39978. if (material && material.needAlphaTesting()) {
  39979. var alphaTexture = material.getAlphaTestTexture();
  39980. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  39981. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  39982. }
  39983. // Glow emissive only
  39984. if (emissiveTexture) {
  39985. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  39986. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  39987. }
  39988. // Bones
  39989. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  39990. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  39991. }
  39992. // Draw
  39993. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  39994. }
  39995. else {
  39996. // Need to reset refresh rate of the shadowMap
  39997. _this._mainTexture.resetRefreshCounter();
  39998. }
  39999. };
  40000. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  40001. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  40002. var index;
  40003. for (index = 0; index < opaqueSubMeshes.length; index++) {
  40004. renderSubMesh(opaqueSubMeshes.data[index]);
  40005. }
  40006. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  40007. renderSubMesh(alphaTestSubMeshes.data[index]);
  40008. }
  40009. for (index = 0; index < transparentSubMeshes.length; index++) {
  40010. renderSubMesh(transparentSubMeshes.data[index]);
  40011. }
  40012. };
  40013. this._mainTexture.onClearObservable.add(function (engine) {
  40014. engine.clear(HighlightLayer.neutralColor, true, true, true);
  40015. });
  40016. };
  40017. /**
  40018. * Checks for the readiness of the element composing the layer.
  40019. * @param subMesh the mesh to check for
  40020. * @param useInstances specify wether or not to use instances to render the mesh
  40021. * @param emissiveTexture the associated emissive texture used to generate the glow
  40022. * @return true if ready otherwise, false
  40023. */
  40024. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  40025. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  40026. return false;
  40027. }
  40028. var defines = [];
  40029. var attribs = [BABYLON.VertexBuffer.PositionKind];
  40030. var mesh = subMesh.getMesh();
  40031. var material = subMesh.getMaterial();
  40032. var uv1 = false;
  40033. var uv2 = false;
  40034. // Alpha test
  40035. if (material && material.needAlphaTesting()) {
  40036. var alphaTexture = material.getAlphaTestTexture();
  40037. if (alphaTexture) {
  40038. defines.push("#define ALPHATEST");
  40039. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  40040. alphaTexture.coordinatesIndex === 1) {
  40041. defines.push("#define DIFFUSEUV2");
  40042. uv2 = true;
  40043. }
  40044. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40045. defines.push("#define DIFFUSEUV1");
  40046. uv1 = true;
  40047. }
  40048. }
  40049. }
  40050. // Emissive
  40051. if (emissiveTexture) {
  40052. defines.push("#define EMISSIVE");
  40053. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  40054. emissiveTexture.coordinatesIndex === 1) {
  40055. defines.push("#define EMISSIVEUV2");
  40056. uv2 = true;
  40057. }
  40058. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40059. defines.push("#define EMISSIVEUV1");
  40060. uv1 = true;
  40061. }
  40062. }
  40063. if (uv1) {
  40064. attribs.push(BABYLON.VertexBuffer.UVKind);
  40065. defines.push("#define UV1");
  40066. }
  40067. if (uv2) {
  40068. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  40069. defines.push("#define UV2");
  40070. }
  40071. // Bones
  40072. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  40073. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40074. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40075. if (mesh.numBoneInfluencers > 4) {
  40076. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40077. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  40078. }
  40079. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40080. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40081. }
  40082. else {
  40083. defines.push("#define NUM_BONE_INFLUENCERS 0");
  40084. }
  40085. // Instances
  40086. if (useInstances) {
  40087. defines.push("#define INSTANCES");
  40088. attribs.push("world0");
  40089. attribs.push("world1");
  40090. attribs.push("world2");
  40091. attribs.push("world3");
  40092. }
  40093. // Get correct effect
  40094. var join = defines.join("\n");
  40095. if (this._cachedDefines !== join) {
  40096. this._cachedDefines = join;
  40097. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  40098. }
  40099. return this._glowMapGenerationEffect.isReady();
  40100. };
  40101. /**
  40102. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  40103. */
  40104. HighlightLayer.prototype.render = function () {
  40105. var currentEffect = this._glowMapMergeEffect;
  40106. // Check
  40107. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  40108. return;
  40109. var engine = this._scene.getEngine();
  40110. this.onBeforeComposeObservable.notifyObservers(this);
  40111. // Render
  40112. engine.enableEffect(currentEffect);
  40113. engine.setState(false);
  40114. // Cache
  40115. var previousStencilBuffer = engine.getStencilBuffer();
  40116. var previousStencilFunction = engine.getStencilFunction();
  40117. var previousStencilMask = engine.getStencilMask();
  40118. var previousAlphaMode = engine.getAlphaMode();
  40119. // Texture
  40120. currentEffect.setTexture("textureSampler", this._blurTexture);
  40121. // VBOs
  40122. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  40123. // Draw order
  40124. engine.setAlphaMode(this._options.alphaBlendingMode);
  40125. engine.setStencilMask(0x00);
  40126. engine.setStencilBuffer(true);
  40127. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  40128. if (this.outerGlow) {
  40129. currentEffect.setFloat("offset", 0);
  40130. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  40131. engine.draw(true, 0, 6);
  40132. }
  40133. if (this.innerGlow) {
  40134. currentEffect.setFloat("offset", 1);
  40135. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  40136. engine.draw(true, 0, 6);
  40137. }
  40138. // Restore Cache
  40139. engine.setStencilFunction(previousStencilFunction);
  40140. engine.setStencilMask(previousStencilMask);
  40141. engine.setAlphaMode(previousAlphaMode);
  40142. engine.setStencilBuffer(previousStencilBuffer);
  40143. this.onAfterComposeObservable.notifyObservers(this);
  40144. // Handle size changes.
  40145. var size = this._mainTexture.getSize();
  40146. this.setMainTextureSize();
  40147. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  40148. // Recreate RTT and post processes on size change.
  40149. this.onSizeChangedObservable.notifyObservers(this);
  40150. this.disposeTextureAndPostProcesses();
  40151. this.createTextureAndPostProcesses();
  40152. }
  40153. };
  40154. /**
  40155. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  40156. * @param mesh The mesh to exclude from the highlight layer
  40157. */
  40158. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  40159. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  40160. if (!meshExcluded) {
  40161. this._excludedMeshes[mesh.uniqueId] = {
  40162. mesh: mesh,
  40163. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  40164. mesh.getEngine().setStencilBuffer(false);
  40165. }),
  40166. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  40167. mesh.getEngine().setStencilBuffer(true);
  40168. }),
  40169. };
  40170. }
  40171. };
  40172. /**
  40173. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  40174. * @param mesh The mesh to highlight
  40175. */
  40176. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  40177. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  40178. if (meshExcluded) {
  40179. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  40180. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  40181. }
  40182. this._excludedMeshes[mesh.uniqueId] = undefined;
  40183. };
  40184. /**
  40185. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  40186. * @param mesh The mesh to highlight
  40187. * @param color The color of the highlight
  40188. * @param glowEmissiveOnly Extract the glow from the emissive texture
  40189. */
  40190. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  40191. var _this = this;
  40192. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  40193. var meshHighlight = this._meshes[mesh.uniqueId];
  40194. if (meshHighlight) {
  40195. meshHighlight.color = color;
  40196. }
  40197. else {
  40198. this._meshes[mesh.uniqueId] = {
  40199. mesh: mesh,
  40200. color: color,
  40201. // Lambda required for capture due to Observable this context
  40202. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  40203. if (_this._excludedMeshes[mesh.uniqueId]) {
  40204. _this.defaultStencilReference(mesh);
  40205. }
  40206. else {
  40207. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  40208. }
  40209. }),
  40210. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  40211. glowEmissiveOnly: glowEmissiveOnly
  40212. };
  40213. }
  40214. this._shouldRender = true;
  40215. };
  40216. /**
  40217. * Remove a mesh from the highlight layer in order to make it stop glowing.
  40218. * @param mesh The mesh to highlight
  40219. */
  40220. HighlightLayer.prototype.removeMesh = function (mesh) {
  40221. var meshHighlight = this._meshes[mesh.uniqueId];
  40222. if (meshHighlight) {
  40223. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  40224. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  40225. }
  40226. this._meshes[mesh.uniqueId] = undefined;
  40227. this._shouldRender = false;
  40228. for (var meshHighlightToCheck in this._meshes) {
  40229. if (meshHighlightToCheck) {
  40230. this._shouldRender = true;
  40231. break;
  40232. }
  40233. }
  40234. };
  40235. /**
  40236. * Returns true if the layer contains information to display, otherwise false.
  40237. */
  40238. HighlightLayer.prototype.shouldRender = function () {
  40239. return this.isEnabled && this._shouldRender;
  40240. };
  40241. /**
  40242. * Sets the main texture desired size which is the closest power of two
  40243. * of the engine canvas size.
  40244. */
  40245. HighlightLayer.prototype.setMainTextureSize = function () {
  40246. if (this._options.mainTextureFixedSize) {
  40247. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  40248. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  40249. }
  40250. else {
  40251. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  40252. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  40253. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  40254. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  40255. }
  40256. };
  40257. /**
  40258. * Force the stencil to the normal expected value for none glowing parts
  40259. */
  40260. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  40261. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  40262. };
  40263. /**
  40264. * Dispose only the render target textures and post process.
  40265. */
  40266. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  40267. this._blurTexture.dispose();
  40268. this._mainTexture.dispose();
  40269. this._downSamplePostprocess.dispose();
  40270. this._horizontalBlurPostprocess.dispose();
  40271. this._verticalBlurPostprocess.dispose();
  40272. };
  40273. /**
  40274. * Dispose the highlight layer and free resources.
  40275. */
  40276. HighlightLayer.prototype.dispose = function () {
  40277. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40278. if (vertexBuffer) {
  40279. vertexBuffer.dispose();
  40280. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40281. }
  40282. if (this._indexBuffer) {
  40283. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40284. this._indexBuffer = null;
  40285. }
  40286. // Clean textures and post processes
  40287. this.disposeTextureAndPostProcesses();
  40288. // Clean mesh references
  40289. for (var id in this._meshes) {
  40290. var meshHighlight = this._meshes[id];
  40291. if (meshHighlight && meshHighlight.mesh) {
  40292. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  40293. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  40294. }
  40295. }
  40296. this._meshes = null;
  40297. for (var id in this._excludedMeshes) {
  40298. var meshHighlight = this._excludedMeshes[id];
  40299. if (meshHighlight) {
  40300. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  40301. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  40302. }
  40303. }
  40304. this._excludedMeshes = null;
  40305. // Remove from scene
  40306. var index = this._scene.highlightLayers.indexOf(this, 0);
  40307. if (index > -1) {
  40308. this._scene.highlightLayers.splice(index, 1);
  40309. }
  40310. // Callback
  40311. this.onDisposeObservable.notifyObservers(this);
  40312. this.onDisposeObservable.clear();
  40313. this.onBeforeRenderMainTextureObservable.clear();
  40314. this.onBeforeBlurObservable.clear();
  40315. this.onBeforeComposeObservable.clear();
  40316. this.onAfterComposeObservable.clear();
  40317. this.onSizeChangedObservable.clear();
  40318. };
  40319. return HighlightLayer;
  40320. }());
  40321. /**
  40322. * The neutral color used during the preparation of the glow effect.
  40323. * This is black by default as the blend operation is a blend operation.
  40324. */
  40325. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  40326. /**
  40327. * Stencil value used for glowing meshes.
  40328. */
  40329. HighlightLayer.glowingMeshStencilReference = 0x02;
  40330. /**
  40331. * Stencil value used for the other meshes in the scene.
  40332. */
  40333. HighlightLayer.normalMeshStencilReference = 0x01;
  40334. BABYLON.HighlightLayer = HighlightLayer;
  40335. })(BABYLON || (BABYLON = {}));
  40336. //# sourceMappingURL=babylon.highlightlayer.js.map
  40337. var BABYLON;
  40338. (function (BABYLON) {
  40339. var SIMDVector3 = (function () {
  40340. function SIMDVector3() {
  40341. }
  40342. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  40343. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  40344. };
  40345. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  40346. var m = transformation.m;
  40347. var m0 = SIMD.Float32x4.load(m, 0);
  40348. var m1 = SIMD.Float32x4.load(m, 4);
  40349. var m2 = SIMD.Float32x4.load(m, 8);
  40350. var m3 = SIMD.Float32x4.load(m, 12);
  40351. 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));
  40352. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  40353. result.x = SIMD.Float32x4.extractLane(r, 0);
  40354. result.y = SIMD.Float32x4.extractLane(r, 1);
  40355. result.z = SIMD.Float32x4.extractLane(r, 2);
  40356. };
  40357. return SIMDVector3;
  40358. }());
  40359. var SIMDMatrix = (function () {
  40360. function SIMDMatrix() {
  40361. }
  40362. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  40363. var tm = this.m;
  40364. var om = other.m;
  40365. var m0 = SIMD.Float32x4.load(om, 0);
  40366. var m1 = SIMD.Float32x4.load(om, 4);
  40367. var m2 = SIMD.Float32x4.load(om, 8);
  40368. var m3 = SIMD.Float32x4.load(om, 12);
  40369. for (var i = 0; i < 16; i += 4) {
  40370. 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)))));
  40371. }
  40372. return this;
  40373. };
  40374. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  40375. var src = this.m;
  40376. var dest = other.m;
  40377. // Load the 4 rows
  40378. var src0 = SIMD.Float32x4.load(src, 0);
  40379. var src1 = SIMD.Float32x4.load(src, 4);
  40380. var src2 = SIMD.Float32x4.load(src, 8);
  40381. var src3 = SIMD.Float32x4.load(src, 12);
  40382. // Transpose the source matrix. Sort of. Not a true transpose operation
  40383. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  40384. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  40385. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  40386. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  40387. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  40388. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  40389. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  40390. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  40391. // This is a true transposition, but it will lead to an incorrect result
  40392. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  40393. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  40394. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  40395. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  40396. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  40397. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  40398. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  40399. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  40400. // ----
  40401. tmp1 = SIMD.Float32x4.mul(row2, row3);
  40402. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40403. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  40404. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  40405. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40406. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  40407. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  40408. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  40409. // ----
  40410. tmp1 = SIMD.Float32x4.mul(row1, row2);
  40411. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40412. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  40413. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  40414. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40415. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  40416. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  40417. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  40418. // ----
  40419. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  40420. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40421. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  40422. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  40423. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  40424. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40425. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  40426. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  40427. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  40428. // ----
  40429. tmp1 = SIMD.Float32x4.mul(row0, row1);
  40430. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40431. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  40432. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  40433. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40434. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  40435. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  40436. // ----
  40437. tmp1 = SIMD.Float32x4.mul(row0, row3);
  40438. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40439. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  40440. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  40441. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40442. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  40443. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  40444. // ----
  40445. tmp1 = SIMD.Float32x4.mul(row0, row2);
  40446. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  40447. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  40448. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  40449. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  40450. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  40451. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  40452. // Compute determinant
  40453. var det = SIMD.Float32x4.mul(row0, minor0);
  40454. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  40455. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  40456. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  40457. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  40458. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  40459. // These shuffles aren't necessary if the faulty transposition is done
  40460. // up at the top of this function.
  40461. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  40462. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  40463. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  40464. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  40465. // Compute final values by multiplying with 1/det
  40466. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  40467. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  40468. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  40469. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  40470. return this;
  40471. };
  40472. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  40473. var out = result.m;
  40474. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  40475. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  40476. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  40477. // cc.kmVec3Subtract(f, pCenter, pEye);
  40478. var f = SIMD.Float32x4.sub(center, eye);
  40479. // cc.kmVec3Normalize(f, f);
  40480. var tmp = SIMD.Float32x4.mul(f, f);
  40481. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40482. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40483. // cc.kmVec3Assign(up, pUp);
  40484. // cc.kmVec3Normalize(up, up);
  40485. tmp = SIMD.Float32x4.mul(up, up);
  40486. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40487. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40488. // cc.kmVec3Cross(s, f, up);
  40489. 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)));
  40490. // cc.kmVec3Normalize(s, s);
  40491. tmp = SIMD.Float32x4.mul(s, s);
  40492. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40493. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40494. // cc.kmVec3Cross(u, s, f);
  40495. 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)));
  40496. // cc.kmVec3Normalize(s, s);
  40497. tmp = SIMD.Float32x4.mul(s, s);
  40498. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  40499. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  40500. var zero = SIMD.Float32x4.splat(0.0);
  40501. s = SIMD.Float32x4.neg(s);
  40502. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  40503. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  40504. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  40505. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  40506. 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);
  40507. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  40508. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  40509. 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)))));
  40510. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  40511. 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)))));
  40512. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  40513. 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)))));
  40514. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  40515. 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)))));
  40516. };
  40517. return SIMDMatrix;
  40518. }());
  40519. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  40520. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  40521. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  40522. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  40523. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  40524. var SIMDHelper = (function () {
  40525. function SIMDHelper() {
  40526. }
  40527. Object.defineProperty(SIMDHelper, "IsEnabled", {
  40528. get: function () {
  40529. return SIMDHelper._isEnabled;
  40530. },
  40531. enumerable: true,
  40532. configurable: true
  40533. });
  40534. SIMDHelper.DisableSIMD = function () {
  40535. // Replace functions
  40536. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  40537. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  40538. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  40539. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  40540. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  40541. SIMDHelper._isEnabled = false;
  40542. };
  40543. SIMDHelper.EnableSIMD = function () {
  40544. if (self.SIMD === undefined) {
  40545. return;
  40546. }
  40547. // check if polyfills needed
  40548. if (!self.Math.fround) {
  40549. self.Math.fround = (function (array) { return function (x) {
  40550. return array[0] = x, array[0];
  40551. }; })(new Float32Array(1));
  40552. }
  40553. if (!self.Math.imul) {
  40554. self.Math.imul = function (a, b) {
  40555. var ah = (a >>> 16) & 0xffff;
  40556. var al = a & 0xffff;
  40557. var bh = (b >>> 16) & 0xffff;
  40558. var bl = b & 0xffff;
  40559. // the shift by 0 fixes the sign on the high part
  40560. // the final |0 converts the unsigned value into a signed value
  40561. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  40562. };
  40563. }
  40564. // Replace functions
  40565. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  40566. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  40567. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  40568. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  40569. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  40570. SIMDHelper._isEnabled = true;
  40571. };
  40572. return SIMDHelper;
  40573. }());
  40574. SIMDHelper._isEnabled = false;
  40575. BABYLON.SIMDHelper = SIMDHelper;
  40576. })(BABYLON || (BABYLON = {}));
  40577. //# sourceMappingURL=babylon.math.SIMD.js.map
  40578. var BABYLON;
  40579. (function (BABYLON) {
  40580. /**
  40581. * This class describe a rectangle that were added to the map.
  40582. * You have access to its coordinates either in pixel or normalized (UV)
  40583. */
  40584. var PackedRect = (function () {
  40585. function PackedRect(root, parent, pos, size) {
  40586. this._pos = pos;
  40587. this._size = size;
  40588. this._root = root;
  40589. this._parent = parent;
  40590. this._contentSize = null;
  40591. this._bottomNode = null;
  40592. this._leftNode = null;
  40593. this._initialSize = null;
  40594. this._rightNode = null;
  40595. }
  40596. Object.defineProperty(PackedRect.prototype, "pos", {
  40597. /**
  40598. * @returns the position of this node into the map
  40599. */
  40600. get: function () {
  40601. return this._pos;
  40602. },
  40603. enumerable: true,
  40604. configurable: true
  40605. });
  40606. Object.defineProperty(PackedRect.prototype, "contentSize", {
  40607. /**
  40608. * @returns the size of the rectangle this node handles
  40609. */
  40610. get: function () {
  40611. return this._contentSize;
  40612. },
  40613. enumerable: true,
  40614. configurable: true
  40615. });
  40616. Object.defineProperty(PackedRect.prototype, "UVs", {
  40617. /**
  40618. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  40619. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  40620. */
  40621. get: function () {
  40622. return this.getUVsForCustomSize(this._root._size);
  40623. },
  40624. enumerable: true,
  40625. configurable: true
  40626. });
  40627. /**
  40628. * 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.
  40629. * This method will return the UVs for this part by given the custom size of what you really use
  40630. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  40631. */
  40632. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  40633. var mainWidth = this._root._size.width;
  40634. var mainHeight = this._root._size.height;
  40635. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  40636. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  40637. var uvs = new Array();
  40638. uvs.push(topLeft);
  40639. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  40640. uvs.push(rightBottom);
  40641. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  40642. return uvs;
  40643. };
  40644. /**
  40645. * Free this rectangle from the map.
  40646. * Call this method when you no longer need the rectangle to be in the map.
  40647. */
  40648. PackedRect.prototype.freeContent = function () {
  40649. if (!this.contentSize) {
  40650. return;
  40651. }
  40652. this._contentSize = null;
  40653. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  40654. this.attemptDefrag();
  40655. };
  40656. Object.defineProperty(PackedRect.prototype, "isUsed", {
  40657. get: function () {
  40658. return this._contentSize != null || this._leftNode != null;
  40659. },
  40660. enumerable: true,
  40661. configurable: true
  40662. });
  40663. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  40664. var node = this.findNode(contentSize);
  40665. // Not enough space...
  40666. if (!node) {
  40667. return null;
  40668. }
  40669. node.splitNode(contentSize);
  40670. return node;
  40671. };
  40672. PackedRect.prototype.findNode = function (size) {
  40673. var resNode = null;
  40674. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  40675. if (this.isUsed) {
  40676. if (this._leftNode) {
  40677. resNode = this._leftNode.findNode(size);
  40678. }
  40679. if (!resNode && this._rightNode) {
  40680. resNode = this._rightNode.findNode(size);
  40681. }
  40682. if (!resNode && this._bottomNode) {
  40683. resNode = this._bottomNode.findNode(size);
  40684. }
  40685. }
  40686. else if (this._initialSize) {
  40687. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  40688. resNode = this;
  40689. }
  40690. else {
  40691. return null;
  40692. }
  40693. }
  40694. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  40695. resNode = this;
  40696. }
  40697. return resNode;
  40698. };
  40699. PackedRect.prototype.splitNode = function (contentSize) {
  40700. // 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)
  40701. if (!this._contentSize && this._initialSize) {
  40702. this._contentSize = contentSize.clone();
  40703. 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));
  40704. return this._leftNode.splitNode(contentSize);
  40705. }
  40706. else {
  40707. this._contentSize = contentSize.clone();
  40708. this._initialSize = contentSize.clone();
  40709. if (contentSize.width !== this._size.width) {
  40710. 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));
  40711. }
  40712. if (contentSize.height !== this._size.height) {
  40713. 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));
  40714. }
  40715. return this;
  40716. }
  40717. };
  40718. PackedRect.prototype.attemptDefrag = function () {
  40719. if (!this.isUsed && this.isRecursiveFree) {
  40720. this.clearNode();
  40721. if (this._parent) {
  40722. this._parent.attemptDefrag();
  40723. }
  40724. }
  40725. };
  40726. PackedRect.prototype.clearNode = function () {
  40727. this._initialSize = null;
  40728. this._rightNode = null;
  40729. this._bottomNode = null;
  40730. };
  40731. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  40732. get: function () {
  40733. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  40734. },
  40735. enumerable: true,
  40736. configurable: true
  40737. });
  40738. PackedRect.prototype.evalFreeSize = function (size) {
  40739. var levelSize = 0;
  40740. if (!this.isUsed) {
  40741. if (this._initialSize) {
  40742. levelSize = this._initialSize.surface;
  40743. }
  40744. else {
  40745. levelSize = this._size.surface;
  40746. }
  40747. }
  40748. if (this._rightNode) {
  40749. levelSize += this._rightNode.evalFreeSize(0);
  40750. }
  40751. if (this._bottomNode) {
  40752. levelSize += this._bottomNode.evalFreeSize(0);
  40753. }
  40754. return levelSize + size;
  40755. };
  40756. return PackedRect;
  40757. }());
  40758. BABYLON.PackedRect = PackedRect;
  40759. /**
  40760. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  40761. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  40762. * 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.
  40763. */
  40764. var RectPackingMap = (function (_super) {
  40765. __extends(RectPackingMap, _super);
  40766. /**
  40767. * Create an instance of the object with a dimension using the given size
  40768. * @param size The dimension of the rectangle that will contain all the sub ones.
  40769. */
  40770. function RectPackingMap(size) {
  40771. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  40772. _this._root = _this;
  40773. return _this;
  40774. }
  40775. /**
  40776. * Add a rectangle, finding the best location to store it into the map
  40777. * @param size the dimension of the rectangle to store
  40778. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  40779. */
  40780. RectPackingMap.prototype.addRect = function (size) {
  40781. var node = this.findAndSplitNode(size);
  40782. return node;
  40783. };
  40784. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  40785. /**
  40786. * Return the current space free normalized between [0;1]
  40787. * @returns {}
  40788. */
  40789. get: function () {
  40790. var freeSize = 0;
  40791. freeSize = this.evalFreeSize(freeSize);
  40792. return freeSize / (this._size.width * this._size.height);
  40793. },
  40794. enumerable: true,
  40795. configurable: true
  40796. });
  40797. return RectPackingMap;
  40798. }(PackedRect));
  40799. BABYLON.RectPackingMap = RectPackingMap;
  40800. })(BABYLON || (BABYLON = {}));
  40801. //# sourceMappingURL=babylon.rectPackingMap.js.map
  40802. var BABYLON;
  40803. (function (BABYLON) {
  40804. var DynamicFloatArrayElementInfo = (function () {
  40805. function DynamicFloatArrayElementInfo() {
  40806. }
  40807. return DynamicFloatArrayElementInfo;
  40808. }());
  40809. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  40810. /**
  40811. * 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.
  40812. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  40813. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  40814. * 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.
  40815. * 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.
  40816. * 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".
  40817. */
  40818. var DynamicFloatArray = (function () {
  40819. /**
  40820. * Construct an instance of the dynamic float array
  40821. * @param stride size of one element in float (i.e. not bytes!)
  40822. * @param initialElementCount the number of available entries at construction
  40823. */
  40824. function DynamicFloatArray(stride, initialElementCount) {
  40825. this.compareValueOffset = null;
  40826. this.sortingAscending = true;
  40827. this._stride = stride;
  40828. this.buffer = new Float32Array(stride * initialElementCount);
  40829. this._lastUsed = 0;
  40830. this._firstFree = 0;
  40831. this._allEntries = new Array(initialElementCount);
  40832. this._freeEntries = new Array(initialElementCount);
  40833. for (var i = 0; i < initialElementCount; i++) {
  40834. var element = new DynamicFloatArrayElementInfo();
  40835. element.offset = i * stride;
  40836. this._allEntries[i] = element;
  40837. this._freeEntries[initialElementCount - i - 1] = element;
  40838. }
  40839. }
  40840. /**
  40841. * Allocate an element in the array.
  40842. * @return the element info instance that contains the offset into the main buffer of the element's location.
  40843. * Beware, this offset may change when you call pack()
  40844. */
  40845. DynamicFloatArray.prototype.allocElement = function () {
  40846. if (this._freeEntries.length === 0) {
  40847. this._growBuffer();
  40848. }
  40849. var el = this._freeEntries.pop();
  40850. this._lastUsed = Math.max(el.offset, this._lastUsed);
  40851. if (el.offset === this._firstFree) {
  40852. if (this._freeEntries.length > 0) {
  40853. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  40854. }
  40855. else {
  40856. this._firstFree += this._stride;
  40857. }
  40858. }
  40859. return el;
  40860. };
  40861. /**
  40862. * Free the element corresponding to the given element info
  40863. * @param elInfo the element that describe the allocated element
  40864. */
  40865. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  40866. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  40867. this._freeEntries.push(elInfo);
  40868. };
  40869. /**
  40870. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  40871. * 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().
  40872. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  40873. */
  40874. DynamicFloatArray.prototype.pack = function () {
  40875. // no free slot? no need to pack
  40876. if (this._freeEntries.length === 0) {
  40877. return this.buffer;
  40878. }
  40879. // If the buffer is already packed the last used will always be lower than the first free
  40880. // 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.
  40881. if (this._lastUsed < this._firstFree) {
  40882. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  40883. return elementsBuffer_1;
  40884. }
  40885. var s = this._stride;
  40886. // 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
  40887. var lastFree = new DynamicFloatArrayElementInfo();
  40888. lastFree.offset = this.totalElementCount * s;
  40889. this._freeEntries.push(lastFree);
  40890. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  40891. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  40892. var firstFreeSlotOffset = sortedFree[0].offset;
  40893. var freeZoneSize = 1;
  40894. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  40895. var prevOffset = sortedFree[0].offset;
  40896. for (var i = 1; i < sortedFree.length; i++) {
  40897. // 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
  40898. if (firstFreeSlotOffset >= occupiedZoneSize) {
  40899. break;
  40900. }
  40901. var curFree = sortedFree[i];
  40902. var curOffset = curFree.offset;
  40903. // Compute the distance between this offset and the previous
  40904. var distance = curOffset - prevOffset;
  40905. // If the distance is the stride size, they are adjacent, it good, move to the next
  40906. if (distance === s) {
  40907. // Free zone is one element bigger
  40908. ++freeZoneSize;
  40909. // as we're about to iterate to the next, the cur becomes the previous...
  40910. prevOffset = curOffset;
  40911. continue;
  40912. }
  40913. // Distance is bigger, which means there's x element between the previous free and this one
  40914. var usedRange = (distance / s) - 1;
  40915. // Two cases the free zone is smaller than the data to move or bigger
  40916. // Copy what can fit in the free zone
  40917. var curMoveOffset = curOffset - s;
  40918. var copyCount = Math.min(freeZoneSize, usedRange);
  40919. for (var j = 0; j < copyCount; j++) {
  40920. var freeI = firstFreeSlotOffset / s;
  40921. var curI = curMoveOffset / s;
  40922. var moveEl = sortedAll[curI];
  40923. this._moveElement(moveEl, firstFreeSlotOffset);
  40924. var replacedEl = sortedAll[freeI];
  40925. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  40926. replacedEl.offset = curMoveOffset;
  40927. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  40928. sortedAll[freeI] = moveEl;
  40929. sortedAll[curI] = replacedEl;
  40930. curMoveOffset -= s;
  40931. firstFreeSlotOffset += s;
  40932. }
  40933. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  40934. if (freeZoneSize <= usedRange) {
  40935. firstFreeSlotOffset = curMoveOffset + s;
  40936. freeZoneSize = 1 + copyCount;
  40937. }
  40938. else {
  40939. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  40940. }
  40941. // as we're about to iterate to the next, the cur becomes the previous...
  40942. prevOffset = curOffset;
  40943. }
  40944. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  40945. this._lastUsed = firstFreeSlotOffset - s;
  40946. this._firstFree = firstFreeSlotOffset;
  40947. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  40948. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  40949. this._allEntries = sortedAll;
  40950. return elementsBuffer;
  40951. };
  40952. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  40953. for (var i = 0; i < this._stride; i++) {
  40954. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  40955. }
  40956. element.offset = destOffset;
  40957. };
  40958. DynamicFloatArray.prototype._growBuffer = function () {
  40959. // Allocate the new buffer with 50% more entries, copy the content of the current one
  40960. var newElCount = Math.floor(this.totalElementCount * 1.5);
  40961. var newBuffer = new Float32Array(newElCount * this._stride);
  40962. newBuffer.set(this.buffer);
  40963. var curCount = this.totalElementCount;
  40964. var addedCount = newElCount - this.totalElementCount;
  40965. for (var i = 0; i < addedCount; i++) {
  40966. var element = new DynamicFloatArrayElementInfo();
  40967. element.offset = (curCount + i) * this.stride;
  40968. this._allEntries.push(element);
  40969. this._freeEntries[addedCount - i - 1] = element;
  40970. }
  40971. this._firstFree = curCount * this.stride;
  40972. this.buffer = newBuffer;
  40973. };
  40974. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  40975. /**
  40976. * Get the total count of entries that can fit in the current buffer
  40977. * @returns the elements count
  40978. */
  40979. get: function () {
  40980. return this._allEntries.length;
  40981. },
  40982. enumerable: true,
  40983. configurable: true
  40984. });
  40985. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  40986. /**
  40987. * Get the count of free entries that can still be allocated without resizing the buffer
  40988. * @returns the free elements count
  40989. */
  40990. get: function () {
  40991. return this._freeEntries.length;
  40992. },
  40993. enumerable: true,
  40994. configurable: true
  40995. });
  40996. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  40997. /**
  40998. * Get the count of allocated elements
  40999. * @returns the allocated elements count
  41000. */
  41001. get: function () {
  41002. return this._allEntries.length - this._freeEntries.length;
  41003. },
  41004. enumerable: true,
  41005. configurable: true
  41006. });
  41007. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  41008. /**
  41009. * Return the size of one element in float
  41010. * @returns the size in float
  41011. */
  41012. get: function () {
  41013. return this._stride;
  41014. },
  41015. enumerable: true,
  41016. configurable: true
  41017. });
  41018. DynamicFloatArray.prototype.sort = function () {
  41019. var _this = this;
  41020. if (!this.compareValueOffset) {
  41021. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  41022. }
  41023. var count = this.usedElementCount;
  41024. // Do we have to (re)create the sort table?
  41025. if (!this._sortTable || this._sortTable.length < count) {
  41026. // 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...
  41027. var newCount = Math.min(this.totalElementCount, count * 2);
  41028. this._sortTable = new Array(newCount);
  41029. }
  41030. if (!this._sortedTable || this._sortedTable.length !== count) {
  41031. this._sortedTable = new Array(count);
  41032. }
  41033. // Because, you know...
  41034. this.pack();
  41035. //let stride = this.stride;
  41036. //for (let i = 0; i < count; i++) {
  41037. // let si = this._sortTable[i];
  41038. // if (!si) {
  41039. // si = new SortInfo();
  41040. // this._sortTable[i] = si;
  41041. // }
  41042. // si.entry = this._allEntries[i];
  41043. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  41044. // si.swapedOffset = null;
  41045. // this._sortedTable[i] = si;
  41046. //}
  41047. var curOffset = 0;
  41048. var stride = this.stride;
  41049. for (var i = 0; i < count; i++, curOffset += stride) {
  41050. var si = this._sortTable[i];
  41051. if (!si) {
  41052. si = new SortInfo();
  41053. this._sortTable[i] = si;
  41054. }
  41055. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  41056. si.offset = curOffset;
  41057. si.swapedOffset = null;
  41058. this._sortedTable[i] = si;
  41059. }
  41060. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  41061. if (this.sortingAscending) {
  41062. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  41063. }
  41064. else {
  41065. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  41066. }
  41067. var swapElements = function (src, dst) {
  41068. for (var i = 0; i < stride; i++) {
  41069. var tps = _this.buffer[dst + i];
  41070. _this.buffer[dst + i] = _this.buffer[src + i];
  41071. _this.buffer[src + i] = tps;
  41072. }
  41073. };
  41074. // 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:
  41075. // 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),
  41076. // and I still want something with a good algorithm complexity.
  41077. // 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,
  41078. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  41079. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  41080. // 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
  41081. // until we find a SortInfo object without a swapedOffset which means we got the right location
  41082. // 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
  41083. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  41084. for (var i = 0; i < count; i++) {
  41085. // Get the element to move
  41086. var sourceSI = this._sortedTable[i];
  41087. var destSI = this._sortTable[i];
  41088. var sourceOff = sourceSI.offset;
  41089. // If the source changed location, find the new one
  41090. if (sourceSI.swapedOffset) {
  41091. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  41092. var curSI = sourceSI;
  41093. while (curSI.swapedOffset) {
  41094. curSI = this._sortTable[curSI.swapedOffset / stride];
  41095. }
  41096. // Finally get the right location
  41097. sourceOff = curSI.offset;
  41098. }
  41099. // Tag the element being replaced with its new location
  41100. destSI.swapedOffset = sourceOff;
  41101. // Swap elements (only if needed)
  41102. if (sourceOff !== destSI.offset) {
  41103. swapElements(sourceOff, destSI.offset);
  41104. }
  41105. // Update the offset in the corresponding DFAE
  41106. //sourceSI.entry.offset = destSI.entry.offset;
  41107. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  41108. }
  41109. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  41110. return true;
  41111. };
  41112. return DynamicFloatArray;
  41113. }());
  41114. BABYLON.DynamicFloatArray = DynamicFloatArray;
  41115. var SortInfo = (function () {
  41116. function SortInfo() {
  41117. this.compareData = this.offset = this.swapedOffset = null;
  41118. }
  41119. return SortInfo;
  41120. }());
  41121. })(BABYLON || (BABYLON = {}));
  41122. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  41123. var BABYLON;
  41124. (function (BABYLON) {
  41125. var MapTexture = (function (_super) {
  41126. __extends(MapTexture, _super);
  41127. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  41128. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  41129. if (useMipMap === void 0) { useMipMap = false; }
  41130. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  41131. _this.name = name;
  41132. _this._size = size;
  41133. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41134. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41135. // Create the rectPackMap that will allocate portion of the texture
  41136. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  41137. // Create the texture that will store the content
  41138. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  41139. return _this;
  41140. }
  41141. /**
  41142. * Allocate a rectangle of a given size in the texture map
  41143. * @param size the size of the rectangle to allocation
  41144. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  41145. */
  41146. MapTexture.prototype.allocateRect = function (size) {
  41147. return this._rectPackingMap.addRect(size);
  41148. };
  41149. /**
  41150. * Free a given rectangle from the texture map
  41151. * @param rectInfo the instance corresponding to the rect to free.
  41152. */
  41153. MapTexture.prototype.freeRect = function (rectInfo) {
  41154. if (rectInfo) {
  41155. rectInfo.freeContent();
  41156. }
  41157. };
  41158. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  41159. /**
  41160. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  41161. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  41162. * @returns {}
  41163. */
  41164. get: function () {
  41165. return this._rectPackingMap.freeSpace;
  41166. },
  41167. enumerable: true,
  41168. configurable: true
  41169. });
  41170. /**
  41171. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  41172. * 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.
  41173. * Don't forget to call unbindTexture when you're done rendering
  41174. * @param rect the zone to render to
  41175. * @param clear true to clear the portion's color/depth data
  41176. */
  41177. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  41178. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  41179. };
  41180. /**
  41181. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  41182. * 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.
  41183. * Don't forget to call unbindTexture when you're done rendering
  41184. * @param pos the position into the texture
  41185. * @param size the portion to fit the clip space to
  41186. * @param clear true to clear the portion's color/depth data
  41187. */
  41188. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  41189. var engine = this.getScene().getEngine();
  41190. engine.bindFramebuffer(this._texture);
  41191. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  41192. if (clear) {
  41193. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  41194. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  41195. }
  41196. };
  41197. /**
  41198. * Unbind the texture map from the rendering engine.
  41199. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  41200. * @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.
  41201. */
  41202. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  41203. // Dump ?
  41204. if (dumpForDebug) {
  41205. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  41206. }
  41207. var engine = this.getScene().getEngine();
  41208. if (this._replacedViewport) {
  41209. engine.setViewport(this._replacedViewport);
  41210. this._replacedViewport = null;
  41211. }
  41212. engine.unBindFramebuffer(this._texture);
  41213. };
  41214. Object.defineProperty(MapTexture.prototype, "canRescale", {
  41215. get: function () {
  41216. return false;
  41217. },
  41218. enumerable: true,
  41219. configurable: true
  41220. });
  41221. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  41222. // Anyway, there's not much point to use this method for this kind of texture I guess
  41223. MapTexture.prototype.clone = function () {
  41224. return null;
  41225. };
  41226. return MapTexture;
  41227. }(BABYLON.Texture));
  41228. BABYLON.MapTexture = MapTexture;
  41229. })(BABYLON || (BABYLON = {}));
  41230. //# sourceMappingURL=babylon.mapTexture.js.map
  41231. var BABYLON;
  41232. (function (BABYLON) {
  41233. var ShaderMaterial = (function (_super) {
  41234. __extends(ShaderMaterial, _super);
  41235. function ShaderMaterial(name, scene, shaderPath, options) {
  41236. var _this = _super.call(this, name, scene) || this;
  41237. _this._textures = {};
  41238. _this._textureArrays = {};
  41239. _this._floats = {};
  41240. _this._floatsArrays = {};
  41241. _this._colors3 = {};
  41242. _this._colors4 = {};
  41243. _this._vectors2 = {};
  41244. _this._vectors3 = {};
  41245. _this._vectors4 = {};
  41246. _this._matrices = {};
  41247. _this._matrices3x3 = {};
  41248. _this._matrices2x2 = {};
  41249. _this._vectors3Arrays = {};
  41250. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  41251. _this._shaderPath = shaderPath;
  41252. options.needAlphaBlending = options.needAlphaBlending || false;
  41253. options.needAlphaTesting = options.needAlphaTesting || false;
  41254. options.attributes = options.attributes || ["position", "normal", "uv"];
  41255. options.uniforms = options.uniforms || ["worldViewProjection"];
  41256. options.samplers = options.samplers || [];
  41257. options.defines = options.defines || [];
  41258. _this._options = options;
  41259. return _this;
  41260. }
  41261. ShaderMaterial.prototype.getClassName = function () {
  41262. return "ShaderMaterial";
  41263. };
  41264. ShaderMaterial.prototype.needAlphaBlending = function () {
  41265. return this._options.needAlphaBlending;
  41266. };
  41267. ShaderMaterial.prototype.needAlphaTesting = function () {
  41268. return this._options.needAlphaTesting;
  41269. };
  41270. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  41271. if (this._options.uniforms.indexOf(uniformName) === -1) {
  41272. this._options.uniforms.push(uniformName);
  41273. }
  41274. };
  41275. ShaderMaterial.prototype.setTexture = function (name, texture) {
  41276. if (this._options.samplers.indexOf(name) === -1) {
  41277. this._options.samplers.push(name);
  41278. }
  41279. this._textures[name] = texture;
  41280. return this;
  41281. };
  41282. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  41283. if (this._options.samplers.indexOf(name) === -1) {
  41284. this._options.samplers.push(name);
  41285. }
  41286. this._checkUniform(name);
  41287. this._textureArrays[name] = textures;
  41288. return this;
  41289. };
  41290. ShaderMaterial.prototype.setFloat = function (name, value) {
  41291. this._checkUniform(name);
  41292. this._floats[name] = value;
  41293. return this;
  41294. };
  41295. ShaderMaterial.prototype.setFloats = function (name, value) {
  41296. this._checkUniform(name);
  41297. this._floatsArrays[name] = value;
  41298. return this;
  41299. };
  41300. ShaderMaterial.prototype.setColor3 = function (name, value) {
  41301. this._checkUniform(name);
  41302. this._colors3[name] = value;
  41303. return this;
  41304. };
  41305. ShaderMaterial.prototype.setColor4 = function (name, value) {
  41306. this._checkUniform(name);
  41307. this._colors4[name] = value;
  41308. return this;
  41309. };
  41310. ShaderMaterial.prototype.setVector2 = function (name, value) {
  41311. this._checkUniform(name);
  41312. this._vectors2[name] = value;
  41313. return this;
  41314. };
  41315. ShaderMaterial.prototype.setVector3 = function (name, value) {
  41316. this._checkUniform(name);
  41317. this._vectors3[name] = value;
  41318. return this;
  41319. };
  41320. ShaderMaterial.prototype.setVector4 = function (name, value) {
  41321. this._checkUniform(name);
  41322. this._vectors4[name] = value;
  41323. return this;
  41324. };
  41325. ShaderMaterial.prototype.setMatrix = function (name, value) {
  41326. this._checkUniform(name);
  41327. this._matrices[name] = value;
  41328. return this;
  41329. };
  41330. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  41331. this._checkUniform(name);
  41332. this._matrices3x3[name] = value;
  41333. return this;
  41334. };
  41335. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  41336. this._checkUniform(name);
  41337. this._matrices2x2[name] = value;
  41338. return this;
  41339. };
  41340. ShaderMaterial.prototype.setArray3 = function (name, value) {
  41341. this._checkUniform(name);
  41342. this._vectors3Arrays[name] = value;
  41343. return this;
  41344. };
  41345. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  41346. if (!mesh) {
  41347. return true;
  41348. }
  41349. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  41350. return false;
  41351. }
  41352. return false;
  41353. };
  41354. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  41355. var scene = this.getScene();
  41356. var engine = scene.getEngine();
  41357. if (!this.checkReadyOnEveryCall) {
  41358. if (this._renderId === scene.getRenderId()) {
  41359. if (this._checkCache(scene, mesh, useInstances)) {
  41360. return true;
  41361. }
  41362. }
  41363. }
  41364. // Instances
  41365. var defines = [];
  41366. var fallbacks = new BABYLON.EffectFallbacks();
  41367. if (useInstances) {
  41368. defines.push("#define INSTANCES");
  41369. }
  41370. for (var index = 0; index < this._options.defines.length; index++) {
  41371. defines.push(this._options.defines[index]);
  41372. }
  41373. // Bones
  41374. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  41375. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  41376. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  41377. fallbacks.addCPUSkinningFallback(0, mesh);
  41378. }
  41379. // Alpha test
  41380. if (engine.getAlphaTesting()) {
  41381. defines.push("#define ALPHATEST");
  41382. }
  41383. var previousEffect = this._effect;
  41384. var join = defines.join("\n");
  41385. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  41386. if (!this._effect.isReady()) {
  41387. return false;
  41388. }
  41389. if (previousEffect !== this._effect) {
  41390. scene.resetCachedMaterial();
  41391. }
  41392. this._renderId = scene.getRenderId();
  41393. return true;
  41394. };
  41395. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41396. var scene = this.getScene();
  41397. if (this._options.uniforms.indexOf("world") !== -1) {
  41398. this._effect.setMatrix("world", world);
  41399. }
  41400. if (this._options.uniforms.indexOf("worldView") !== -1) {
  41401. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  41402. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  41403. }
  41404. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  41405. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  41406. }
  41407. };
  41408. ShaderMaterial.prototype.bind = function (world, mesh) {
  41409. // Std values
  41410. this.bindOnlyWorldMatrix(world);
  41411. if (this.getScene().getCachedMaterial() !== this) {
  41412. if (this._options.uniforms.indexOf("view") !== -1) {
  41413. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  41414. }
  41415. if (this._options.uniforms.indexOf("projection") !== -1) {
  41416. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  41417. }
  41418. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  41419. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  41420. }
  41421. // Bones
  41422. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  41423. var name;
  41424. // Texture
  41425. for (name in this._textures) {
  41426. this._effect.setTexture(name, this._textures[name]);
  41427. }
  41428. // Texture arrays
  41429. for (name in this._textureArrays) {
  41430. this._effect.setTextureArray(name, this._textureArrays[name]);
  41431. }
  41432. // Float
  41433. for (name in this._floats) {
  41434. this._effect.setFloat(name, this._floats[name]);
  41435. }
  41436. // Float s
  41437. for (name in this._floatsArrays) {
  41438. this._effect.setArray(name, this._floatsArrays[name]);
  41439. }
  41440. // Color3
  41441. for (name in this._colors3) {
  41442. this._effect.setColor3(name, this._colors3[name]);
  41443. }
  41444. // Color4
  41445. for (name in this._colors4) {
  41446. var color = this._colors4[name];
  41447. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  41448. }
  41449. // Vector2
  41450. for (name in this._vectors2) {
  41451. this._effect.setVector2(name, this._vectors2[name]);
  41452. }
  41453. // Vector3
  41454. for (name in this._vectors3) {
  41455. this._effect.setVector3(name, this._vectors3[name]);
  41456. }
  41457. // Vector4
  41458. for (name in this._vectors4) {
  41459. this._effect.setVector4(name, this._vectors4[name]);
  41460. }
  41461. // Matrix
  41462. for (name in this._matrices) {
  41463. this._effect.setMatrix(name, this._matrices[name]);
  41464. }
  41465. // Matrix 3x3
  41466. for (name in this._matrices3x3) {
  41467. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  41468. }
  41469. // Matrix 2x2
  41470. for (name in this._matrices2x2) {
  41471. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  41472. }
  41473. // Vector3Array
  41474. for (name in this._vectors3Arrays) {
  41475. this._effect.setArray3(name, this._vectors3Arrays[name]);
  41476. }
  41477. }
  41478. _super.prototype.bind.call(this, world, mesh);
  41479. };
  41480. ShaderMaterial.prototype.clone = function (name) {
  41481. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  41482. return newShaderMaterial;
  41483. };
  41484. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  41485. if (forceDisposeTextures) {
  41486. var name;
  41487. for (name in this._textures) {
  41488. this._textures[name].dispose();
  41489. }
  41490. for (name in this._textureArrays) {
  41491. var array = this._textureArrays[name];
  41492. for (var index = 0; index < array.length; index++) {
  41493. array[index].dispose();
  41494. }
  41495. }
  41496. }
  41497. this._textures = {};
  41498. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  41499. };
  41500. ShaderMaterial.prototype.serialize = function () {
  41501. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  41502. serializationObject.customType = "BABYLON.ShaderMaterial";
  41503. serializationObject.options = this._options;
  41504. serializationObject.shaderPath = this._shaderPath;
  41505. var name;
  41506. // Texture
  41507. serializationObject.textures = {};
  41508. for (name in this._textures) {
  41509. serializationObject.textures[name] = this._textures[name].serialize();
  41510. }
  41511. // Texture arrays
  41512. serializationObject.textureArrays = {};
  41513. for (name in this._textureArrays) {
  41514. serializationObject.textureArrays[name] = [];
  41515. var array = this._textureArrays[name];
  41516. for (var index = 0; index < array.length; index++) {
  41517. serializationObject.textureArrays[name].push(array[index].serialize());
  41518. }
  41519. }
  41520. // Float
  41521. serializationObject.floats = {};
  41522. for (name in this._floats) {
  41523. serializationObject.floats[name] = this._floats[name];
  41524. }
  41525. // Float s
  41526. serializationObject.floatArrays = {};
  41527. for (name in this._floatsArrays) {
  41528. serializationObject.floatArrays[name] = this._floatsArrays[name];
  41529. }
  41530. // Color3
  41531. serializationObject.colors3 = {};
  41532. for (name in this._colors3) {
  41533. serializationObject.colors3[name] = this._colors3[name].asArray();
  41534. }
  41535. // Color4
  41536. serializationObject.colors4 = {};
  41537. for (name in this._colors4) {
  41538. serializationObject.colors4[name] = this._colors4[name].asArray();
  41539. }
  41540. // Vector2
  41541. serializationObject.vectors2 = {};
  41542. for (name in this._vectors2) {
  41543. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  41544. }
  41545. // Vector3
  41546. serializationObject.vectors3 = {};
  41547. for (name in this._vectors3) {
  41548. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  41549. }
  41550. // Vector4
  41551. serializationObject.vectors4 = {};
  41552. for (name in this._vectors4) {
  41553. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  41554. }
  41555. // Matrix
  41556. serializationObject.matrices = {};
  41557. for (name in this._matrices) {
  41558. serializationObject.matrices[name] = this._matrices[name].asArray();
  41559. }
  41560. // Matrix 3x3
  41561. serializationObject.matrices3x3 = {};
  41562. for (name in this._matrices3x3) {
  41563. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  41564. }
  41565. // Matrix 2x2
  41566. serializationObject.matrices2x2 = {};
  41567. for (name in this._matrices2x2) {
  41568. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  41569. }
  41570. // Vector3Array
  41571. serializationObject.vectors3Arrays = {};
  41572. for (name in this._vectors3Arrays) {
  41573. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  41574. }
  41575. return serializationObject;
  41576. };
  41577. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  41578. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  41579. var name;
  41580. // Texture
  41581. for (name in source.textures) {
  41582. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  41583. }
  41584. // Texture arrays
  41585. for (name in source.textureArrays) {
  41586. var array = source.textureArrays[name];
  41587. var textureArray = new Array();
  41588. for (var index = 0; index < array.length; index++) {
  41589. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  41590. }
  41591. material.setTextureArray(name, textureArray);
  41592. }
  41593. // Float
  41594. for (name in source.floats) {
  41595. material.setFloat(name, source.floats[name]);
  41596. }
  41597. // Float s
  41598. for (name in source.floatsArrays) {
  41599. material.setFloats(name, source.floatsArrays[name]);
  41600. }
  41601. // Color3
  41602. for (name in source.colors3) {
  41603. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  41604. }
  41605. // Color4
  41606. for (name in source.colors4) {
  41607. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  41608. }
  41609. // Vector2
  41610. for (name in source.vectors2) {
  41611. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  41612. }
  41613. // Vector3
  41614. for (name in source.vectors3) {
  41615. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  41616. }
  41617. // Vector4
  41618. for (name in source.vectors4) {
  41619. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  41620. }
  41621. // Matrix
  41622. for (name in source.matrices) {
  41623. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  41624. }
  41625. // Matrix 3x3
  41626. for (name in source.matrices3x3) {
  41627. material.setMatrix3x3(name, source.matrices3x3[name]);
  41628. }
  41629. // Matrix 2x2
  41630. for (name in source.matrices2x2) {
  41631. material.setMatrix2x2(name, source.matrices2x2[name]);
  41632. }
  41633. // Vector3Array
  41634. for (name in source.vectors3Arrays) {
  41635. material.setArray3(name, source.vectors3Arrays[name]);
  41636. }
  41637. return material;
  41638. };
  41639. return ShaderMaterial;
  41640. }(BABYLON.Material));
  41641. BABYLON.ShaderMaterial = ShaderMaterial;
  41642. })(BABYLON || (BABYLON = {}));
  41643. //# sourceMappingURL=babylon.shaderMaterial.js.map
  41644. var BABYLON;
  41645. (function (BABYLON) {
  41646. var Internals;
  41647. (function (Internals) {
  41648. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  41649. // All values and structures referenced from:
  41650. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  41651. var DDS_MAGIC = 0x20534444;
  41652. 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;
  41653. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  41654. 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;
  41655. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  41656. function FourCCToInt32(value) {
  41657. return value.charCodeAt(0) +
  41658. (value.charCodeAt(1) << 8) +
  41659. (value.charCodeAt(2) << 16) +
  41660. (value.charCodeAt(3) << 24);
  41661. }
  41662. function Int32ToFourCC(value) {
  41663. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  41664. }
  41665. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  41666. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  41667. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  41668. var headerLengthInt = 31; // The header length in 32 bit ints
  41669. // Offsets into the header array
  41670. var off_magic = 0;
  41671. var off_size = 1;
  41672. var off_flags = 2;
  41673. var off_height = 3;
  41674. var off_width = 4;
  41675. var off_mipmapCount = 7;
  41676. var off_pfFlags = 20;
  41677. var off_pfFourCC = 21;
  41678. var off_RGBbpp = 22;
  41679. var off_RMask = 23;
  41680. var off_GMask = 24;
  41681. var off_BMask = 25;
  41682. var off_AMask = 26;
  41683. var off_caps1 = 27;
  41684. var off_caps2 = 28;
  41685. ;
  41686. var DDSTools = (function () {
  41687. function DDSTools() {
  41688. }
  41689. DDSTools.GetDDSInfo = function (arrayBuffer) {
  41690. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  41691. var mipmapCount = 1;
  41692. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  41693. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41694. }
  41695. return {
  41696. width: header[off_width],
  41697. height: header[off_height],
  41698. mipmapCount: mipmapCount,
  41699. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  41700. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  41701. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  41702. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  41703. };
  41704. };
  41705. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41706. var byteArray = new Uint8Array(dataLength);
  41707. var srcData = new Uint8Array(arrayBuffer);
  41708. var index = 0;
  41709. for (var y = height - 1; y >= 0; y--) {
  41710. for (var x = 0; x < width; x++) {
  41711. var srcPos = dataOffset + (x + y * width) * 4;
  41712. byteArray[index + 2] = srcData[srcPos];
  41713. byteArray[index + 1] = srcData[srcPos + 1];
  41714. byteArray[index] = srcData[srcPos + 2];
  41715. byteArray[index + 3] = srcData[srcPos + 3];
  41716. index += 4;
  41717. }
  41718. }
  41719. return byteArray;
  41720. };
  41721. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41722. var byteArray = new Uint8Array(dataLength);
  41723. var srcData = new Uint8Array(arrayBuffer);
  41724. var index = 0;
  41725. for (var y = height - 1; y >= 0; y--) {
  41726. for (var x = 0; x < width; x++) {
  41727. var srcPos = dataOffset + (x + y * width) * 3;
  41728. byteArray[index + 2] = srcData[srcPos];
  41729. byteArray[index + 1] = srcData[srcPos + 1];
  41730. byteArray[index] = srcData[srcPos + 2];
  41731. index += 3;
  41732. }
  41733. }
  41734. return byteArray;
  41735. };
  41736. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41737. var byteArray = new Uint8Array(dataLength);
  41738. var srcData = new Uint8Array(arrayBuffer);
  41739. var index = 0;
  41740. for (var y = height - 1; y >= 0; y--) {
  41741. for (var x = 0; x < width; x++) {
  41742. var srcPos = dataOffset + (x + y * width);
  41743. byteArray[index] = srcData[srcPos];
  41744. index++;
  41745. }
  41746. }
  41747. return byteArray;
  41748. };
  41749. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  41750. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  41751. if (header[off_magic] != DDS_MAGIC) {
  41752. BABYLON.Tools.Error("Invalid magic number in DDS header");
  41753. return;
  41754. }
  41755. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  41756. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  41757. return;
  41758. }
  41759. if (info.isFourCC) {
  41760. fourCC = header[off_pfFourCC];
  41761. switch (fourCC) {
  41762. case FOURCC_DXT1:
  41763. blockBytes = 8;
  41764. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  41765. break;
  41766. case FOURCC_DXT3:
  41767. blockBytes = 16;
  41768. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  41769. break;
  41770. case FOURCC_DXT5:
  41771. blockBytes = 16;
  41772. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  41773. break;
  41774. default:
  41775. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  41776. return;
  41777. }
  41778. }
  41779. mipmapCount = 1;
  41780. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  41781. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41782. }
  41783. var bpp = header[off_RGBbpp];
  41784. for (var face = 0; face < faces; face++) {
  41785. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41786. width = header[off_width];
  41787. height = header[off_height];
  41788. dataOffset = header[off_size] + 4;
  41789. for (i = 0; i < mipmapCount; ++i) {
  41790. if (info.isRGB) {
  41791. if (bpp === 24) {
  41792. dataLength = width * height * 3;
  41793. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41794. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  41795. }
  41796. else {
  41797. dataLength = width * height * 4;
  41798. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41799. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  41800. }
  41801. }
  41802. else if (info.isLuminance) {
  41803. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  41804. var unpaddedRowSize = width;
  41805. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  41806. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  41807. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41808. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  41809. }
  41810. else {
  41811. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  41812. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  41813. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  41814. }
  41815. dataOffset += dataLength;
  41816. width *= 0.5;
  41817. height *= 0.5;
  41818. width = Math.max(1.0, width);
  41819. height = Math.max(1.0, height);
  41820. }
  41821. }
  41822. };
  41823. return DDSTools;
  41824. }());
  41825. Internals.DDSTools = DDSTools;
  41826. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41827. })(BABYLON || (BABYLON = {}));
  41828. //# sourceMappingURL=babylon.tools.dds.js.map
  41829. var BABYLON;
  41830. (function (BABYLON) {
  41831. var Internals;
  41832. (function (Internals) {
  41833. /**
  41834. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  41835. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  41836. */
  41837. var KhronosTextureContainer = (function () {
  41838. /**
  41839. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  41840. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  41841. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  41842. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  41843. */
  41844. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  41845. this.arrayBuffer = arrayBuffer;
  41846. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  41847. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  41848. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  41849. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  41850. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  41851. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  41852. BABYLON.Tools.Error("texture missing KTX identifier");
  41853. return;
  41854. }
  41855. // load the reset of the header in native 32 bit int
  41856. var header = new Int32Array(this.arrayBuffer, 12, 13);
  41857. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  41858. var oppositeEndianess = header[0] === 0x01020304;
  41859. // read all the header elements in order they exist in the file, without modification (sans endainness)
  41860. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  41861. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  41862. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  41863. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  41864. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  41865. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  41866. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  41867. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  41868. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  41869. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  41870. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  41871. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  41872. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  41873. if (this.glType !== 0) {
  41874. BABYLON.Tools.Error("only compressed formats currently supported");
  41875. return;
  41876. }
  41877. else {
  41878. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  41879. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  41880. }
  41881. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  41882. BABYLON.Tools.Error("only 2D textures currently supported");
  41883. return;
  41884. }
  41885. if (this.numberOfArrayElements !== 0) {
  41886. BABYLON.Tools.Error("texture arrays not currently supported");
  41887. return;
  41888. }
  41889. if (this.numberOfFaces !== facesExpected) {
  41890. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  41891. return;
  41892. }
  41893. // we now have a completely validated file, so could use existence of loadType as success
  41894. // would need to make this more elaborate & adjust checks above to support more than one load type
  41895. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  41896. }
  41897. // not as fast hardware based, but will probably never need to use
  41898. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  41899. return ((val & 0xFF) << 24)
  41900. | ((val & 0xFF00) << 8)
  41901. | ((val >> 8) & 0xFF00)
  41902. | ((val >> 24) & 0xFF);
  41903. };
  41904. /**
  41905. * It is assumed that the texture has already been created & is currently bound
  41906. */
  41907. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  41908. switch (this.loadType) {
  41909. case KhronosTextureContainer.COMPRESSED_2D:
  41910. this._upload2DCompressedLevels(gl, loadMipmaps);
  41911. break;
  41912. case KhronosTextureContainer.TEX_2D:
  41913. case KhronosTextureContainer.COMPRESSED_3D:
  41914. case KhronosTextureContainer.TEX_3D:
  41915. }
  41916. };
  41917. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  41918. // initialize width & height for level 1
  41919. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  41920. var width = this.pixelWidth;
  41921. var height = this.pixelHeight;
  41922. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  41923. for (var level = 0; level < mipmapCount; level++) {
  41924. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  41925. for (var face = 0; face < this.numberOfFaces; face++) {
  41926. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41927. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  41928. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  41929. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  41930. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  41931. }
  41932. width = Math.max(1.0, width * 0.5);
  41933. height = Math.max(1.0, height * 0.5);
  41934. }
  41935. };
  41936. return KhronosTextureContainer;
  41937. }());
  41938. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  41939. // load types
  41940. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  41941. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  41942. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  41943. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  41944. Internals.KhronosTextureContainer = KhronosTextureContainer;
  41945. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41946. })(BABYLON || (BABYLON = {}));
  41947. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  41948. var BABYLON;
  41949. (function (BABYLON) {
  41950. var CannonJSPlugin = (function () {
  41951. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  41952. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  41953. if (iterations === void 0) { iterations = 10; }
  41954. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  41955. this.name = "CannonJSPlugin";
  41956. this._physicsMaterials = [];
  41957. this._fixedTimeStep = 1 / 60;
  41958. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41959. this._currentCollisionGroup = 2;
  41960. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  41961. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  41962. this._tmpPosition = BABYLON.Vector3.Zero();
  41963. this._tmpQuaternion = new BABYLON.Quaternion();
  41964. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  41965. this._tmpDeltaRotation = new BABYLON.Quaternion();
  41966. this._tmpUnityRotation = new BABYLON.Quaternion();
  41967. if (!this.isSupported()) {
  41968. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  41969. return;
  41970. }
  41971. this.world = new CANNON.World();
  41972. this.world.broadphase = new CANNON.NaiveBroadphase();
  41973. this.world.solver.iterations = iterations;
  41974. }
  41975. CannonJSPlugin.prototype.setGravity = function (gravity) {
  41976. this.world.gravity.copy(gravity);
  41977. };
  41978. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  41979. this._fixedTimeStep = timeStep;
  41980. };
  41981. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  41982. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  41983. };
  41984. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41985. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41986. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41987. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41988. };
  41989. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41990. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41991. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41992. impostor.physicsBody.applyForce(impulse, worldPoint);
  41993. };
  41994. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41995. //parent-child relationship. Does this impostor has a parent impostor?
  41996. if (impostor.parent) {
  41997. if (impostor.physicsBody) {
  41998. this.removePhysicsBody(impostor);
  41999. //TODO is that needed?
  42000. impostor.forceUpdate();
  42001. }
  42002. return;
  42003. }
  42004. //should a new body be created for this impostor?
  42005. if (impostor.isBodyInitRequired()) {
  42006. var shape = this._createShape(impostor);
  42007. //unregister events, if body is being changed
  42008. var oldBody = impostor.physicsBody;
  42009. if (oldBody) {
  42010. this.removePhysicsBody(impostor);
  42011. }
  42012. //create the body and material
  42013. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  42014. var bodyCreationObject = {
  42015. mass: impostor.getParam("mass"),
  42016. material: material
  42017. };
  42018. // A simple extend, in case native options were used.
  42019. var nativeOptions = impostor.getParam("nativeOptions");
  42020. for (var key in nativeOptions) {
  42021. if (nativeOptions.hasOwnProperty(key)) {
  42022. bodyCreationObject[key] = nativeOptions[key];
  42023. }
  42024. }
  42025. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  42026. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  42027. this.world.addEventListener("preStep", impostor.beforeStep);
  42028. this.world.addEventListener("postStep", impostor.afterStep);
  42029. impostor.physicsBody.addShape(shape);
  42030. this.world.add(impostor.physicsBody);
  42031. //try to keep the body moving in the right direction by taking old properties.
  42032. //Should be tested!
  42033. if (oldBody) {
  42034. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  42035. impostor.physicsBody[param].copy(oldBody[param]);
  42036. });
  42037. }
  42038. this._processChildMeshes(impostor);
  42039. }
  42040. //now update the body's transformation
  42041. this._updatePhysicsBodyTransformation(impostor);
  42042. };
  42043. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  42044. var _this = this;
  42045. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  42046. if (meshChildren.length) {
  42047. var processMesh = function (localPosition, mesh) {
  42048. var childImpostor = mesh.getPhysicsImpostor();
  42049. if (childImpostor) {
  42050. var parent = childImpostor.parent;
  42051. if (parent !== mainImpostor) {
  42052. var localPosition = mesh.position;
  42053. if (childImpostor.physicsBody) {
  42054. _this.removePhysicsBody(childImpostor);
  42055. childImpostor.physicsBody = null;
  42056. }
  42057. childImpostor.parent = mainImpostor;
  42058. childImpostor.resetUpdateFlags();
  42059. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  42060. //Add the mass of the children.
  42061. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  42062. }
  42063. }
  42064. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  42065. };
  42066. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  42067. }
  42068. };
  42069. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  42070. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  42071. this.world.removeEventListener("preStep", impostor.beforeStep);
  42072. this.world.removeEventListener("postStep", impostor.afterStep);
  42073. this.world.remove(impostor.physicsBody);
  42074. };
  42075. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  42076. var mainBody = impostorJoint.mainImpostor.physicsBody;
  42077. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  42078. if (!mainBody || !connectedBody) {
  42079. return;
  42080. }
  42081. var constraint;
  42082. var jointData = impostorJoint.joint.jointData;
  42083. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  42084. var constraintData = {
  42085. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  42086. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  42087. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  42088. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  42089. maxForce: jointData.nativeParams.maxForce,
  42090. collideConnected: !!jointData.collision
  42091. };
  42092. switch (impostorJoint.joint.type) {
  42093. case BABYLON.PhysicsJoint.HingeJoint:
  42094. case BABYLON.PhysicsJoint.Hinge2Joint:
  42095. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  42096. break;
  42097. case BABYLON.PhysicsJoint.DistanceJoint:
  42098. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  42099. break;
  42100. case BABYLON.PhysicsJoint.SpringJoint:
  42101. var springData = jointData;
  42102. constraint = new CANNON.Spring(mainBody, connectedBody, {
  42103. restLength: springData.length,
  42104. stiffness: springData.stiffness,
  42105. damping: springData.damping,
  42106. localAnchorA: constraintData.pivotA,
  42107. localAnchorB: constraintData.pivotB
  42108. });
  42109. break;
  42110. case BABYLON.PhysicsJoint.LockJoint:
  42111. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  42112. break;
  42113. case BABYLON.PhysicsJoint.PointToPointJoint:
  42114. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  42115. default:
  42116. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  42117. break;
  42118. }
  42119. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  42120. constraint.collideConnected = !!jointData.collision;
  42121. impostorJoint.joint.physicsJoint = constraint;
  42122. //don't add spring as constraint, as it is not one.
  42123. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  42124. this.world.addConstraint(constraint);
  42125. }
  42126. else {
  42127. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  42128. constraint.applyForce();
  42129. });
  42130. }
  42131. };
  42132. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  42133. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  42134. };
  42135. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  42136. var index;
  42137. var mat;
  42138. for (index = 0; index < this._physicsMaterials.length; index++) {
  42139. mat = this._physicsMaterials[index];
  42140. if (mat.friction === friction && mat.restitution === restitution) {
  42141. return mat;
  42142. }
  42143. }
  42144. var currentMat = new CANNON.Material(name);
  42145. currentMat.friction = friction;
  42146. currentMat.restitution = restitution;
  42147. this._physicsMaterials.push(currentMat);
  42148. return currentMat;
  42149. };
  42150. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  42151. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  42152. };
  42153. CannonJSPlugin.prototype._createShape = function (impostor) {
  42154. var object = impostor.object;
  42155. var returnValue;
  42156. var extendSize = impostor.getObjectExtendSize();
  42157. switch (impostor.type) {
  42158. case BABYLON.PhysicsEngine.SphereImpostor:
  42159. var radiusX = extendSize.x;
  42160. var radiusY = extendSize.y;
  42161. var radiusZ = extendSize.z;
  42162. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  42163. break;
  42164. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  42165. case BABYLON.PhysicsImpostor.CylinderImpostor:
  42166. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  42167. break;
  42168. case BABYLON.PhysicsImpostor.BoxImpostor:
  42169. var box = extendSize.scale(0.5);
  42170. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  42171. break;
  42172. case BABYLON.PhysicsImpostor.PlaneImpostor:
  42173. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  42174. returnValue = new CANNON.Plane();
  42175. break;
  42176. case BABYLON.PhysicsImpostor.MeshImpostor:
  42177. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  42178. var rawFaces = object.getIndices ? object.getIndices() : [];
  42179. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  42180. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  42181. break;
  42182. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  42183. returnValue = this._createHeightmap(object);
  42184. break;
  42185. case BABYLON.PhysicsImpostor.ParticleImpostor:
  42186. returnValue = new CANNON.Particle();
  42187. break;
  42188. }
  42189. return returnValue;
  42190. };
  42191. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  42192. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42193. var matrix = [];
  42194. //For now pointDepth will not be used and will be automatically calculated.
  42195. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  42196. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  42197. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  42198. var elementSize = dim * 2 / arraySize;
  42199. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  42200. for (var i = 0; i < pos.length; i = i + 3) {
  42201. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  42202. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  42203. var y = pos[i + 1] + minY;
  42204. if (!matrix[x]) {
  42205. matrix[x] = [];
  42206. }
  42207. if (!matrix[x][z]) {
  42208. matrix[x][z] = y;
  42209. }
  42210. matrix[x][z] = Math.max(y, matrix[x][z]);
  42211. }
  42212. for (var x = 0; x <= arraySize; ++x) {
  42213. if (!matrix[x]) {
  42214. var loc = 1;
  42215. while (!matrix[(x + loc) % arraySize]) {
  42216. loc++;
  42217. }
  42218. matrix[x] = matrix[(x + loc) % arraySize].slice();
  42219. }
  42220. for (var z = 0; z <= arraySize; ++z) {
  42221. if (!matrix[x][z]) {
  42222. var loc = 1;
  42223. var newValue;
  42224. while (newValue === undefined) {
  42225. newValue = matrix[x][(z + loc++) % arraySize];
  42226. }
  42227. matrix[x][z] = newValue;
  42228. }
  42229. }
  42230. }
  42231. var shape = new CANNON.Heightfield(matrix, {
  42232. elementSize: elementSize
  42233. });
  42234. //For future reference, needed for body transformation
  42235. shape.minY = minY;
  42236. return shape;
  42237. };
  42238. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  42239. var object = impostor.object;
  42240. //make sure it is updated...
  42241. object.computeWorldMatrix && object.computeWorldMatrix(true);
  42242. // The delta between the mesh position and the mesh bounding box center
  42243. var center = impostor.getObjectCenter();
  42244. var extendSize = impostor.getObjectExtendSize();
  42245. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  42246. this._tmpPosition.copyFrom(center);
  42247. var quaternion = object.rotationQuaternion;
  42248. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  42249. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  42250. //-90 DEG in X, precalculated
  42251. quaternion = quaternion.multiply(this._minus90X);
  42252. //Invert! (Precalculated, 90 deg in X)
  42253. //No need to clone. this will never change.
  42254. impostor.setDeltaRotation(this._plus90X);
  42255. }
  42256. //If it is a heightfield, if should be centered.
  42257. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  42258. var mesh = object;
  42259. //calculate the correct body position:
  42260. var rotationQuaternion = mesh.rotationQuaternion;
  42261. mesh.rotationQuaternion = this._tmpUnityRotation;
  42262. mesh.computeWorldMatrix(true);
  42263. //get original center with no rotation
  42264. var c = center.clone();
  42265. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  42266. //rotation is back
  42267. mesh.rotationQuaternion = rotationQuaternion;
  42268. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  42269. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  42270. mesh.setPivotMatrix(p);
  42271. mesh.computeWorldMatrix(true);
  42272. //calculate the translation
  42273. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  42274. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  42275. //add it inverted to the delta
  42276. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  42277. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  42278. mesh.setPivotMatrix(oldPivot);
  42279. mesh.computeWorldMatrix(true);
  42280. }
  42281. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  42282. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  42283. this._tmpPosition.copyFrom(object.position);
  42284. }
  42285. impostor.setDeltaPosition(this._tmpDeltaPosition);
  42286. //Now update the impostor object
  42287. impostor.physicsBody.position.copy(this._tmpPosition);
  42288. impostor.physicsBody.quaternion.copy(quaternion);
  42289. };
  42290. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  42291. impostor.object.position.copyFrom(impostor.physicsBody.position);
  42292. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  42293. };
  42294. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  42295. impostor.physicsBody.position.copy(newPosition);
  42296. impostor.physicsBody.quaternion.copy(newRotation);
  42297. };
  42298. CannonJSPlugin.prototype.isSupported = function () {
  42299. return window.CANNON !== undefined;
  42300. };
  42301. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  42302. impostor.physicsBody.velocity.copy(velocity);
  42303. };
  42304. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  42305. impostor.physicsBody.angularVelocity.copy(velocity);
  42306. };
  42307. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  42308. var v = impostor.physicsBody.velocity;
  42309. if (!v)
  42310. return null;
  42311. return new BABYLON.Vector3(v.x, v.y, v.z);
  42312. };
  42313. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  42314. var v = impostor.physicsBody.angularVelocity;
  42315. if (!v)
  42316. return null;
  42317. return new BABYLON.Vector3(v.x, v.y, v.z);
  42318. };
  42319. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  42320. impostor.physicsBody.mass = mass;
  42321. impostor.physicsBody.updateMassProperties();
  42322. };
  42323. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  42324. impostor.physicsBody.sleep();
  42325. };
  42326. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  42327. impostor.physicsBody.wakeUp();
  42328. };
  42329. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  42330. joint.physicsJoint.distance = maxDistance;
  42331. };
  42332. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  42333. if (!motorIndex) {
  42334. joint.physicsJoint.enableMotor();
  42335. }
  42336. };
  42337. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  42338. if (!motorIndex) {
  42339. joint.physicsJoint.disableMotor();
  42340. }
  42341. };
  42342. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  42343. if (!motorIndex) {
  42344. joint.physicsJoint.enableMotor();
  42345. joint.physicsJoint.setMotorSpeed(speed);
  42346. if (maxForce) {
  42347. this.setLimit(joint, maxForce);
  42348. }
  42349. }
  42350. };
  42351. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  42352. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  42353. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  42354. };
  42355. CannonJSPlugin.prototype.dispose = function () {
  42356. //nothing to do, actually.
  42357. };
  42358. return CannonJSPlugin;
  42359. }());
  42360. BABYLON.CannonJSPlugin = CannonJSPlugin;
  42361. })(BABYLON || (BABYLON = {}));
  42362. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  42363. var BABYLON;
  42364. (function (BABYLON) {
  42365. var OimoJSPlugin = (function () {
  42366. function OimoJSPlugin(iterations) {
  42367. this.name = "OimoJSPlugin";
  42368. this._tmpImpostorsArray = [];
  42369. this._tmpPositionVector = BABYLON.Vector3.Zero();
  42370. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  42371. this.world.worldscale(1);
  42372. this.world.clear();
  42373. //making sure no stats are calculated
  42374. this.world.isNoStat = true;
  42375. }
  42376. OimoJSPlugin.prototype.setGravity = function (gravity) {
  42377. this.world.gravity.copy(gravity);
  42378. };
  42379. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  42380. this.world.timeStep = timeStep;
  42381. };
  42382. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  42383. var _this = this;
  42384. impostors.forEach(function (impostor) {
  42385. impostor.beforeStep();
  42386. });
  42387. this.world.step();
  42388. impostors.forEach(function (impostor) {
  42389. impostor.afterStep();
  42390. //update the ordered impostors array
  42391. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  42392. });
  42393. //check for collisions
  42394. var contact = this.world.contacts;
  42395. while (contact !== null) {
  42396. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  42397. contact = contact.next;
  42398. continue;
  42399. }
  42400. //is this body colliding with any other? get the impostor
  42401. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  42402. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  42403. if (!mainImpostor || !collidingImpostor) {
  42404. contact = contact.next;
  42405. continue;
  42406. }
  42407. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  42408. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  42409. contact = contact.next;
  42410. }
  42411. };
  42412. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  42413. var mass = impostor.physicsBody.massInfo.mass;
  42414. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  42415. };
  42416. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  42417. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  42418. this.applyImpulse(impostor, force, contactPoint);
  42419. };
  42420. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  42421. var _this = this;
  42422. //parent-child relationship. Does this impostor has a parent impostor?
  42423. if (impostor.parent) {
  42424. if (impostor.physicsBody) {
  42425. this.removePhysicsBody(impostor);
  42426. //TODO is that needed?
  42427. impostor.forceUpdate();
  42428. }
  42429. return;
  42430. }
  42431. if (impostor.isBodyInitRequired()) {
  42432. var bodyConfig = {
  42433. name: impostor.uniqueId,
  42434. //Oimo must have mass, also for static objects.
  42435. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  42436. size: [],
  42437. type: [],
  42438. pos: [],
  42439. rot: [],
  42440. move: impostor.getParam("mass") !== 0,
  42441. //Supporting older versions of Oimo
  42442. world: this.world
  42443. };
  42444. var impostors = [impostor];
  42445. var addToArray = function (parent) {
  42446. if (!parent.getChildMeshes)
  42447. return;
  42448. parent.getChildMeshes().forEach(function (m) {
  42449. if (m.physicsImpostor) {
  42450. impostors.push(m.physicsImpostor);
  42451. m.physicsImpostor._init();
  42452. }
  42453. });
  42454. };
  42455. addToArray(impostor.object);
  42456. var checkWithEpsilon_1 = function (value) {
  42457. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  42458. };
  42459. impostors.forEach(function (i) {
  42460. //get the correct bounding box
  42461. var oldQuaternion = i.object.rotationQuaternion;
  42462. var rot = new OIMO.Euler().setFromQuaternion({
  42463. x: impostor.object.rotationQuaternion.x,
  42464. y: impostor.object.rotationQuaternion.y,
  42465. z: impostor.object.rotationQuaternion.z,
  42466. s: impostor.object.rotationQuaternion.w
  42467. });
  42468. var extendSize = i.getObjectExtendSize();
  42469. if (i === impostor) {
  42470. var center = impostor.getObjectCenter();
  42471. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  42472. //Can also use Array.prototype.push.apply
  42473. bodyConfig.pos.push(center.x);
  42474. bodyConfig.pos.push(center.y);
  42475. bodyConfig.pos.push(center.z);
  42476. //tmp solution
  42477. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  42478. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  42479. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  42480. }
  42481. else {
  42482. bodyConfig.pos.push(i.object.position.x);
  42483. bodyConfig.pos.push(i.object.position.y);
  42484. bodyConfig.pos.push(i.object.position.z);
  42485. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  42486. bodyConfig.rot.push(0);
  42487. bodyConfig.rot.push(0);
  42488. bodyConfig.rot.push(0);
  42489. }
  42490. // register mesh
  42491. switch (i.type) {
  42492. case BABYLON.PhysicsImpostor.ParticleImpostor:
  42493. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  42494. case BABYLON.PhysicsImpostor.SphereImpostor:
  42495. var radiusX = extendSize.x;
  42496. var radiusY = extendSize.y;
  42497. var radiusZ = extendSize.z;
  42498. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  42499. bodyConfig.type.push('sphere');
  42500. //due to the way oimo works with compounds, add 3 times
  42501. bodyConfig.size.push(size);
  42502. bodyConfig.size.push(size);
  42503. bodyConfig.size.push(size);
  42504. break;
  42505. case BABYLON.PhysicsImpostor.CylinderImpostor:
  42506. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  42507. var sizeY = checkWithEpsilon_1(extendSize.y);
  42508. bodyConfig.type.push('cylinder');
  42509. bodyConfig.size.push(sizeX);
  42510. bodyConfig.size.push(sizeY);
  42511. //due to the way oimo works with compounds, add one more value.
  42512. bodyConfig.size.push(sizeY);
  42513. break;
  42514. case BABYLON.PhysicsImpostor.PlaneImpostor:
  42515. case BABYLON.PhysicsImpostor.BoxImpostor:
  42516. default:
  42517. var sizeX = checkWithEpsilon_1(extendSize.x);
  42518. var sizeY = checkWithEpsilon_1(extendSize.y);
  42519. var sizeZ = checkWithEpsilon_1(extendSize.z);
  42520. bodyConfig.type.push('box');
  42521. bodyConfig.size.push(sizeX);
  42522. bodyConfig.size.push(sizeY);
  42523. bodyConfig.size.push(sizeZ);
  42524. break;
  42525. }
  42526. //actually not needed, but hey...
  42527. i.object.rotationQuaternion = oldQuaternion;
  42528. });
  42529. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  42530. }
  42531. else {
  42532. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  42533. }
  42534. impostor.setDeltaPosition(this._tmpPositionVector);
  42535. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  42536. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  42537. };
  42538. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  42539. //impostor.physicsBody.dispose();
  42540. //Same as : (older oimo versions)
  42541. this.world.removeRigidBody(impostor.physicsBody);
  42542. };
  42543. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  42544. var mainBody = impostorJoint.mainImpostor.physicsBody;
  42545. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  42546. if (!mainBody || !connectedBody) {
  42547. return;
  42548. }
  42549. var jointData = impostorJoint.joint.jointData;
  42550. var options = jointData.nativeParams || {};
  42551. var type;
  42552. var nativeJointData = {
  42553. body1: mainBody,
  42554. body2: connectedBody,
  42555. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  42556. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  42557. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  42558. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  42559. min: options.min,
  42560. max: options.max,
  42561. collision: options.collision || jointData.collision,
  42562. spring: options.spring,
  42563. //supporting older version of Oimo
  42564. world: this.world
  42565. };
  42566. switch (impostorJoint.joint.type) {
  42567. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  42568. type = "jointBall";
  42569. break;
  42570. case BABYLON.PhysicsJoint.SpringJoint:
  42571. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  42572. var springData = jointData;
  42573. nativeJointData.min = springData.length || nativeJointData.min;
  42574. //Max should also be set, just make sure it is at least min
  42575. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  42576. case BABYLON.PhysicsJoint.DistanceJoint:
  42577. type = "jointDistance";
  42578. nativeJointData.max = jointData.maxDistance;
  42579. break;
  42580. case BABYLON.PhysicsJoint.PrismaticJoint:
  42581. type = "jointPrisme";
  42582. break;
  42583. case BABYLON.PhysicsJoint.SliderJoint:
  42584. type = "jointSlide";
  42585. break;
  42586. case BABYLON.PhysicsJoint.WheelJoint:
  42587. type = "jointWheel";
  42588. break;
  42589. case BABYLON.PhysicsJoint.HingeJoint:
  42590. default:
  42591. type = "jointHinge";
  42592. break;
  42593. }
  42594. nativeJointData.type = type;
  42595. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  42596. };
  42597. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  42598. //Bug in Oimo prevents us from disposing a joint in the playground
  42599. //joint.joint.physicsJoint.dispose();
  42600. //So we will bruteforce it!
  42601. try {
  42602. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  42603. }
  42604. catch (e) {
  42605. BABYLON.Tools.Warn(e);
  42606. }
  42607. };
  42608. OimoJSPlugin.prototype.isSupported = function () {
  42609. return OIMO !== undefined;
  42610. };
  42611. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  42612. if (!impostor.physicsBody.sleeping) {
  42613. //TODO check that
  42614. if (impostor.physicsBody.shapes.next) {
  42615. var parentShape = this._getLastShape(impostor.physicsBody);
  42616. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  42617. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  42618. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  42619. }
  42620. else {
  42621. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  42622. }
  42623. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  42624. impostor.object.rotationQuaternion.normalize();
  42625. }
  42626. };
  42627. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  42628. var body = impostor.physicsBody;
  42629. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  42630. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  42631. body.syncShapes();
  42632. body.awake();
  42633. };
  42634. OimoJSPlugin.prototype._getLastShape = function (body) {
  42635. var lastShape = body.shapes;
  42636. while (lastShape.next) {
  42637. lastShape = lastShape.next;
  42638. }
  42639. return lastShape;
  42640. };
  42641. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  42642. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  42643. };
  42644. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  42645. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  42646. };
  42647. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  42648. var v = impostor.physicsBody.linearVelocity;
  42649. if (!v)
  42650. return null;
  42651. return new BABYLON.Vector3(v.x, v.y, v.z);
  42652. };
  42653. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  42654. var v = impostor.physicsBody.angularVelocity;
  42655. if (!v)
  42656. return null;
  42657. return new BABYLON.Vector3(v.x, v.y, v.z);
  42658. };
  42659. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  42660. var staticBody = mass === 0;
  42661. //this will actually set the body's density and not its mass.
  42662. //But this is how oimo treats the mass variable.
  42663. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  42664. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  42665. };
  42666. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  42667. impostor.physicsBody.sleep();
  42668. };
  42669. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  42670. impostor.physicsBody.awake();
  42671. };
  42672. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  42673. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  42674. if (minDistance !== void 0) {
  42675. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  42676. }
  42677. };
  42678. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  42679. //TODO separate rotational and transational motors.
  42680. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42681. if (motor) {
  42682. motor.setMotor(speed, maxForce);
  42683. }
  42684. };
  42685. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  42686. //TODO separate rotational and transational motors.
  42687. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  42688. if (motor) {
  42689. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  42690. }
  42691. };
  42692. OimoJSPlugin.prototype.dispose = function () {
  42693. this.world.clear();
  42694. };
  42695. return OimoJSPlugin;
  42696. }());
  42697. BABYLON.OimoJSPlugin = OimoJSPlugin;
  42698. })(BABYLON || (BABYLON = {}));
  42699. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  42700. var BABYLON;
  42701. (function (BABYLON) {
  42702. var DisplayPassPostProcess = (function (_super) {
  42703. __extends(DisplayPassPostProcess, _super);
  42704. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  42705. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  42706. }
  42707. return DisplayPassPostProcess;
  42708. }(BABYLON.PostProcess));
  42709. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  42710. })(BABYLON || (BABYLON = {}));
  42711. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  42712. var BABYLON;
  42713. (function (BABYLON) {
  42714. var SimplificationSettings = (function () {
  42715. function SimplificationSettings(quality, distance, optimizeMesh) {
  42716. this.quality = quality;
  42717. this.distance = distance;
  42718. this.optimizeMesh = optimizeMesh;
  42719. }
  42720. return SimplificationSettings;
  42721. }());
  42722. BABYLON.SimplificationSettings = SimplificationSettings;
  42723. var SimplificationQueue = (function () {
  42724. function SimplificationQueue() {
  42725. this.running = false;
  42726. this._simplificationArray = [];
  42727. }
  42728. SimplificationQueue.prototype.addTask = function (task) {
  42729. this._simplificationArray.push(task);
  42730. };
  42731. SimplificationQueue.prototype.executeNext = function () {
  42732. var task = this._simplificationArray.pop();
  42733. if (task) {
  42734. this.running = true;
  42735. this.runSimplification(task);
  42736. }
  42737. else {
  42738. this.running = false;
  42739. }
  42740. };
  42741. SimplificationQueue.prototype.runSimplification = function (task) {
  42742. var _this = this;
  42743. if (task.parallelProcessing) {
  42744. //parallel simplifier
  42745. task.settings.forEach(function (setting) {
  42746. var simplifier = _this.getSimplifier(task);
  42747. simplifier.simplify(setting, function (newMesh) {
  42748. task.mesh.addLODLevel(setting.distance, newMesh);
  42749. newMesh.isVisible = true;
  42750. //check if it is the last
  42751. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  42752. //all done, run the success callback.
  42753. task.successCallback();
  42754. }
  42755. _this.executeNext();
  42756. });
  42757. });
  42758. }
  42759. else {
  42760. //single simplifier.
  42761. var simplifier = this.getSimplifier(task);
  42762. var runDecimation = function (setting, callback) {
  42763. simplifier.simplify(setting, function (newMesh) {
  42764. task.mesh.addLODLevel(setting.distance, newMesh);
  42765. newMesh.isVisible = true;
  42766. //run the next quality level
  42767. callback();
  42768. });
  42769. };
  42770. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  42771. runDecimation(task.settings[loop.index], function () {
  42772. loop.executeNext();
  42773. });
  42774. }, function () {
  42775. //execution ended, run the success callback.
  42776. if (task.successCallback) {
  42777. task.successCallback();
  42778. }
  42779. _this.executeNext();
  42780. });
  42781. }
  42782. };
  42783. SimplificationQueue.prototype.getSimplifier = function (task) {
  42784. switch (task.simplificationType) {
  42785. case SimplificationType.QUADRATIC:
  42786. default:
  42787. return new QuadraticErrorSimplification(task.mesh);
  42788. }
  42789. };
  42790. return SimplificationQueue;
  42791. }());
  42792. BABYLON.SimplificationQueue = SimplificationQueue;
  42793. /**
  42794. * The implemented types of simplification.
  42795. * At the moment only Quadratic Error Decimation is implemented.
  42796. */
  42797. var SimplificationType;
  42798. (function (SimplificationType) {
  42799. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  42800. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  42801. var DecimationTriangle = (function () {
  42802. function DecimationTriangle(vertices) {
  42803. this.vertices = vertices;
  42804. this.error = new Array(4);
  42805. this.deleted = false;
  42806. this.isDirty = false;
  42807. this.deletePending = false;
  42808. this.borderFactor = 0;
  42809. }
  42810. return DecimationTriangle;
  42811. }());
  42812. BABYLON.DecimationTriangle = DecimationTriangle;
  42813. var DecimationVertex = (function () {
  42814. function DecimationVertex(position, id) {
  42815. this.position = position;
  42816. this.id = id;
  42817. this.isBorder = true;
  42818. this.q = new QuadraticMatrix();
  42819. this.triangleCount = 0;
  42820. this.triangleStart = 0;
  42821. this.originalOffsets = [];
  42822. }
  42823. DecimationVertex.prototype.updatePosition = function (newPosition) {
  42824. this.position.copyFrom(newPosition);
  42825. };
  42826. return DecimationVertex;
  42827. }());
  42828. BABYLON.DecimationVertex = DecimationVertex;
  42829. var QuadraticMatrix = (function () {
  42830. function QuadraticMatrix(data) {
  42831. this.data = new Array(10);
  42832. for (var i = 0; i < 10; ++i) {
  42833. if (data && data[i]) {
  42834. this.data[i] = data[i];
  42835. }
  42836. else {
  42837. this.data[i] = 0;
  42838. }
  42839. }
  42840. }
  42841. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  42842. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  42843. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  42844. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  42845. return det;
  42846. };
  42847. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  42848. for (var i = 0; i < 10; ++i) {
  42849. this.data[i] += matrix.data[i];
  42850. }
  42851. };
  42852. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  42853. for (var i = 0; i < 10; ++i) {
  42854. this.data[i] += data[i];
  42855. }
  42856. };
  42857. QuadraticMatrix.prototype.add = function (matrix) {
  42858. var m = new QuadraticMatrix();
  42859. for (var i = 0; i < 10; ++i) {
  42860. m.data[i] = this.data[i] + matrix.data[i];
  42861. }
  42862. return m;
  42863. };
  42864. QuadraticMatrix.FromData = function (a, b, c, d) {
  42865. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  42866. };
  42867. //returning an array to avoid garbage collection
  42868. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  42869. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  42870. };
  42871. return QuadraticMatrix;
  42872. }());
  42873. BABYLON.QuadraticMatrix = QuadraticMatrix;
  42874. var Reference = (function () {
  42875. function Reference(vertexId, triangleId) {
  42876. this.vertexId = vertexId;
  42877. this.triangleId = triangleId;
  42878. }
  42879. return Reference;
  42880. }());
  42881. BABYLON.Reference = Reference;
  42882. /**
  42883. * An implementation of the Quadratic Error simplification algorithm.
  42884. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  42885. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  42886. * @author RaananW
  42887. */
  42888. var QuadraticErrorSimplification = (function () {
  42889. function QuadraticErrorSimplification(_mesh) {
  42890. this._mesh = _mesh;
  42891. this.initialized = false;
  42892. this.syncIterations = 5000;
  42893. this.aggressiveness = 7;
  42894. this.decimationIterations = 100;
  42895. this.boundingBoxEpsilon = BABYLON.Epsilon;
  42896. }
  42897. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  42898. var _this = this;
  42899. this.initDecimatedMesh();
  42900. //iterating through the submeshes array, one after the other.
  42901. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  42902. _this.initWithMesh(loop.index, function () {
  42903. _this.runDecimation(settings, loop.index, function () {
  42904. loop.executeNext();
  42905. });
  42906. }, settings.optimizeMesh);
  42907. }, function () {
  42908. setTimeout(function () {
  42909. successCallback(_this._reconstructedMesh);
  42910. }, 0);
  42911. });
  42912. };
  42913. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  42914. var _this = this;
  42915. var gCount = 0;
  42916. triangle.vertices.forEach(function (vertex) {
  42917. var count = 0;
  42918. var vPos = vertex.position;
  42919. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  42920. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  42921. ++count;
  42922. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  42923. ++count;
  42924. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  42925. ++count;
  42926. if (count > 1) {
  42927. ++gCount;
  42928. }
  42929. ;
  42930. });
  42931. if (gCount > 1) {
  42932. console.log(triangle, gCount);
  42933. }
  42934. return gCount > 1;
  42935. };
  42936. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  42937. var _this = this;
  42938. var targetCount = ~~(this.triangles.length * settings.quality);
  42939. var deletedTriangles = 0;
  42940. var triangleCount = this.triangles.length;
  42941. var iterationFunction = function (iteration, callback) {
  42942. setTimeout(function () {
  42943. if (iteration % 5 === 0) {
  42944. _this.updateMesh(iteration === 0);
  42945. }
  42946. for (var i = 0; i < _this.triangles.length; ++i) {
  42947. _this.triangles[i].isDirty = false;
  42948. }
  42949. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  42950. var trianglesIterator = function (i) {
  42951. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  42952. var t = _this.triangles[tIdx];
  42953. if (!t)
  42954. return;
  42955. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  42956. return;
  42957. }
  42958. for (var j = 0; j < 3; ++j) {
  42959. if (t.error[j] < threshold) {
  42960. var deleted0 = [];
  42961. var deleted1 = [];
  42962. var v0 = t.vertices[j];
  42963. var v1 = t.vertices[(j + 1) % 3];
  42964. if (v0.isBorder || v1.isBorder)
  42965. continue;
  42966. var p = BABYLON.Vector3.Zero();
  42967. var n = BABYLON.Vector3.Zero();
  42968. var uv = BABYLON.Vector2.Zero();
  42969. var color = new BABYLON.Color4(0, 0, 0, 1);
  42970. _this.calculateError(v0, v1, p, n, uv, color);
  42971. var delTr = [];
  42972. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  42973. continue;
  42974. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  42975. continue;
  42976. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  42977. continue;
  42978. var uniqueArray = [];
  42979. delTr.forEach(function (deletedT) {
  42980. if (uniqueArray.indexOf(deletedT) === -1) {
  42981. deletedT.deletePending = true;
  42982. uniqueArray.push(deletedT);
  42983. }
  42984. });
  42985. if (uniqueArray.length % 2 !== 0) {
  42986. continue;
  42987. }
  42988. v0.q = v1.q.add(v0.q);
  42989. v0.updatePosition(p);
  42990. var tStart = _this.references.length;
  42991. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  42992. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  42993. var tCount = _this.references.length - tStart;
  42994. if (tCount <= v0.triangleCount) {
  42995. if (tCount) {
  42996. for (var c = 0; c < tCount; c++) {
  42997. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  42998. }
  42999. }
  43000. }
  43001. else {
  43002. v0.triangleStart = tStart;
  43003. }
  43004. v0.triangleCount = tCount;
  43005. break;
  43006. }
  43007. }
  43008. };
  43009. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  43010. }, 0);
  43011. };
  43012. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  43013. if (triangleCount - deletedTriangles <= targetCount)
  43014. loop.breakLoop();
  43015. else {
  43016. iterationFunction(loop.index, function () {
  43017. loop.executeNext();
  43018. });
  43019. }
  43020. }, function () {
  43021. setTimeout(function () {
  43022. //reconstruct this part of the mesh
  43023. _this.reconstructMesh(submeshIndex);
  43024. successCallback();
  43025. }, 0);
  43026. });
  43027. };
  43028. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  43029. var _this = this;
  43030. this.vertices = [];
  43031. this.triangles = [];
  43032. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43033. var indices = this._mesh.getIndices();
  43034. var submesh = this._mesh.subMeshes[submeshIndex];
  43035. var findInVertices = function (positionToSearch) {
  43036. if (optimizeMesh) {
  43037. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  43038. if (_this.vertices[ii].position.equals(positionToSearch)) {
  43039. return _this.vertices[ii];
  43040. }
  43041. }
  43042. }
  43043. return null;
  43044. };
  43045. var vertexReferences = [];
  43046. var vertexInit = function (i) {
  43047. var offset = i + submesh.verticesStart;
  43048. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  43049. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  43050. vertex.originalOffsets.push(offset);
  43051. if (vertex.id === _this.vertices.length) {
  43052. _this.vertices.push(vertex);
  43053. }
  43054. vertexReferences.push(vertex.id);
  43055. };
  43056. //var totalVertices = mesh.getTotalVertices();
  43057. var totalVertices = submesh.verticesCount;
  43058. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  43059. var indicesInit = function (i) {
  43060. var offset = (submesh.indexStart / 3) + i;
  43061. var pos = (offset * 3);
  43062. var i0 = indices[pos + 0];
  43063. var i1 = indices[pos + 1];
  43064. var i2 = indices[pos + 2];
  43065. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  43066. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  43067. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  43068. var triangle = new DecimationTriangle([v0, v1, v2]);
  43069. triangle.originalOffset = pos;
  43070. _this.triangles.push(triangle);
  43071. };
  43072. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  43073. _this.init(callback);
  43074. });
  43075. });
  43076. };
  43077. QuadraticErrorSimplification.prototype.init = function (callback) {
  43078. var _this = this;
  43079. var triangleInit1 = function (i) {
  43080. var t = _this.triangles[i];
  43081. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  43082. for (var j = 0; j < 3; j++) {
  43083. 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))));
  43084. }
  43085. };
  43086. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  43087. var triangleInit2 = function (i) {
  43088. var t = _this.triangles[i];
  43089. for (var j = 0; j < 3; ++j) {
  43090. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  43091. }
  43092. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  43093. };
  43094. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  43095. _this.initialized = true;
  43096. callback();
  43097. });
  43098. });
  43099. };
  43100. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  43101. var newTriangles = [];
  43102. var i;
  43103. for (i = 0; i < this.vertices.length; ++i) {
  43104. this.vertices[i].triangleCount = 0;
  43105. }
  43106. var t;
  43107. var j;
  43108. for (i = 0; i < this.triangles.length; ++i) {
  43109. if (!this.triangles[i].deleted) {
  43110. t = this.triangles[i];
  43111. for (j = 0; j < 3; ++j) {
  43112. t.vertices[j].triangleCount = 1;
  43113. }
  43114. newTriangles.push(t);
  43115. }
  43116. }
  43117. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  43118. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  43119. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  43120. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  43121. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43122. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43123. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43124. var vertexCount = 0;
  43125. for (i = 0; i < this.vertices.length; ++i) {
  43126. var vertex = this.vertices[i];
  43127. vertex.id = vertexCount;
  43128. if (vertex.triangleCount) {
  43129. vertex.originalOffsets.forEach(function (originalOffset) {
  43130. newPositionData.push(vertex.position.x);
  43131. newPositionData.push(vertex.position.y);
  43132. newPositionData.push(vertex.position.z);
  43133. newNormalData.push(normalData[originalOffset * 3]);
  43134. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  43135. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  43136. if (uvs && uvs.length) {
  43137. newUVsData.push(uvs[(originalOffset * 2)]);
  43138. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  43139. }
  43140. else if (colorsData && colorsData.length) {
  43141. newColorsData.push(colorsData[(originalOffset * 4)]);
  43142. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  43143. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  43144. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  43145. }
  43146. ++vertexCount;
  43147. });
  43148. }
  43149. }
  43150. var startingIndex = this._reconstructedMesh.getTotalIndices();
  43151. var startingVertex = this._reconstructedMesh.getTotalVertices();
  43152. var submeshesArray = this._reconstructedMesh.subMeshes;
  43153. this._reconstructedMesh.subMeshes = [];
  43154. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  43155. var originalIndices = this._mesh.getIndices();
  43156. for (i = 0; i < newTriangles.length; ++i) {
  43157. t = newTriangles[i]; //now get the new referencing point for each vertex
  43158. [0, 1, 2].forEach(function (idx) {
  43159. var id = originalIndices[t.originalOffset + idx];
  43160. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  43161. if (offset < 0)
  43162. offset = 0;
  43163. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  43164. });
  43165. }
  43166. //overwriting the old vertex buffers and indices.
  43167. this._reconstructedMesh.setIndices(newIndicesArray);
  43168. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  43169. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  43170. if (newUVsData.length > 0)
  43171. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  43172. if (newColorsData.length > 0)
  43173. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  43174. //create submesh
  43175. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  43176. if (submeshIndex > 0) {
  43177. this._reconstructedMesh.subMeshes = [];
  43178. submeshesArray.forEach(function (submesh) {
  43179. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  43180. });
  43181. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  43182. }
  43183. };
  43184. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  43185. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  43186. this._reconstructedMesh.material = this._mesh.material;
  43187. this._reconstructedMesh.parent = this._mesh.parent;
  43188. this._reconstructedMesh.isVisible = false;
  43189. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  43190. };
  43191. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  43192. for (var i = 0; i < vertex1.triangleCount; ++i) {
  43193. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  43194. if (t.deleted)
  43195. continue;
  43196. var s = this.references[vertex1.triangleStart + i].vertexId;
  43197. var v1 = t.vertices[(s + 1) % 3];
  43198. var v2 = t.vertices[(s + 2) % 3];
  43199. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  43200. deletedArray[i] = true;
  43201. delTr.push(t);
  43202. continue;
  43203. }
  43204. var d1 = v1.position.subtract(point);
  43205. d1 = d1.normalize();
  43206. var d2 = v2.position.subtract(point);
  43207. d2 = d2.normalize();
  43208. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  43209. return true;
  43210. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  43211. deletedArray[i] = false;
  43212. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  43213. return true;
  43214. }
  43215. return false;
  43216. };
  43217. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  43218. var newDeleted = deletedTriangles;
  43219. for (var i = 0; i < vertex.triangleCount; ++i) {
  43220. var ref = this.references[vertex.triangleStart + i];
  43221. var t = this.triangles[ref.triangleId];
  43222. if (t.deleted)
  43223. continue;
  43224. if (deletedArray[i] && t.deletePending) {
  43225. t.deleted = true;
  43226. newDeleted++;
  43227. continue;
  43228. }
  43229. t.vertices[ref.vertexId] = origVertex;
  43230. t.isDirty = true;
  43231. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  43232. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  43233. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  43234. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  43235. this.references.push(ref);
  43236. }
  43237. return newDeleted;
  43238. };
  43239. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  43240. for (var i = 0; i < this.vertices.length; ++i) {
  43241. var vCount = [];
  43242. var vId = [];
  43243. var v = this.vertices[i];
  43244. var j;
  43245. for (j = 0; j < v.triangleCount; ++j) {
  43246. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  43247. for (var ii = 0; ii < 3; ii++) {
  43248. var ofs = 0;
  43249. var vv = triangle.vertices[ii];
  43250. while (ofs < vCount.length) {
  43251. if (vId[ofs] === vv.id)
  43252. break;
  43253. ++ofs;
  43254. }
  43255. if (ofs === vCount.length) {
  43256. vCount.push(1);
  43257. vId.push(vv.id);
  43258. }
  43259. else {
  43260. vCount[ofs]++;
  43261. }
  43262. }
  43263. }
  43264. for (j = 0; j < vCount.length; ++j) {
  43265. if (vCount[j] === 1) {
  43266. this.vertices[vId[j]].isBorder = true;
  43267. }
  43268. else {
  43269. this.vertices[vId[j]].isBorder = false;
  43270. }
  43271. }
  43272. }
  43273. };
  43274. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  43275. if (identifyBorders === void 0) { identifyBorders = false; }
  43276. var i;
  43277. if (!identifyBorders) {
  43278. var newTrianglesVector = [];
  43279. for (i = 0; i < this.triangles.length; ++i) {
  43280. if (!this.triangles[i].deleted) {
  43281. newTrianglesVector.push(this.triangles[i]);
  43282. }
  43283. }
  43284. this.triangles = newTrianglesVector;
  43285. }
  43286. for (i = 0; i < this.vertices.length; ++i) {
  43287. this.vertices[i].triangleCount = 0;
  43288. this.vertices[i].triangleStart = 0;
  43289. }
  43290. var t;
  43291. var j;
  43292. var v;
  43293. for (i = 0; i < this.triangles.length; ++i) {
  43294. t = this.triangles[i];
  43295. for (j = 0; j < 3; ++j) {
  43296. v = t.vertices[j];
  43297. v.triangleCount++;
  43298. }
  43299. }
  43300. var tStart = 0;
  43301. for (i = 0; i < this.vertices.length; ++i) {
  43302. this.vertices[i].triangleStart = tStart;
  43303. tStart += this.vertices[i].triangleCount;
  43304. this.vertices[i].triangleCount = 0;
  43305. }
  43306. var newReferences = new Array(this.triangles.length * 3);
  43307. for (i = 0; i < this.triangles.length; ++i) {
  43308. t = this.triangles[i];
  43309. for (j = 0; j < 3; ++j) {
  43310. v = t.vertices[j];
  43311. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  43312. v.triangleCount++;
  43313. }
  43314. }
  43315. this.references = newReferences;
  43316. if (identifyBorders) {
  43317. this.identifyBorder();
  43318. }
  43319. };
  43320. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  43321. var x = point.x;
  43322. var y = point.y;
  43323. var z = point.z;
  43324. 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
  43325. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  43326. };
  43327. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  43328. var q = vertex1.q.add(vertex2.q);
  43329. var border = vertex1.isBorder && vertex2.isBorder;
  43330. var error = 0;
  43331. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  43332. if (qDet !== 0 && !border) {
  43333. if (!pointResult) {
  43334. pointResult = BABYLON.Vector3.Zero();
  43335. }
  43336. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  43337. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  43338. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  43339. error = this.vertexError(q, pointResult);
  43340. }
  43341. else {
  43342. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  43343. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  43344. var error1 = this.vertexError(q, vertex1.position);
  43345. var error2 = this.vertexError(q, vertex2.position);
  43346. var error3 = this.vertexError(q, p3);
  43347. error = Math.min(error1, error2, error3);
  43348. if (error === error1) {
  43349. if (pointResult) {
  43350. pointResult.copyFrom(vertex1.position);
  43351. }
  43352. }
  43353. else if (error === error2) {
  43354. if (pointResult) {
  43355. pointResult.copyFrom(vertex2.position);
  43356. }
  43357. }
  43358. else {
  43359. if (pointResult) {
  43360. pointResult.copyFrom(p3);
  43361. }
  43362. }
  43363. }
  43364. return error;
  43365. };
  43366. return QuadraticErrorSimplification;
  43367. }());
  43368. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  43369. })(BABYLON || (BABYLON = {}));
  43370. //# sourceMappingURL=babylon.meshSimplification.js.map
  43371. var BABYLON;
  43372. (function (BABYLON) {
  43373. var serializedGeometries = [];
  43374. var serializeGeometry = function (geometry, serializationGeometries) {
  43375. if (serializedGeometries[geometry.id]) {
  43376. return;
  43377. }
  43378. if (geometry.doNotSerialize) {
  43379. return;
  43380. }
  43381. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  43382. serializationGeometries.boxes.push(geometry.serialize());
  43383. }
  43384. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  43385. serializationGeometries.spheres.push(geometry.serialize());
  43386. }
  43387. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  43388. serializationGeometries.cylinders.push(geometry.serialize());
  43389. }
  43390. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  43391. serializationGeometries.toruses.push(geometry.serialize());
  43392. }
  43393. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  43394. serializationGeometries.grounds.push(geometry.serialize());
  43395. }
  43396. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  43397. serializationGeometries.planes.push(geometry.serialize());
  43398. }
  43399. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  43400. serializationGeometries.torusKnots.push(geometry.serialize());
  43401. }
  43402. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  43403. throw new Error("Unknown primitive type");
  43404. }
  43405. else {
  43406. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  43407. }
  43408. serializedGeometries[geometry.id] = true;
  43409. };
  43410. var serializeMesh = function (mesh, serializationScene) {
  43411. var serializationObject = {};
  43412. serializationObject.name = mesh.name;
  43413. serializationObject.id = mesh.id;
  43414. if (BABYLON.Tags.HasTags(mesh)) {
  43415. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  43416. }
  43417. serializationObject.position = mesh.position.asArray();
  43418. if (mesh.rotationQuaternion) {
  43419. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  43420. }
  43421. else if (mesh.rotation) {
  43422. serializationObject.rotation = mesh.rotation.asArray();
  43423. }
  43424. serializationObject.scaling = mesh.scaling.asArray();
  43425. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  43426. serializationObject.isEnabled = mesh.isEnabled();
  43427. serializationObject.isVisible = mesh.isVisible;
  43428. serializationObject.infiniteDistance = mesh.infiniteDistance;
  43429. serializationObject.pickable = mesh.isPickable;
  43430. serializationObject.receiveShadows = mesh.receiveShadows;
  43431. serializationObject.billboardMode = mesh.billboardMode;
  43432. serializationObject.visibility = mesh.visibility;
  43433. serializationObject.checkCollisions = mesh.checkCollisions;
  43434. serializationObject.isBlocker = mesh.isBlocker;
  43435. // Parent
  43436. if (mesh.parent) {
  43437. serializationObject.parentId = mesh.parent.id;
  43438. }
  43439. // Geometry
  43440. var geometry = mesh._geometry;
  43441. if (geometry) {
  43442. var geometryId = geometry.id;
  43443. serializationObject.geometryId = geometryId;
  43444. if (!mesh.getScene().getGeometryByID(geometryId)) {
  43445. // 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
  43446. serializeGeometry(geometry, serializationScene.geometries);
  43447. }
  43448. // SubMeshes
  43449. serializationObject.subMeshes = [];
  43450. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  43451. var subMesh = mesh.subMeshes[subIndex];
  43452. serializationObject.subMeshes.push({
  43453. materialIndex: subMesh.materialIndex,
  43454. verticesStart: subMesh.verticesStart,
  43455. verticesCount: subMesh.verticesCount,
  43456. indexStart: subMesh.indexStart,
  43457. indexCount: subMesh.indexCount
  43458. });
  43459. }
  43460. }
  43461. // Material
  43462. if (mesh.material) {
  43463. serializationObject.materialId = mesh.material.id;
  43464. }
  43465. else {
  43466. mesh.material = null;
  43467. }
  43468. // Skeleton
  43469. if (mesh.skeleton) {
  43470. serializationObject.skeletonId = mesh.skeleton.id;
  43471. }
  43472. // Physics
  43473. //TODO implement correct serialization for physics impostors.
  43474. if (mesh.getPhysicsImpostor()) {
  43475. serializationObject.physicsMass = mesh.getPhysicsMass();
  43476. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  43477. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  43478. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  43479. }
  43480. // Metadata
  43481. if (mesh.metadata) {
  43482. serializationObject.metadata = mesh.metadata;
  43483. }
  43484. // Instances
  43485. serializationObject.instances = [];
  43486. for (var index = 0; index < mesh.instances.length; index++) {
  43487. var instance = mesh.instances[index];
  43488. var serializationInstance = {
  43489. name: instance.name,
  43490. position: instance.position.asArray(),
  43491. scaling: instance.scaling.asArray()
  43492. };
  43493. if (instance.rotationQuaternion) {
  43494. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  43495. }
  43496. else if (instance.rotation) {
  43497. serializationInstance.rotation = instance.rotation.asArray();
  43498. }
  43499. serializationObject.instances.push(serializationInstance);
  43500. // Animations
  43501. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  43502. serializationInstance.ranges = instance.serializeAnimationRanges();
  43503. }
  43504. // Animations
  43505. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  43506. serializationObject.ranges = mesh.serializeAnimationRanges();
  43507. // Layer mask
  43508. serializationObject.layerMask = mesh.layerMask;
  43509. // Alpha
  43510. serializationObject.alphaIndex = mesh.alphaIndex;
  43511. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  43512. // Overlay
  43513. serializationObject.overlayAlpha = mesh.overlayAlpha;
  43514. serializationObject.overlayColor = mesh.overlayColor.asArray();
  43515. serializationObject.renderOverlay = mesh.renderOverlay;
  43516. // Fog
  43517. serializationObject.applyFog = mesh.applyFog;
  43518. // Action Manager
  43519. if (mesh.actionManager) {
  43520. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  43521. }
  43522. return serializationObject;
  43523. };
  43524. var finalizeSingleMesh = function (mesh, serializationObject) {
  43525. //only works if the mesh is already loaded
  43526. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  43527. //serialize material
  43528. if (mesh.material) {
  43529. if (mesh.material instanceof BABYLON.StandardMaterial) {
  43530. serializationObject.materials = serializationObject.materials || [];
  43531. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  43532. serializationObject.materials.push(mesh.material.serialize());
  43533. }
  43534. }
  43535. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  43536. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  43537. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  43538. serializationObject.multiMaterials.push(mesh.material.serialize());
  43539. }
  43540. }
  43541. }
  43542. //serialize geometry
  43543. var geometry = mesh._geometry;
  43544. if (geometry) {
  43545. if (!serializationObject.geometries) {
  43546. serializationObject.geometries = {};
  43547. serializationObject.geometries.boxes = [];
  43548. serializationObject.geometries.spheres = [];
  43549. serializationObject.geometries.cylinders = [];
  43550. serializationObject.geometries.toruses = [];
  43551. serializationObject.geometries.grounds = [];
  43552. serializationObject.geometries.planes = [];
  43553. serializationObject.geometries.torusKnots = [];
  43554. serializationObject.geometries.vertexData = [];
  43555. }
  43556. serializeGeometry(geometry, serializationObject.geometries);
  43557. }
  43558. // Skeletons
  43559. if (mesh.skeleton) {
  43560. serializationObject.skeletons = serializationObject.skeletons || [];
  43561. serializationObject.skeletons.push(mesh.skeleton.serialize());
  43562. }
  43563. //serialize the actual mesh
  43564. serializationObject.meshes = serializationObject.meshes || [];
  43565. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43566. }
  43567. };
  43568. var SceneSerializer = (function () {
  43569. function SceneSerializer() {
  43570. }
  43571. SceneSerializer.ClearCache = function () {
  43572. serializedGeometries = [];
  43573. };
  43574. SceneSerializer.Serialize = function (scene) {
  43575. var serializationObject = {};
  43576. // Scene
  43577. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  43578. serializationObject.autoClear = scene.autoClear;
  43579. serializationObject.clearColor = scene.clearColor.asArray();
  43580. serializationObject.ambientColor = scene.ambientColor.asArray();
  43581. serializationObject.gravity = scene.gravity.asArray();
  43582. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  43583. serializationObject.workerCollisions = scene.workerCollisions;
  43584. // Fog
  43585. if (scene.fogMode && scene.fogMode !== 0) {
  43586. serializationObject.fogMode = scene.fogMode;
  43587. serializationObject.fogColor = scene.fogColor.asArray();
  43588. serializationObject.fogStart = scene.fogStart;
  43589. serializationObject.fogEnd = scene.fogEnd;
  43590. serializationObject.fogDensity = scene.fogDensity;
  43591. }
  43592. //Physics
  43593. if (scene.isPhysicsEnabled()) {
  43594. serializationObject.physicsEnabled = true;
  43595. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  43596. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  43597. }
  43598. // Metadata
  43599. if (scene.metadata) {
  43600. serializationObject.metadata = scene.metadata;
  43601. }
  43602. // Lights
  43603. serializationObject.lights = [];
  43604. var index;
  43605. var light;
  43606. for (index = 0; index < scene.lights.length; index++) {
  43607. light = scene.lights[index];
  43608. if (!light.doNotSerialize) {
  43609. serializationObject.lights.push(light.serialize());
  43610. }
  43611. }
  43612. // Cameras
  43613. serializationObject.cameras = [];
  43614. for (index = 0; index < scene.cameras.length; index++) {
  43615. var camera = scene.cameras[index];
  43616. if (!camera.doNotSerialize) {
  43617. serializationObject.cameras.push(camera.serialize());
  43618. }
  43619. }
  43620. if (scene.activeCamera) {
  43621. serializationObject.activeCameraID = scene.activeCamera.id;
  43622. }
  43623. // Animations
  43624. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  43625. // Materials
  43626. serializationObject.materials = [];
  43627. serializationObject.multiMaterials = [];
  43628. var material;
  43629. for (index = 0; index < scene.materials.length; index++) {
  43630. material = scene.materials[index];
  43631. if (!material.doNotSerialize) {
  43632. serializationObject.materials.push(material.serialize());
  43633. }
  43634. }
  43635. // MultiMaterials
  43636. serializationObject.multiMaterials = [];
  43637. for (index = 0; index < scene.multiMaterials.length; index++) {
  43638. var multiMaterial = scene.multiMaterials[index];
  43639. serializationObject.multiMaterials.push(multiMaterial.serialize());
  43640. }
  43641. // Skeletons
  43642. serializationObject.skeletons = [];
  43643. for (index = 0; index < scene.skeletons.length; index++) {
  43644. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  43645. }
  43646. // Geometries
  43647. serializationObject.geometries = {};
  43648. serializationObject.geometries.boxes = [];
  43649. serializationObject.geometries.spheres = [];
  43650. serializationObject.geometries.cylinders = [];
  43651. serializationObject.geometries.toruses = [];
  43652. serializationObject.geometries.grounds = [];
  43653. serializationObject.geometries.planes = [];
  43654. serializationObject.geometries.torusKnots = [];
  43655. serializationObject.geometries.vertexData = [];
  43656. serializedGeometries = [];
  43657. var geometries = scene.getGeometries();
  43658. for (index = 0; index < geometries.length; index++) {
  43659. var geometry = geometries[index];
  43660. if (geometry.isReady()) {
  43661. serializeGeometry(geometry, serializationObject.geometries);
  43662. }
  43663. }
  43664. // Meshes
  43665. serializationObject.meshes = [];
  43666. for (index = 0; index < scene.meshes.length; index++) {
  43667. var abstractMesh = scene.meshes[index];
  43668. if (abstractMesh instanceof BABYLON.Mesh) {
  43669. var mesh = abstractMesh;
  43670. if (!mesh.doNotSerialize) {
  43671. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  43672. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  43673. }
  43674. }
  43675. }
  43676. }
  43677. // Particles Systems
  43678. serializationObject.particleSystems = [];
  43679. for (index = 0; index < scene.particleSystems.length; index++) {
  43680. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  43681. }
  43682. // Lens flares
  43683. serializationObject.lensFlareSystems = [];
  43684. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  43685. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  43686. }
  43687. // Shadows
  43688. serializationObject.shadowGenerators = [];
  43689. for (index = 0; index < scene.lights.length; index++) {
  43690. light = scene.lights[index];
  43691. var shadowGenerator = light.getShadowGenerator();
  43692. // Only support serialization for official generator so far.
  43693. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  43694. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  43695. }
  43696. }
  43697. // Action Manager
  43698. if (scene.actionManager) {
  43699. serializationObject.actions = scene.actionManager.serialize("scene");
  43700. }
  43701. // Audio
  43702. serializationObject.sounds = [];
  43703. for (index = 0; index < scene.soundTracks.length; index++) {
  43704. var soundtrack = scene.soundTracks[index];
  43705. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  43706. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  43707. }
  43708. }
  43709. return serializationObject;
  43710. };
  43711. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  43712. if (withParents === void 0) { withParents = false; }
  43713. if (withChildren === void 0) { withChildren = false; }
  43714. var serializationObject = {};
  43715. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  43716. if (withParents || withChildren) {
  43717. //deliberate for loop! not for each, appended should be processed as well.
  43718. for (var i = 0; i < toSerialize.length; ++i) {
  43719. if (withChildren) {
  43720. toSerialize[i].getDescendants().forEach(function (node) {
  43721. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  43722. toSerialize.push(node);
  43723. }
  43724. });
  43725. }
  43726. //make sure the array doesn't contain the object already
  43727. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  43728. toSerialize.push(toSerialize[i].parent);
  43729. }
  43730. }
  43731. }
  43732. toSerialize.forEach(function (mesh) {
  43733. finalizeSingleMesh(mesh, serializationObject);
  43734. });
  43735. return serializationObject;
  43736. };
  43737. return SceneSerializer;
  43738. }());
  43739. BABYLON.SceneSerializer = SceneSerializer;
  43740. })(BABYLON || (BABYLON = {}));
  43741. //# sourceMappingURL=babylon.sceneSerializer.js.map
  43742. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  43743. // Huge respect for a such great lib.
  43744. // Earcut license:
  43745. // Copyright (c) 2016, Mapbox
  43746. //
  43747. // Permission to use, copy, modify, and/or distribute this software for any purpose
  43748. // with or without fee is hereby granted, provided that the above copyright notice
  43749. // and this permission notice appear in all copies.
  43750. //
  43751. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  43752. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  43753. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  43754. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  43755. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  43756. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  43757. // THIS SOFTWARE.
  43758. var Earcut;
  43759. (function (Earcut) {
  43760. /**
  43761. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  43762. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  43763. * @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).
  43764. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  43765. */
  43766. function earcut(data, holeIndices, dim) {
  43767. dim = dim || 2;
  43768. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  43769. if (!outerNode)
  43770. return triangles;
  43771. var minX, minY, maxX, maxY, x, y, size;
  43772. if (hasHoles)
  43773. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  43774. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  43775. if (data.length > 80 * dim) {
  43776. minX = maxX = data[0];
  43777. minY = maxY = data[1];
  43778. for (var i = dim; i < outerLen; i += dim) {
  43779. x = data[i];
  43780. y = data[i + 1];
  43781. if (x < minX)
  43782. minX = x;
  43783. if (y < minY)
  43784. minY = y;
  43785. if (x > maxX)
  43786. maxX = x;
  43787. if (y > maxY)
  43788. maxY = y;
  43789. }
  43790. // minX, minY and size are later used to transform coords into integers for z-order calculation
  43791. size = Math.max(maxX - minX, maxY - minY);
  43792. }
  43793. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  43794. return triangles;
  43795. }
  43796. Earcut.earcut = earcut;
  43797. // create a circular doubly linked list from polygon points in the specified winding order
  43798. function linkedList(data, start, end, dim, clockwise) {
  43799. var i, last;
  43800. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  43801. for (i = start; i < end; i += dim)
  43802. last = insertNode(i, data[i], data[i + 1], last);
  43803. }
  43804. else {
  43805. for (i = end - dim; i >= start; i -= dim)
  43806. last = insertNode(i, data[i], data[i + 1], last);
  43807. }
  43808. if (last && equals(last, last.next)) {
  43809. removeNode(last);
  43810. last = last.next;
  43811. }
  43812. return last;
  43813. }
  43814. // eliminate colinear or duplicate points
  43815. function filterPoints(start, end) {
  43816. if (!start)
  43817. return start;
  43818. if (!end)
  43819. end = start;
  43820. var p = start, again;
  43821. do {
  43822. again = false;
  43823. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  43824. removeNode(p);
  43825. p = end = p.prev;
  43826. if (p === p.next)
  43827. return null;
  43828. again = true;
  43829. }
  43830. else {
  43831. p = p.next;
  43832. }
  43833. } while (again || p !== end);
  43834. return end;
  43835. }
  43836. // main ear slicing loop which triangulates a polygon (given as a linked list)
  43837. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  43838. if (!ear)
  43839. return;
  43840. // interlink polygon nodes in z-order
  43841. if (!pass && size)
  43842. indexCurve(ear, minX, minY, size);
  43843. var stop = ear, prev, next;
  43844. // iterate through ears, slicing them one by one
  43845. while (ear.prev !== ear.next) {
  43846. prev = ear.prev;
  43847. next = ear.next;
  43848. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  43849. // cut off the triangle
  43850. triangles.push(prev.i / dim);
  43851. triangles.push(ear.i / dim);
  43852. triangles.push(next.i / dim);
  43853. removeNode(ear);
  43854. // skipping the next vertice leads to less sliver triangles
  43855. ear = next.next;
  43856. stop = next.next;
  43857. continue;
  43858. }
  43859. ear = next;
  43860. // if we looped through the whole remaining polygon and can't find any more ears
  43861. if (ear === stop) {
  43862. // try filtering points and slicing again
  43863. if (!pass) {
  43864. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  43865. }
  43866. else if (pass === 1) {
  43867. ear = cureLocalIntersections(ear, triangles, dim);
  43868. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  43869. }
  43870. else if (pass === 2) {
  43871. splitEarcut(ear, triangles, dim, minX, minY, size);
  43872. }
  43873. break;
  43874. }
  43875. }
  43876. }
  43877. // check whether a polygon node forms a valid ear with adjacent nodes
  43878. function isEar(ear) {
  43879. var a = ear.prev, b = ear, c = ear.next;
  43880. if (area(a, b, c) >= 0)
  43881. return false; // reflex, can't be an ear
  43882. // now make sure we don't have other points inside the potential ear
  43883. var p = ear.next.next;
  43884. while (p !== ear.prev) {
  43885. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43886. area(p.prev, p, p.next) >= 0)
  43887. return false;
  43888. p = p.next;
  43889. }
  43890. return true;
  43891. }
  43892. function isEarHashed(ear, minX, minY, size) {
  43893. var a = ear.prev, b = ear, c = ear.next;
  43894. if (area(a, b, c) >= 0)
  43895. return false; // reflex, can't be an ear
  43896. // triangle bbox; min & max are calculated like this for speed
  43897. 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);
  43898. // z-order range for the current triangle bbox;
  43899. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  43900. // first look for points inside the triangle in increasing z-order
  43901. var p = ear.nextZ;
  43902. while (p && p.z <= maxZ) {
  43903. if (p !== ear.prev &&
  43904. p !== ear.next &&
  43905. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43906. area(p.prev, p, p.next) >= 0)
  43907. return false;
  43908. p = p.nextZ;
  43909. }
  43910. // then look for points in decreasing z-order
  43911. p = ear.prevZ;
  43912. while (p && p.z >= minZ) {
  43913. if (p !== ear.prev &&
  43914. p !== ear.next &&
  43915. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43916. area(p.prev, p, p.next) >= 0)
  43917. return false;
  43918. p = p.prevZ;
  43919. }
  43920. return true;
  43921. }
  43922. // go through all polygon nodes and cure small local self-intersections
  43923. function cureLocalIntersections(start, triangles, dim) {
  43924. var p = start;
  43925. do {
  43926. var a = p.prev, b = p.next.next;
  43927. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  43928. triangles.push(a.i / dim);
  43929. triangles.push(p.i / dim);
  43930. triangles.push(b.i / dim);
  43931. // remove two nodes involved
  43932. removeNode(p);
  43933. removeNode(p.next);
  43934. p = start = b;
  43935. }
  43936. p = p.next;
  43937. } while (p !== start);
  43938. return p;
  43939. }
  43940. // try splitting polygon into two and triangulate them independently
  43941. function splitEarcut(start, triangles, dim, minX, minY, size) {
  43942. // look for a valid diagonal that divides the polygon into two
  43943. var a = start;
  43944. do {
  43945. var b = a.next.next;
  43946. while (b !== a.prev) {
  43947. if (a.i !== b.i && isValidDiagonal(a, b)) {
  43948. // split the polygon in two by the diagonal
  43949. var c = splitPolygon(a, b);
  43950. // filter colinear points around the cuts
  43951. a = filterPoints(a, a.next);
  43952. c = filterPoints(c, c.next);
  43953. // run earcut on each half
  43954. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  43955. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  43956. return;
  43957. }
  43958. b = b.next;
  43959. }
  43960. a = a.next;
  43961. } while (a !== start);
  43962. }
  43963. // link every hole into the outer loop, producing a single-ring polygon without holes
  43964. function eliminateHoles(data, holeIndices, outerNode, dim) {
  43965. var queue = [], i, len, start, end, list;
  43966. for (i = 0, len = holeIndices.length; i < len; i++) {
  43967. start = holeIndices[i] * dim;
  43968. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43969. list = linkedList(data, start, end, dim, false);
  43970. if (list === list.next)
  43971. list.steiner = true;
  43972. queue.push(getLeftmost(list));
  43973. }
  43974. queue.sort(compareX);
  43975. // process holes from left to right
  43976. for (i = 0; i < queue.length; i++) {
  43977. eliminateHole(queue[i], outerNode);
  43978. outerNode = filterPoints(outerNode, outerNode.next);
  43979. }
  43980. return outerNode;
  43981. }
  43982. function compareX(a, b) {
  43983. return a.x - b.x;
  43984. }
  43985. // find a bridge between vertices that connects hole with an outer ring and and link it
  43986. function eliminateHole(hole, outerNode) {
  43987. outerNode = findHoleBridge(hole, outerNode);
  43988. if (outerNode) {
  43989. var b = splitPolygon(outerNode, hole);
  43990. filterPoints(b, b.next);
  43991. }
  43992. }
  43993. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43994. function findHoleBridge(hole, outerNode) {
  43995. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  43996. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43997. // segment's endpoint with lesser x will be potential connection point
  43998. do {
  43999. if (hy <= p.y && hy >= p.next.y) {
  44000. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  44001. if (x <= hx && x > qx) {
  44002. qx = x;
  44003. if (x === hx) {
  44004. if (hy === p.y)
  44005. return p;
  44006. if (hy === p.next.y)
  44007. return p.next;
  44008. }
  44009. m = p.x < p.next.x ? p : p.next;
  44010. }
  44011. }
  44012. p = p.next;
  44013. } while (p !== outerNode);
  44014. if (!m)
  44015. return null;
  44016. if (hx === qx)
  44017. return m.prev; // hole touches outer segment; pick lower endpoint
  44018. // look for points inside the triangle of hole point, segment intersection and endpoint;
  44019. // if there are no points found, we have a valid connection;
  44020. // otherwise choose the point of the minimum angle with the ray as connection point
  44021. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  44022. p = m.next;
  44023. while (p !== stop) {
  44024. if (hx >= p.x &&
  44025. p.x >= mx &&
  44026. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  44027. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  44028. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  44029. m = p;
  44030. tanMin = tan;
  44031. }
  44032. }
  44033. p = p.next;
  44034. }
  44035. return m;
  44036. }
  44037. // interlink polygon nodes in z-order
  44038. function indexCurve(start, minX, minY, size) {
  44039. var p = start;
  44040. do {
  44041. if (p.z === null)
  44042. p.z = zOrder(p.x, p.y, minX, minY, size);
  44043. p.prevZ = p.prev;
  44044. p.nextZ = p.next;
  44045. p = p.next;
  44046. } while (p !== start);
  44047. p.prevZ.nextZ = null;
  44048. p.prevZ = null;
  44049. sortLinked(p);
  44050. }
  44051. // Simon Tatham's linked list merge sort algorithm
  44052. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  44053. function sortLinked(list) {
  44054. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  44055. do {
  44056. p = list;
  44057. list = null;
  44058. tail = null;
  44059. numMerges = 0;
  44060. while (p) {
  44061. numMerges++;
  44062. q = p;
  44063. pSize = 0;
  44064. for (i = 0; i < inSize; i++) {
  44065. pSize++;
  44066. q = q.nextZ;
  44067. if (!q)
  44068. break;
  44069. }
  44070. qSize = inSize;
  44071. while (pSize > 0 || (qSize > 0 && q)) {
  44072. if (pSize === 0) {
  44073. e = q;
  44074. q = q.nextZ;
  44075. qSize--;
  44076. }
  44077. else if (qSize === 0 || !q) {
  44078. e = p;
  44079. p = p.nextZ;
  44080. pSize--;
  44081. }
  44082. else if (p.z <= q.z) {
  44083. e = p;
  44084. p = p.nextZ;
  44085. pSize--;
  44086. }
  44087. else {
  44088. e = q;
  44089. q = q.nextZ;
  44090. qSize--;
  44091. }
  44092. if (tail)
  44093. tail.nextZ = e;
  44094. else
  44095. list = e;
  44096. e.prevZ = tail;
  44097. tail = e;
  44098. }
  44099. p = q;
  44100. }
  44101. tail.nextZ = null;
  44102. inSize *= 2;
  44103. } while (numMerges > 1);
  44104. return list;
  44105. }
  44106. // z-order of a point given coords and size of the data bounding box
  44107. function zOrder(x, y, minX, minY, size) {
  44108. // coords are transformed into non-negative 15-bit integer range
  44109. x = 32767 * (x - minX) / size;
  44110. y = 32767 * (y - minY) / size;
  44111. x = (x | (x << 8)) & 0x00FF00FF;
  44112. x = (x | (x << 4)) & 0x0F0F0F0F;
  44113. x = (x | (x << 2)) & 0x33333333;
  44114. x = (x | (x << 1)) & 0x55555555;
  44115. y = (y | (y << 8)) & 0x00FF00FF;
  44116. y = (y | (y << 4)) & 0x0F0F0F0F;
  44117. y = (y | (y << 2)) & 0x33333333;
  44118. y = (y | (y << 1)) & 0x55555555;
  44119. return x | (y << 1);
  44120. }
  44121. // find the leftmost node of a polygon ring
  44122. function getLeftmost(start) {
  44123. var p = start, leftmost = start;
  44124. do {
  44125. if (p.x < leftmost.x)
  44126. leftmost = p;
  44127. p = p.next;
  44128. } while (p !== start);
  44129. return leftmost;
  44130. }
  44131. // check if a point lies within a convex triangle
  44132. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  44133. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  44134. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  44135. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  44136. }
  44137. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  44138. function isValidDiagonal(a, b) {
  44139. return a.next.i !== b.i &&
  44140. a.prev.i !== b.i &&
  44141. !intersectsPolygon(a, b) &&
  44142. locallyInside(a, b) &&
  44143. locallyInside(b, a) &&
  44144. middleInside(a, b);
  44145. }
  44146. // signed area of a triangle
  44147. function area(p, q, r) {
  44148. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  44149. }
  44150. // check if two points are equal
  44151. function equals(p1, p2) {
  44152. return p1.x === p2.x && p1.y === p2.y;
  44153. }
  44154. // check if two segments intersect
  44155. function intersects(p1, q1, p2, q2) {
  44156. if ((equals(p1, q1) && equals(p2, q2)) ||
  44157. (equals(p1, q2) && equals(p2, q1)))
  44158. return true;
  44159. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  44160. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  44161. }
  44162. // check if a polygon diagonal intersects any polygon segments
  44163. function intersectsPolygon(a, b) {
  44164. var p = a;
  44165. do {
  44166. if (p.i !== a.i &&
  44167. p.next.i !== a.i &&
  44168. p.i !== b.i &&
  44169. p.next.i !== b.i &&
  44170. intersects(p, p.next, a, b))
  44171. return true;
  44172. p = p.next;
  44173. } while (p !== a);
  44174. return false;
  44175. }
  44176. // check if a polygon diagonal is locally inside the polygon
  44177. function locallyInside(a, b) {
  44178. return area(a.prev, a, a.next) < 0
  44179. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  44180. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  44181. }
  44182. // check if the middle point of a polygon diagonal is inside the polygon
  44183. function middleInside(a, b) {
  44184. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  44185. do {
  44186. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  44187. inside = !inside;
  44188. p = p.next;
  44189. } while (p !== a);
  44190. return inside;
  44191. }
  44192. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  44193. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  44194. function splitPolygon(a, b) {
  44195. 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;
  44196. a.next = b;
  44197. b.prev = a;
  44198. a2.next = an;
  44199. an.prev = a2;
  44200. b2.next = a2;
  44201. a2.prev = b2;
  44202. bp.next = b2;
  44203. b2.prev = bp;
  44204. return b2;
  44205. }
  44206. // create a node and optionally link it with previous one (in a circular doubly linked list)
  44207. function insertNode(i, x, y, last) {
  44208. var p = new Node(i, x, y);
  44209. if (!last) {
  44210. p.prev = p;
  44211. p.next = p;
  44212. }
  44213. else {
  44214. p.next = last.next;
  44215. p.prev = last;
  44216. last.next.prev = p;
  44217. last.next = p;
  44218. }
  44219. return p;
  44220. }
  44221. function removeNode(p) {
  44222. p.next.prev = p.prev;
  44223. p.prev.next = p.next;
  44224. if (p.prevZ)
  44225. p.prevZ.nextZ = p.nextZ;
  44226. if (p.nextZ)
  44227. p.nextZ.prevZ = p.prevZ;
  44228. }
  44229. function Node(i, x, y) {
  44230. // vertice index in coordinates array
  44231. this.i = i;
  44232. // vertex coordinates
  44233. this.x = x;
  44234. this.y = y;
  44235. // previous and next vertice nodes in a polygon ring
  44236. this.prev = null;
  44237. this.next = null;
  44238. // z-order curve value
  44239. this.z = null;
  44240. // previous and next nodes in z-order
  44241. this.prevZ = null;
  44242. this.nextZ = null;
  44243. // indicates whether this is a steiner point
  44244. this.steiner = false;
  44245. }
  44246. /**
  44247. * return a percentage difference between the polygon area and its triangulation area;
  44248. * used to verify correctness of triangulation
  44249. */
  44250. function deviation(data, holeIndices, dim, triangles) {
  44251. var hasHoles = holeIndices && holeIndices.length;
  44252. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  44253. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  44254. if (hasHoles) {
  44255. for (var i = 0, len = holeIndices.length; i < len; i++) {
  44256. var start = holeIndices[i] * dim;
  44257. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  44258. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  44259. }
  44260. }
  44261. var trianglesArea = 0;
  44262. for (i = 0; i < triangles.length; i += 3) {
  44263. var a = triangles[i] * dim;
  44264. var b = triangles[i + 1] * dim;
  44265. var c = triangles[i + 2] * dim;
  44266. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  44267. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  44268. }
  44269. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  44270. }
  44271. Earcut.deviation = deviation;
  44272. ;
  44273. function signedArea(data, start, end, dim) {
  44274. var sum = 0;
  44275. for (var i = start, j = end - dim; i < end; i += dim) {
  44276. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  44277. j = i;
  44278. }
  44279. return sum;
  44280. }
  44281. /**
  44282. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  44283. */
  44284. function flatten(data) {
  44285. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  44286. for (var i = 0; i < data.length; i++) {
  44287. for (var j = 0; j < data[i].length; j++) {
  44288. for (var d = 0; d < dim; d++)
  44289. result.vertices.push(data[i][j][d]);
  44290. }
  44291. if (i > 0) {
  44292. holeIndex += data[i - 1].length;
  44293. result.holes.push(holeIndex);
  44294. }
  44295. }
  44296. return result;
  44297. }
  44298. Earcut.flatten = flatten;
  44299. ;
  44300. })(Earcut || (Earcut = {}));
  44301. //# sourceMappingURL=babylon.earcut.js.map
  44302. var BABYLON;
  44303. (function (BABYLON) {
  44304. // Unique ID when we import meshes from Babylon to CSG
  44305. var currentCSGMeshId = 0;
  44306. // # class Vertex
  44307. // Represents a vertex of a polygon. Use your own vertex class instead of this
  44308. // one to provide additional features like texture coordinates and vertex
  44309. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  44310. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  44311. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  44312. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  44313. // is not used anywhere else.
  44314. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  44315. var Vertex = (function () {
  44316. function Vertex(pos, normal, uv) {
  44317. this.pos = pos;
  44318. this.normal = normal;
  44319. this.uv = uv;
  44320. }
  44321. Vertex.prototype.clone = function () {
  44322. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  44323. };
  44324. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  44325. // orientation of a polygon is flipped.
  44326. Vertex.prototype.flip = function () {
  44327. this.normal = this.normal.scale(-1);
  44328. };
  44329. // Create a new vertex between this vertex and `other` by linearly
  44330. // interpolating all properties using a parameter of `t`. Subclasses should
  44331. // override this to interpolate additional properties.
  44332. Vertex.prototype.interpolate = function (other, t) {
  44333. 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));
  44334. };
  44335. return Vertex;
  44336. }());
  44337. // # class Plane
  44338. // Represents a plane in 3D space.
  44339. var Plane = (function () {
  44340. function Plane(normal, w) {
  44341. this.normal = normal;
  44342. this.w = w;
  44343. }
  44344. Plane.FromPoints = function (a, b, c) {
  44345. var v0 = c.subtract(a);
  44346. var v1 = b.subtract(a);
  44347. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  44348. return null;
  44349. }
  44350. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  44351. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  44352. };
  44353. Plane.prototype.clone = function () {
  44354. return new Plane(this.normal.clone(), this.w);
  44355. };
  44356. Plane.prototype.flip = function () {
  44357. this.normal.scaleInPlace(-1);
  44358. this.w = -this.w;
  44359. };
  44360. // Split `polygon` by this plane if needed, then put the polygon or polygon
  44361. // fragments in the appropriate lists. Coplanar polygons go into either
  44362. // `coplanarFront` or `coplanarBack` depending on their orientation with
  44363. // respect to this plane. Polygons in front or in back of this plane go into
  44364. // either `front` or `back`.
  44365. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  44366. var COPLANAR = 0;
  44367. var FRONT = 1;
  44368. var BACK = 2;
  44369. var SPANNING = 3;
  44370. // Classify each point as well as the entire polygon into one of the above
  44371. // four classes.
  44372. var polygonType = 0;
  44373. var types = [];
  44374. var i;
  44375. var t;
  44376. for (i = 0; i < polygon.vertices.length; i++) {
  44377. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  44378. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  44379. polygonType |= type;
  44380. types.push(type);
  44381. }
  44382. // Put the polygon in the correct list, splitting it when necessary.
  44383. switch (polygonType) {
  44384. case COPLANAR:
  44385. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  44386. break;
  44387. case FRONT:
  44388. front.push(polygon);
  44389. break;
  44390. case BACK:
  44391. back.push(polygon);
  44392. break;
  44393. case SPANNING:
  44394. var f = [], b = [];
  44395. for (i = 0; i < polygon.vertices.length; i++) {
  44396. var j = (i + 1) % polygon.vertices.length;
  44397. var ti = types[i], tj = types[j];
  44398. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  44399. if (ti !== BACK)
  44400. f.push(vi);
  44401. if (ti !== FRONT)
  44402. b.push(ti !== BACK ? vi.clone() : vi);
  44403. if ((ti | tj) === SPANNING) {
  44404. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  44405. var v = vi.interpolate(vj, t);
  44406. f.push(v);
  44407. b.push(v.clone());
  44408. }
  44409. }
  44410. var poly;
  44411. if (f.length >= 3) {
  44412. poly = new Polygon(f, polygon.shared);
  44413. if (poly.plane)
  44414. front.push(poly);
  44415. }
  44416. if (b.length >= 3) {
  44417. poly = new Polygon(b, polygon.shared);
  44418. if (poly.plane)
  44419. back.push(poly);
  44420. }
  44421. break;
  44422. }
  44423. };
  44424. return Plane;
  44425. }());
  44426. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  44427. // point is on the plane.
  44428. Plane.EPSILON = 1e-5;
  44429. // # class Polygon
  44430. // Represents a convex polygon. The vertices used to initialize a polygon must
  44431. // be coplanar and form a convex loop.
  44432. //
  44433. // Each convex polygon has a `shared` property, which is shared between all
  44434. // polygons that are clones of each other or were split from the same polygon.
  44435. // This can be used to define per-polygon properties (such as surface color).
  44436. var Polygon = (function () {
  44437. function Polygon(vertices, shared) {
  44438. this.vertices = vertices;
  44439. this.shared = shared;
  44440. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  44441. }
  44442. Polygon.prototype.clone = function () {
  44443. var vertices = this.vertices.map(function (v) { return v.clone(); });
  44444. return new Polygon(vertices, this.shared);
  44445. };
  44446. Polygon.prototype.flip = function () {
  44447. this.vertices.reverse().map(function (v) { v.flip(); });
  44448. this.plane.flip();
  44449. };
  44450. return Polygon;
  44451. }());
  44452. // # class Node
  44453. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  44454. // by picking a polygon to split along. That polygon (and all other coplanar
  44455. // polygons) are added directly to that node and the other polygons are added to
  44456. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  44457. // no distinction between internal and leaf nodes.
  44458. var Node = (function () {
  44459. function Node(polygons) {
  44460. this.plane = null;
  44461. this.front = null;
  44462. this.back = null;
  44463. this.polygons = [];
  44464. if (polygons) {
  44465. this.build(polygons);
  44466. }
  44467. }
  44468. Node.prototype.clone = function () {
  44469. var node = new Node();
  44470. node.plane = this.plane && this.plane.clone();
  44471. node.front = this.front && this.front.clone();
  44472. node.back = this.back && this.back.clone();
  44473. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  44474. return node;
  44475. };
  44476. // Convert solid space to empty space and empty space to solid space.
  44477. Node.prototype.invert = function () {
  44478. for (var i = 0; i < this.polygons.length; i++) {
  44479. this.polygons[i].flip();
  44480. }
  44481. if (this.plane) {
  44482. this.plane.flip();
  44483. }
  44484. if (this.front) {
  44485. this.front.invert();
  44486. }
  44487. if (this.back) {
  44488. this.back.invert();
  44489. }
  44490. var temp = this.front;
  44491. this.front = this.back;
  44492. this.back = temp;
  44493. };
  44494. // Recursively remove all polygons in `polygons` that are inside this BSP
  44495. // tree.
  44496. Node.prototype.clipPolygons = function (polygons) {
  44497. if (!this.plane)
  44498. return polygons.slice();
  44499. var front = [], back = [];
  44500. for (var i = 0; i < polygons.length; i++) {
  44501. this.plane.splitPolygon(polygons[i], front, back, front, back);
  44502. }
  44503. if (this.front) {
  44504. front = this.front.clipPolygons(front);
  44505. }
  44506. if (this.back) {
  44507. back = this.back.clipPolygons(back);
  44508. }
  44509. else {
  44510. back = [];
  44511. }
  44512. return front.concat(back);
  44513. };
  44514. // Remove all polygons in this BSP tree that are inside the other BSP tree
  44515. // `bsp`.
  44516. Node.prototype.clipTo = function (bsp) {
  44517. this.polygons = bsp.clipPolygons(this.polygons);
  44518. if (this.front)
  44519. this.front.clipTo(bsp);
  44520. if (this.back)
  44521. this.back.clipTo(bsp);
  44522. };
  44523. // Return a list of all polygons in this BSP tree.
  44524. Node.prototype.allPolygons = function () {
  44525. var polygons = this.polygons.slice();
  44526. if (this.front)
  44527. polygons = polygons.concat(this.front.allPolygons());
  44528. if (this.back)
  44529. polygons = polygons.concat(this.back.allPolygons());
  44530. return polygons;
  44531. };
  44532. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  44533. // new polygons are filtered down to the bottom of the tree and become new
  44534. // nodes there. Each set of polygons is partitioned using the first polygon
  44535. // (no heuristic is used to pick a good split).
  44536. Node.prototype.build = function (polygons) {
  44537. if (!polygons.length)
  44538. return;
  44539. if (!this.plane)
  44540. this.plane = polygons[0].plane.clone();
  44541. var front = [], back = [];
  44542. for (var i = 0; i < polygons.length; i++) {
  44543. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  44544. }
  44545. if (front.length) {
  44546. if (!this.front)
  44547. this.front = new Node();
  44548. this.front.build(front);
  44549. }
  44550. if (back.length) {
  44551. if (!this.back)
  44552. this.back = new Node();
  44553. this.back.build(back);
  44554. }
  44555. };
  44556. return Node;
  44557. }());
  44558. var CSG = (function () {
  44559. function CSG() {
  44560. this.polygons = new Array();
  44561. }
  44562. // Convert BABYLON.Mesh to BABYLON.CSG
  44563. CSG.FromMesh = function (mesh) {
  44564. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  44565. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  44566. if (mesh instanceof BABYLON.Mesh) {
  44567. mesh.computeWorldMatrix(true);
  44568. matrix = mesh.getWorldMatrix();
  44569. meshPosition = mesh.position.clone();
  44570. meshRotation = mesh.rotation.clone();
  44571. if (mesh.rotationQuaternion) {
  44572. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  44573. }
  44574. meshScaling = mesh.scaling.clone();
  44575. }
  44576. else {
  44577. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  44578. }
  44579. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  44580. var subMeshes = mesh.subMeshes;
  44581. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  44582. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  44583. vertices = [];
  44584. for (var j = 0; j < 3; j++) {
  44585. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  44586. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  44587. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  44588. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  44589. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  44590. vertex = new Vertex(position, normal, uv);
  44591. vertices.push(vertex);
  44592. }
  44593. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  44594. // To handle the case of degenerated triangle
  44595. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  44596. if (polygon.plane)
  44597. polygons.push(polygon);
  44598. }
  44599. }
  44600. var csg = CSG.FromPolygons(polygons);
  44601. csg.matrix = matrix;
  44602. csg.position = meshPosition;
  44603. csg.rotation = meshRotation;
  44604. csg.scaling = meshScaling;
  44605. csg.rotationQuaternion = meshRotationQuaternion;
  44606. currentCSGMeshId++;
  44607. return csg;
  44608. };
  44609. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  44610. CSG.FromPolygons = function (polygons) {
  44611. var csg = new CSG();
  44612. csg.polygons = polygons;
  44613. return csg;
  44614. };
  44615. CSG.prototype.clone = function () {
  44616. var csg = new CSG();
  44617. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  44618. csg.copyTransformAttributes(this);
  44619. return csg;
  44620. };
  44621. CSG.prototype.toPolygons = function () {
  44622. return this.polygons;
  44623. };
  44624. CSG.prototype.union = function (csg) {
  44625. var a = new Node(this.clone().polygons);
  44626. var b = new Node(csg.clone().polygons);
  44627. a.clipTo(b);
  44628. b.clipTo(a);
  44629. b.invert();
  44630. b.clipTo(a);
  44631. b.invert();
  44632. a.build(b.allPolygons());
  44633. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44634. };
  44635. CSG.prototype.unionInPlace = function (csg) {
  44636. var a = new Node(this.polygons);
  44637. var b = new Node(csg.polygons);
  44638. a.clipTo(b);
  44639. b.clipTo(a);
  44640. b.invert();
  44641. b.clipTo(a);
  44642. b.invert();
  44643. a.build(b.allPolygons());
  44644. this.polygons = a.allPolygons();
  44645. };
  44646. CSG.prototype.subtract = function (csg) {
  44647. var a = new Node(this.clone().polygons);
  44648. var b = new Node(csg.clone().polygons);
  44649. a.invert();
  44650. a.clipTo(b);
  44651. b.clipTo(a);
  44652. b.invert();
  44653. b.clipTo(a);
  44654. b.invert();
  44655. a.build(b.allPolygons());
  44656. a.invert();
  44657. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44658. };
  44659. CSG.prototype.subtractInPlace = function (csg) {
  44660. var a = new Node(this.polygons);
  44661. var b = new Node(csg.polygons);
  44662. a.invert();
  44663. a.clipTo(b);
  44664. b.clipTo(a);
  44665. b.invert();
  44666. b.clipTo(a);
  44667. b.invert();
  44668. a.build(b.allPolygons());
  44669. a.invert();
  44670. this.polygons = a.allPolygons();
  44671. };
  44672. CSG.prototype.intersect = function (csg) {
  44673. var a = new Node(this.clone().polygons);
  44674. var b = new Node(csg.clone().polygons);
  44675. a.invert();
  44676. b.clipTo(a);
  44677. b.invert();
  44678. a.clipTo(b);
  44679. b.clipTo(a);
  44680. a.build(b.allPolygons());
  44681. a.invert();
  44682. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  44683. };
  44684. CSG.prototype.intersectInPlace = function (csg) {
  44685. var a = new Node(this.polygons);
  44686. var b = new Node(csg.polygons);
  44687. a.invert();
  44688. b.clipTo(a);
  44689. b.invert();
  44690. a.clipTo(b);
  44691. b.clipTo(a);
  44692. a.build(b.allPolygons());
  44693. a.invert();
  44694. this.polygons = a.allPolygons();
  44695. };
  44696. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  44697. // not modified.
  44698. CSG.prototype.inverse = function () {
  44699. var csg = this.clone();
  44700. csg.inverseInPlace();
  44701. return csg;
  44702. };
  44703. CSG.prototype.inverseInPlace = function () {
  44704. this.polygons.map(function (p) { p.flip(); });
  44705. };
  44706. // This is used to keep meshes transformations so they can be restored
  44707. // when we build back a Babylon Mesh
  44708. // NB : All CSG operations are performed in world coordinates
  44709. CSG.prototype.copyTransformAttributes = function (csg) {
  44710. this.matrix = csg.matrix;
  44711. this.position = csg.position;
  44712. this.rotation = csg.rotation;
  44713. this.scaling = csg.scaling;
  44714. this.rotationQuaternion = csg.rotationQuaternion;
  44715. return this;
  44716. };
  44717. // Build Raw mesh from CSG
  44718. // Coordinates here are in world space
  44719. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  44720. var matrix = this.matrix.clone();
  44721. matrix.invert();
  44722. 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;
  44723. if (keepSubMeshes) {
  44724. // Sort Polygons, since subMeshes are indices range
  44725. polygons.sort(function (a, b) {
  44726. if (a.shared.meshId === b.shared.meshId) {
  44727. return a.shared.subMeshId - b.shared.subMeshId;
  44728. }
  44729. else {
  44730. return a.shared.meshId - b.shared.meshId;
  44731. }
  44732. });
  44733. }
  44734. for (var i = 0, il = polygons.length; i < il; i++) {
  44735. polygon = polygons[i];
  44736. // Building SubMeshes
  44737. if (!subMesh_dict[polygon.shared.meshId]) {
  44738. subMesh_dict[polygon.shared.meshId] = {};
  44739. }
  44740. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  44741. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  44742. indexStart: +Infinity,
  44743. indexEnd: -Infinity,
  44744. materialIndex: polygon.shared.materialIndex
  44745. };
  44746. }
  44747. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  44748. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  44749. polygonIndices[0] = 0;
  44750. polygonIndices[1] = j - 1;
  44751. polygonIndices[2] = j;
  44752. for (var k = 0; k < 3; k++) {
  44753. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  44754. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  44755. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  44756. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  44757. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  44758. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  44759. // Check if 2 points can be merged
  44760. if (!(typeof vertex_idx !== 'undefined' &&
  44761. normals[vertex_idx * 3] === localNormal.x &&
  44762. normals[vertex_idx * 3 + 1] === localNormal.y &&
  44763. normals[vertex_idx * 3 + 2] === localNormal.z &&
  44764. uvs[vertex_idx * 2] === uv.x &&
  44765. uvs[vertex_idx * 2 + 1] === uv.y)) {
  44766. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  44767. uvs.push(uv.x, uv.y);
  44768. normals.push(normal.x, normal.y, normal.z);
  44769. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  44770. }
  44771. indices.push(vertex_idx);
  44772. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  44773. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  44774. currentIndex++;
  44775. }
  44776. }
  44777. }
  44778. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  44779. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  44780. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  44781. mesh.setIndices(indices);
  44782. if (keepSubMeshes) {
  44783. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  44784. var materialIndexOffset = 0, materialMaxIndex;
  44785. mesh.subMeshes = new Array();
  44786. for (var m in subMesh_dict) {
  44787. materialMaxIndex = -1;
  44788. for (var sm in subMesh_dict[m]) {
  44789. subMesh_obj = subMesh_dict[m][sm];
  44790. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  44791. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  44792. }
  44793. materialIndexOffset += ++materialMaxIndex;
  44794. }
  44795. }
  44796. return mesh;
  44797. };
  44798. // Build Mesh from CSG taking material and transforms into account
  44799. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  44800. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  44801. mesh.material = material;
  44802. mesh.position.copyFrom(this.position);
  44803. mesh.rotation.copyFrom(this.rotation);
  44804. if (this.rotationQuaternion) {
  44805. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  44806. }
  44807. mesh.scaling.copyFrom(this.scaling);
  44808. mesh.computeWorldMatrix(true);
  44809. return mesh;
  44810. };
  44811. return CSG;
  44812. }());
  44813. BABYLON.CSG = CSG;
  44814. })(BABYLON || (BABYLON = {}));
  44815. //# sourceMappingURL=babylon.csg.js.map
  44816. var BABYLON;
  44817. (function (BABYLON) {
  44818. var VRDistortionCorrectionPostProcess = (function (_super) {
  44819. __extends(VRDistortionCorrectionPostProcess, _super);
  44820. //ANY
  44821. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  44822. var _this = _super.call(this, name, "vrDistortionCorrection", [
  44823. 'LensCenter',
  44824. 'Scale',
  44825. 'ScaleIn',
  44826. 'HmdWarpParam'
  44827. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  44828. _this._isRightEye = isRightEye;
  44829. _this._distortionFactors = vrMetrics.distortionK;
  44830. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  44831. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  44832. _this.onSizeChangedObservable.add(function () {
  44833. _this.aspectRatio = _this.width * .5 / _this.height;
  44834. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  44835. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  44836. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  44837. });
  44838. _this.onApplyObservable.add(function (effect) {
  44839. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  44840. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  44841. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  44842. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  44843. });
  44844. return _this;
  44845. }
  44846. return VRDistortionCorrectionPostProcess;
  44847. }(BABYLON.PostProcess));
  44848. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  44849. })(BABYLON || (BABYLON = {}));
  44850. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  44851. // Mainly based on these 2 articles :
  44852. // 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
  44853. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  44854. var BABYLON;
  44855. (function (BABYLON) {
  44856. var JoystickAxis;
  44857. (function (JoystickAxis) {
  44858. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  44859. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  44860. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  44861. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  44862. var VirtualJoystick = (function () {
  44863. function VirtualJoystick(leftJoystick) {
  44864. var _this = this;
  44865. if (leftJoystick) {
  44866. this._leftJoystick = true;
  44867. }
  44868. else {
  44869. this._leftJoystick = false;
  44870. }
  44871. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  44872. VirtualJoystick._globalJoystickIndex++;
  44873. // By default left & right arrow keys are moving the X
  44874. // and up & down keys are moving the Y
  44875. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44876. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44877. this.reverseLeftRight = false;
  44878. this.reverseUpDown = false;
  44879. // collections of pointers
  44880. this._touches = new BABYLON.StringDictionary();
  44881. this.deltaPosition = BABYLON.Vector3.Zero();
  44882. this._joystickSensibility = 25;
  44883. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44884. this._rotationSpeed = 25;
  44885. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  44886. this._rotateOnAxisRelativeToMesh = false;
  44887. this._onResize = function (evt) {
  44888. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44889. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44890. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  44891. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  44892. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  44893. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  44894. };
  44895. // injecting a canvas element on top of the canvas 3D game
  44896. if (!VirtualJoystick.vjCanvas) {
  44897. window.addEventListener("resize", this._onResize, false);
  44898. VirtualJoystick.vjCanvas = document.createElement("canvas");
  44899. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44900. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44901. VirtualJoystick.vjCanvas.width = window.innerWidth;
  44902. VirtualJoystick.vjCanvas.height = window.innerHeight;
  44903. VirtualJoystick.vjCanvas.style.width = "100%";
  44904. VirtualJoystick.vjCanvas.style.height = "100%";
  44905. VirtualJoystick.vjCanvas.style.position = "absolute";
  44906. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  44907. VirtualJoystick.vjCanvas.style.top = "0px";
  44908. VirtualJoystick.vjCanvas.style.left = "0px";
  44909. VirtualJoystick.vjCanvas.style.zIndex = "5";
  44910. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  44911. // Support for jQuery PEP polyfill
  44912. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  44913. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  44914. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  44915. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44916. document.body.appendChild(VirtualJoystick.vjCanvas);
  44917. }
  44918. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  44919. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  44920. this.pressed = false;
  44921. // default joystick color
  44922. this._joystickColor = "cyan";
  44923. this._joystickPointerID = -1;
  44924. // current joystick position
  44925. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  44926. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  44927. // origin joystick position
  44928. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  44929. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  44930. this._onPointerDownHandlerRef = function (evt) {
  44931. _this._onPointerDown(evt);
  44932. };
  44933. this._onPointerMoveHandlerRef = function (evt) {
  44934. _this._onPointerMove(evt);
  44935. };
  44936. this._onPointerOutHandlerRef = function (evt) {
  44937. _this._onPointerUp(evt);
  44938. };
  44939. this._onPointerUpHandlerRef = function (evt) {
  44940. _this._onPointerUp(evt);
  44941. };
  44942. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  44943. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  44944. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  44945. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  44946. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  44947. evt.preventDefault(); // Disables system menu
  44948. }, false);
  44949. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44950. }
  44951. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  44952. this._joystickSensibility = newJoystickSensibility;
  44953. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44954. };
  44955. VirtualJoystick.prototype._onPointerDown = function (e) {
  44956. var positionOnScreenCondition;
  44957. e.preventDefault();
  44958. if (this._leftJoystick === true) {
  44959. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  44960. }
  44961. else {
  44962. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  44963. }
  44964. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  44965. // First contact will be dedicated to the virtual joystick
  44966. this._joystickPointerID = e.pointerId;
  44967. this._joystickPointerStartPos.x = e.clientX;
  44968. this._joystickPointerStartPos.y = e.clientY;
  44969. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  44970. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  44971. this._deltaJoystickVector.x = 0;
  44972. this._deltaJoystickVector.y = 0;
  44973. this.pressed = true;
  44974. this._touches.add(e.pointerId.toString(), e);
  44975. }
  44976. else {
  44977. // You can only trigger the action buttons with a joystick declared
  44978. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44979. this._action();
  44980. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44981. }
  44982. }
  44983. };
  44984. VirtualJoystick.prototype._onPointerMove = function (e) {
  44985. // If the current pointer is the one associated to the joystick (first touch contact)
  44986. if (this._joystickPointerID == e.pointerId) {
  44987. this._joystickPointerPos.x = e.clientX;
  44988. this._joystickPointerPos.y = e.clientY;
  44989. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44990. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44991. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44992. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44993. switch (this._axisTargetedByLeftAndRight) {
  44994. case JoystickAxis.X:
  44995. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44996. break;
  44997. case JoystickAxis.Y:
  44998. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44999. break;
  45000. case JoystickAxis.Z:
  45001. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  45002. break;
  45003. }
  45004. var directionUpDown = this.reverseUpDown ? 1 : -1;
  45005. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  45006. switch (this._axisTargetedByUpAndDown) {
  45007. case JoystickAxis.X:
  45008. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  45009. break;
  45010. case JoystickAxis.Y:
  45011. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  45012. break;
  45013. case JoystickAxis.Z:
  45014. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  45015. break;
  45016. }
  45017. }
  45018. else {
  45019. var data = this._touches.get(e.pointerId.toString());
  45020. if (data) {
  45021. data.x = e.clientX;
  45022. data.y = e.clientY;
  45023. }
  45024. }
  45025. };
  45026. VirtualJoystick.prototype._onPointerUp = function (e) {
  45027. if (this._joystickPointerID == e.pointerId) {
  45028. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  45029. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  45030. this._joystickPointerID = -1;
  45031. this.pressed = false;
  45032. }
  45033. else {
  45034. var touch = this._touches.get(e.pointerId.toString());
  45035. if (touch) {
  45036. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  45037. }
  45038. }
  45039. this._deltaJoystickVector.x = 0;
  45040. this._deltaJoystickVector.y = 0;
  45041. this._touches.remove(e.pointerId.toString());
  45042. };
  45043. /**
  45044. * Change the color of the virtual joystick
  45045. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  45046. */
  45047. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  45048. this._joystickColor = newColor;
  45049. };
  45050. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  45051. this._action = action;
  45052. };
  45053. // Define which axis you'd like to control for left & right
  45054. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  45055. switch (axis) {
  45056. case JoystickAxis.X:
  45057. case JoystickAxis.Y:
  45058. case JoystickAxis.Z:
  45059. this._axisTargetedByLeftAndRight = axis;
  45060. break;
  45061. default:
  45062. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  45063. break;
  45064. }
  45065. };
  45066. // Define which axis you'd like to control for up & down
  45067. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  45068. switch (axis) {
  45069. case JoystickAxis.X:
  45070. case JoystickAxis.Y:
  45071. case JoystickAxis.Z:
  45072. this._axisTargetedByUpAndDown = axis;
  45073. break;
  45074. default:
  45075. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  45076. break;
  45077. }
  45078. };
  45079. VirtualJoystick.prototype._clearCanvas = function () {
  45080. if (this._leftJoystick) {
  45081. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  45082. }
  45083. else {
  45084. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  45085. }
  45086. };
  45087. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  45088. var _this = this;
  45089. if (this.pressed) {
  45090. this._touches.forEach(function (key, touch) {
  45091. if (touch.pointerId === _this._joystickPointerID) {
  45092. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  45093. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  45094. VirtualJoystick.vjCanvasContext.beginPath();
  45095. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  45096. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  45097. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  45098. VirtualJoystick.vjCanvasContext.stroke();
  45099. VirtualJoystick.vjCanvasContext.closePath();
  45100. VirtualJoystick.vjCanvasContext.beginPath();
  45101. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  45102. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  45103. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  45104. VirtualJoystick.vjCanvasContext.stroke();
  45105. VirtualJoystick.vjCanvasContext.closePath();
  45106. VirtualJoystick.vjCanvasContext.beginPath();
  45107. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  45108. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  45109. VirtualJoystick.vjCanvasContext.stroke();
  45110. VirtualJoystick.vjCanvasContext.closePath();
  45111. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  45112. }
  45113. else {
  45114. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  45115. VirtualJoystick.vjCanvasContext.beginPath();
  45116. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  45117. VirtualJoystick.vjCanvasContext.beginPath();
  45118. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  45119. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  45120. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  45121. VirtualJoystick.vjCanvasContext.stroke();
  45122. VirtualJoystick.vjCanvasContext.closePath();
  45123. touch.prevX = touch.x;
  45124. touch.prevY = touch.y;
  45125. }
  45126. ;
  45127. });
  45128. }
  45129. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  45130. };
  45131. VirtualJoystick.prototype.releaseCanvas = function () {
  45132. if (VirtualJoystick.vjCanvas) {
  45133. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  45134. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  45135. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  45136. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  45137. window.removeEventListener("resize", this._onResize);
  45138. document.body.removeChild(VirtualJoystick.vjCanvas);
  45139. VirtualJoystick.vjCanvas = null;
  45140. }
  45141. };
  45142. return VirtualJoystick;
  45143. }());
  45144. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  45145. VirtualJoystick._globalJoystickIndex = 0;
  45146. BABYLON.VirtualJoystick = VirtualJoystick;
  45147. })(BABYLON || (BABYLON = {}));
  45148. //# sourceMappingURL=babylon.virtualJoystick.js.map
  45149. var BABYLON;
  45150. (function (BABYLON) {
  45151. // We're mainly based on the logic defined into the FreeCamera code
  45152. var VirtualJoysticksCamera = (function (_super) {
  45153. __extends(VirtualJoysticksCamera, _super);
  45154. function VirtualJoysticksCamera(name, position, scene) {
  45155. var _this = _super.call(this, name, position, scene) || this;
  45156. _this.inputs.addVirtualJoystick();
  45157. return _this;
  45158. }
  45159. VirtualJoysticksCamera.prototype.getClassName = function () {
  45160. return "VirtualJoysticksCamera";
  45161. };
  45162. return VirtualJoysticksCamera;
  45163. }(BABYLON.FreeCamera));
  45164. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  45165. })(BABYLON || (BABYLON = {}));
  45166. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  45167. var BABYLON;
  45168. (function (BABYLON) {
  45169. var FreeCameraVirtualJoystickInput = (function () {
  45170. function FreeCameraVirtualJoystickInput() {
  45171. }
  45172. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  45173. return this._leftjoystick;
  45174. };
  45175. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  45176. return this._rightjoystick;
  45177. };
  45178. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  45179. if (this._leftjoystick) {
  45180. var camera = this.camera;
  45181. var speed = camera._computeLocalCameraSpeed() * 50;
  45182. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  45183. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  45184. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  45185. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  45186. if (!this._leftjoystick.pressed) {
  45187. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  45188. }
  45189. if (!this._rightjoystick.pressed) {
  45190. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  45191. }
  45192. }
  45193. };
  45194. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  45195. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  45196. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  45197. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  45198. this._leftjoystick.setJoystickSensibility(0.15);
  45199. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  45200. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  45201. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  45202. this._rightjoystick.reverseUpDown = true;
  45203. this._rightjoystick.setJoystickSensibility(0.05);
  45204. this._rightjoystick.setJoystickColor("yellow");
  45205. };
  45206. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  45207. this._leftjoystick.releaseCanvas();
  45208. this._rightjoystick.releaseCanvas();
  45209. };
  45210. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  45211. return "FreeCameraVirtualJoystickInput";
  45212. };
  45213. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  45214. return "virtualJoystick";
  45215. };
  45216. return FreeCameraVirtualJoystickInput;
  45217. }());
  45218. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  45219. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  45220. })(BABYLON || (BABYLON = {}));
  45221. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  45222. var BABYLON;
  45223. (function (BABYLON) {
  45224. var AnaglyphPostProcess = (function (_super) {
  45225. __extends(AnaglyphPostProcess, _super);
  45226. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  45227. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  45228. _this._passedProcess = rigCameras[0]._rigPostProcess;
  45229. _this.onApplyObservable.add(function (effect) {
  45230. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  45231. });
  45232. return _this;
  45233. }
  45234. return AnaglyphPostProcess;
  45235. }(BABYLON.PostProcess));
  45236. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  45237. })(BABYLON || (BABYLON = {}));
  45238. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  45239. var BABYLON;
  45240. (function (BABYLON) {
  45241. var OutlineRenderer = (function () {
  45242. function OutlineRenderer(scene) {
  45243. this._scene = scene;
  45244. }
  45245. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  45246. var _this = this;
  45247. if (useOverlay === void 0) { useOverlay = false; }
  45248. var scene = this._scene;
  45249. var engine = this._scene.getEngine();
  45250. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  45251. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  45252. return;
  45253. }
  45254. var mesh = subMesh.getRenderingMesh();
  45255. var material = subMesh.getMaterial();
  45256. engine.enableEffect(this._effect);
  45257. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  45258. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  45259. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  45260. // Bones
  45261. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45262. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  45263. }
  45264. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  45265. // Alpha test
  45266. if (material && material.needAlphaTesting()) {
  45267. var alphaTexture = material.getAlphaTestTexture();
  45268. this._effect.setTexture("diffuseSampler", alphaTexture);
  45269. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  45270. }
  45271. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  45272. };
  45273. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  45274. var defines = [];
  45275. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  45276. var mesh = subMesh.getMesh();
  45277. var material = subMesh.getMaterial();
  45278. // Alpha test
  45279. if (material && material.needAlphaTesting()) {
  45280. defines.push("#define ALPHATEST");
  45281. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  45282. attribs.push(BABYLON.VertexBuffer.UVKind);
  45283. defines.push("#define UV1");
  45284. }
  45285. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  45286. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45287. defines.push("#define UV2");
  45288. }
  45289. }
  45290. // Bones
  45291. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  45292. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  45293. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  45294. if (mesh.numBoneInfluencers > 4) {
  45295. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  45296. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  45297. }
  45298. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  45299. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  45300. }
  45301. else {
  45302. defines.push("#define NUM_BONE_INFLUENCERS 0");
  45303. }
  45304. // Instances
  45305. if (useInstances) {
  45306. defines.push("#define INSTANCES");
  45307. attribs.push("world0");
  45308. attribs.push("world1");
  45309. attribs.push("world2");
  45310. attribs.push("world3");
  45311. }
  45312. // Get correct effect
  45313. var join = defines.join("\n");
  45314. if (this._cachedDefines !== join) {
  45315. this._cachedDefines = join;
  45316. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  45317. }
  45318. return this._effect.isReady();
  45319. };
  45320. return OutlineRenderer;
  45321. }());
  45322. BABYLON.OutlineRenderer = OutlineRenderer;
  45323. })(BABYLON || (BABYLON = {}));
  45324. //# sourceMappingURL=babylon.outlineRenderer.js.map
  45325. var BABYLON;
  45326. (function (BABYLON) {
  45327. var MeshAssetTask = (function () {
  45328. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  45329. this.name = name;
  45330. this.meshesNames = meshesNames;
  45331. this.rootUrl = rootUrl;
  45332. this.sceneFilename = sceneFilename;
  45333. this.isCompleted = false;
  45334. }
  45335. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45336. var _this = this;
  45337. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  45338. _this.loadedMeshes = meshes;
  45339. _this.loadedParticleSystems = particleSystems;
  45340. _this.loadedSkeletons = skeletons;
  45341. _this.isCompleted = true;
  45342. if (_this.onSuccess) {
  45343. _this.onSuccess(_this);
  45344. }
  45345. onSuccess();
  45346. }, null, function () {
  45347. if (_this.onError) {
  45348. _this.onError(_this);
  45349. }
  45350. onError();
  45351. });
  45352. };
  45353. return MeshAssetTask;
  45354. }());
  45355. BABYLON.MeshAssetTask = MeshAssetTask;
  45356. var TextFileAssetTask = (function () {
  45357. function TextFileAssetTask(name, url) {
  45358. this.name = name;
  45359. this.url = url;
  45360. this.isCompleted = false;
  45361. }
  45362. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45363. var _this = this;
  45364. BABYLON.Tools.LoadFile(this.url, function (data) {
  45365. _this.text = data;
  45366. _this.isCompleted = true;
  45367. if (_this.onSuccess) {
  45368. _this.onSuccess(_this);
  45369. }
  45370. onSuccess();
  45371. }, null, scene.database, false, function () {
  45372. if (_this.onError) {
  45373. _this.onError(_this);
  45374. }
  45375. onError();
  45376. });
  45377. };
  45378. return TextFileAssetTask;
  45379. }());
  45380. BABYLON.TextFileAssetTask = TextFileAssetTask;
  45381. var BinaryFileAssetTask = (function () {
  45382. function BinaryFileAssetTask(name, url) {
  45383. this.name = name;
  45384. this.url = url;
  45385. this.isCompleted = false;
  45386. }
  45387. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45388. var _this = this;
  45389. BABYLON.Tools.LoadFile(this.url, function (data) {
  45390. _this.data = data;
  45391. _this.isCompleted = true;
  45392. if (_this.onSuccess) {
  45393. _this.onSuccess(_this);
  45394. }
  45395. onSuccess();
  45396. }, null, scene.database, true, function () {
  45397. if (_this.onError) {
  45398. _this.onError(_this);
  45399. }
  45400. onError();
  45401. });
  45402. };
  45403. return BinaryFileAssetTask;
  45404. }());
  45405. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  45406. var ImageAssetTask = (function () {
  45407. function ImageAssetTask(name, url) {
  45408. this.name = name;
  45409. this.url = url;
  45410. this.isCompleted = false;
  45411. }
  45412. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45413. var _this = this;
  45414. var img = new Image();
  45415. BABYLON.Tools.SetCorsBehavior(this.url, img);
  45416. img.onload = function () {
  45417. _this.image = img;
  45418. _this.isCompleted = true;
  45419. if (_this.onSuccess) {
  45420. _this.onSuccess(_this);
  45421. }
  45422. onSuccess();
  45423. };
  45424. img.onerror = function () {
  45425. if (_this.onError) {
  45426. _this.onError(_this);
  45427. }
  45428. onError();
  45429. };
  45430. img.src = this.url;
  45431. };
  45432. return ImageAssetTask;
  45433. }());
  45434. BABYLON.ImageAssetTask = ImageAssetTask;
  45435. var TextureAssetTask = (function () {
  45436. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  45437. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45438. this.name = name;
  45439. this.url = url;
  45440. this.noMipmap = noMipmap;
  45441. this.invertY = invertY;
  45442. this.samplingMode = samplingMode;
  45443. this.isCompleted = false;
  45444. }
  45445. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45446. var _this = this;
  45447. var onload = function () {
  45448. _this.isCompleted = true;
  45449. if (_this.onSuccess) {
  45450. _this.onSuccess(_this);
  45451. }
  45452. onSuccess();
  45453. };
  45454. var onerror = function () {
  45455. if (_this.onError) {
  45456. _this.onError(_this);
  45457. }
  45458. onError();
  45459. };
  45460. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  45461. };
  45462. return TextureAssetTask;
  45463. }());
  45464. BABYLON.TextureAssetTask = TextureAssetTask;
  45465. var CubeTextureAssetTask = (function () {
  45466. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  45467. this.name = name;
  45468. this.url = url;
  45469. this.extensions = extensions;
  45470. this.noMipmap = noMipmap;
  45471. this.files = files;
  45472. this.isCompleted = false;
  45473. }
  45474. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45475. var _this = this;
  45476. var onload = function () {
  45477. _this.isCompleted = true;
  45478. if (_this.onSuccess) {
  45479. _this.onSuccess(_this);
  45480. }
  45481. onSuccess();
  45482. };
  45483. var onerror = function () {
  45484. if (_this.onError) {
  45485. _this.onError(_this);
  45486. }
  45487. onError();
  45488. };
  45489. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  45490. };
  45491. return CubeTextureAssetTask;
  45492. }());
  45493. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  45494. var HDRCubeTextureAssetTask = (function () {
  45495. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  45496. if (noMipmap === void 0) { noMipmap = false; }
  45497. if (generateHarmonics === void 0) { generateHarmonics = true; }
  45498. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  45499. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  45500. this.name = name;
  45501. this.url = url;
  45502. this.size = size;
  45503. this.noMipmap = noMipmap;
  45504. this.generateHarmonics = generateHarmonics;
  45505. this.useInGammaSpace = useInGammaSpace;
  45506. this.usePMREMGenerator = usePMREMGenerator;
  45507. this.isCompleted = false;
  45508. }
  45509. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  45510. var _this = this;
  45511. var onload = function () {
  45512. _this.isCompleted = true;
  45513. if (_this.onSuccess) {
  45514. _this.onSuccess(_this);
  45515. }
  45516. onSuccess();
  45517. };
  45518. var onerror = function () {
  45519. if (_this.onError) {
  45520. _this.onError(_this);
  45521. }
  45522. onError();
  45523. };
  45524. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  45525. };
  45526. return HDRCubeTextureAssetTask;
  45527. }());
  45528. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  45529. var AssetsManager = (function () {
  45530. function AssetsManager(scene) {
  45531. this.tasks = new Array();
  45532. this.waitingTasksCount = 0;
  45533. this.useDefaultLoadingScreen = true;
  45534. this._scene = scene;
  45535. }
  45536. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  45537. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  45538. this.tasks.push(task);
  45539. return task;
  45540. };
  45541. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  45542. var task = new TextFileAssetTask(taskName, url);
  45543. this.tasks.push(task);
  45544. return task;
  45545. };
  45546. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  45547. var task = new BinaryFileAssetTask(taskName, url);
  45548. this.tasks.push(task);
  45549. return task;
  45550. };
  45551. AssetsManager.prototype.addImageTask = function (taskName, url) {
  45552. var task = new ImageAssetTask(taskName, url);
  45553. this.tasks.push(task);
  45554. return task;
  45555. };
  45556. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  45557. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45558. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  45559. this.tasks.push(task);
  45560. return task;
  45561. };
  45562. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  45563. this.waitingTasksCount--;
  45564. if (this.waitingTasksCount === 0) {
  45565. if (this.onFinish) {
  45566. this.onFinish(this.tasks);
  45567. }
  45568. this._scene.getEngine().hideLoadingUI();
  45569. }
  45570. };
  45571. AssetsManager.prototype._runTask = function (task) {
  45572. var _this = this;
  45573. task.run(this._scene, function () {
  45574. if (_this.onTaskSuccess) {
  45575. _this.onTaskSuccess(task);
  45576. }
  45577. _this._decreaseWaitingTasksCount();
  45578. }, function () {
  45579. if (_this.onTaskError) {
  45580. _this.onTaskError(task);
  45581. }
  45582. _this._decreaseWaitingTasksCount();
  45583. });
  45584. };
  45585. AssetsManager.prototype.reset = function () {
  45586. this.tasks = new Array();
  45587. return this;
  45588. };
  45589. AssetsManager.prototype.load = function () {
  45590. this.waitingTasksCount = this.tasks.length;
  45591. if (this.waitingTasksCount === 0) {
  45592. if (this.onFinish) {
  45593. this.onFinish(this.tasks);
  45594. }
  45595. return this;
  45596. }
  45597. if (this.useDefaultLoadingScreen) {
  45598. this._scene.getEngine().displayLoadingUI();
  45599. }
  45600. for (var index = 0; index < this.tasks.length; index++) {
  45601. var task = this.tasks[index];
  45602. this._runTask(task);
  45603. }
  45604. return this;
  45605. };
  45606. return AssetsManager;
  45607. }());
  45608. BABYLON.AssetsManager = AssetsManager;
  45609. })(BABYLON || (BABYLON = {}));
  45610. //# sourceMappingURL=babylon.assetsManager.js.map
  45611. var BABYLON;
  45612. (function (BABYLON) {
  45613. var VRCameraMetrics = (function () {
  45614. function VRCameraMetrics() {
  45615. this.compensateDistortion = true;
  45616. }
  45617. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  45618. get: function () {
  45619. return this.hResolution / (2 * this.vResolution);
  45620. },
  45621. enumerable: true,
  45622. configurable: true
  45623. });
  45624. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  45625. get: function () {
  45626. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  45627. },
  45628. enumerable: true,
  45629. configurable: true
  45630. });
  45631. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  45632. get: function () {
  45633. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45634. var h = (4 * meters) / this.hScreenSize;
  45635. return BABYLON.Matrix.Translation(h, 0, 0);
  45636. },
  45637. enumerable: true,
  45638. configurable: true
  45639. });
  45640. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  45641. get: function () {
  45642. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  45643. var h = (4 * meters) / this.hScreenSize;
  45644. return BABYLON.Matrix.Translation(-h, 0, 0);
  45645. },
  45646. enumerable: true,
  45647. configurable: true
  45648. });
  45649. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  45650. get: function () {
  45651. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  45652. },
  45653. enumerable: true,
  45654. configurable: true
  45655. });
  45656. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  45657. get: function () {
  45658. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  45659. },
  45660. enumerable: true,
  45661. configurable: true
  45662. });
  45663. VRCameraMetrics.GetDefault = function () {
  45664. var result = new VRCameraMetrics();
  45665. result.hResolution = 1280;
  45666. result.vResolution = 800;
  45667. result.hScreenSize = 0.149759993;
  45668. result.vScreenSize = 0.0935999975;
  45669. result.vScreenCenter = 0.0467999987;
  45670. result.eyeToScreenDistance = 0.0410000011;
  45671. result.lensSeparationDistance = 0.0635000020;
  45672. result.interpupillaryDistance = 0.0640000030;
  45673. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  45674. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  45675. result.postProcessScaleFactor = 1.714605507808412;
  45676. result.lensCenterOffset = 0.151976421;
  45677. return result;
  45678. };
  45679. return VRCameraMetrics;
  45680. }());
  45681. BABYLON.VRCameraMetrics = VRCameraMetrics;
  45682. })(BABYLON || (BABYLON = {}));
  45683. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  45684. var BABYLON;
  45685. (function (BABYLON) {
  45686. var WebVRFreeCamera = (function (_super) {
  45687. __extends(WebVRFreeCamera, _super);
  45688. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  45689. if (compensateDistortion === void 0) { compensateDistortion = false; }
  45690. if (webVROptions === void 0) { webVROptions = {}; }
  45691. var _this = _super.call(this, name, position, scene) || this;
  45692. _this.webVROptions = webVROptions;
  45693. _this._vrDevice = null;
  45694. _this._cacheState = null;
  45695. _this._vrEnabled = false;
  45696. _this._attached = false;
  45697. //using the position provided as the current position offset
  45698. _this._positionOffset = position;
  45699. //enable VR
  45700. _this.getEngine().initWebVR();
  45701. if (!_this.getEngine().vrDisplaysPromise) {
  45702. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  45703. }
  45704. else {
  45705. //TODO get the metrics updated using the device's eye parameters!
  45706. //TODO also check that the device has the right capabilities!
  45707. _this._frameData = new VRFrameData();
  45708. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  45709. if (devices.length > 0) {
  45710. _this._vrEnabled = true;
  45711. if (_this.webVROptions.displayName) {
  45712. var found = devices.some(function (device) {
  45713. if (device.displayName === _this.webVROptions.displayName) {
  45714. _this._vrDevice = device;
  45715. return true;
  45716. }
  45717. else {
  45718. return false;
  45719. }
  45720. });
  45721. if (!found) {
  45722. _this._vrDevice = devices[0];
  45723. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  45724. }
  45725. }
  45726. else {
  45727. //choose the first one
  45728. _this._vrDevice = devices[0];
  45729. }
  45730. //reset the rig parameters.
  45731. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  45732. if (_this._attached) {
  45733. _this.getEngine().enableVR(_this._vrDevice);
  45734. }
  45735. }
  45736. else {
  45737. BABYLON.Tools.Error("No WebVR devices found!");
  45738. }
  45739. });
  45740. }
  45741. _this.rotationQuaternion = new BABYLON.Quaternion();
  45742. _this._quaternionCache = new BABYLON.Quaternion();
  45743. return _this;
  45744. }
  45745. WebVRFreeCamera.prototype._checkInputs = function () {
  45746. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  45747. var currentPost = this._frameData.pose;
  45748. //make sure we have data
  45749. if (currentPost && currentPost.orientation) {
  45750. this._cacheState = currentPost;
  45751. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  45752. if (this.webVROptions.trackPosition && this._cacheState.position) {
  45753. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  45754. //scale the position accordingly
  45755. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  45756. //add the position offset
  45757. this.position.addInPlace(this._positionOffset);
  45758. }
  45759. }
  45760. }
  45761. _super.prototype._checkInputs.call(this);
  45762. };
  45763. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  45764. _super.prototype.attachControl.call(this, element, noPreventDefault);
  45765. this._attached = true;
  45766. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  45767. if (this._vrEnabled) {
  45768. this.getEngine().enableVR(this._vrDevice);
  45769. }
  45770. };
  45771. WebVRFreeCamera.prototype.detachControl = function (element) {
  45772. _super.prototype.detachControl.call(this, element);
  45773. this._vrEnabled = false;
  45774. this._attached = false;
  45775. this.getEngine().disableVR();
  45776. };
  45777. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  45778. //Backwards comp.
  45779. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  45780. //this.getEngine().switchFullscreen(requestPointerlock);
  45781. };
  45782. WebVRFreeCamera.prototype.getClassName = function () {
  45783. return "WebVRFreeCamera";
  45784. };
  45785. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  45786. //uses the vrDisplay's "resetPose()".
  45787. //pitch and roll won't be affected.
  45788. this._vrDevice.resetPose();
  45789. };
  45790. /**
  45791. *
  45792. * Set the position offset of the VR camera
  45793. * The offset will be added to the WebVR pose, after scaling it (if set).
  45794. *
  45795. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  45796. *
  45797. * @memberOf WebVRFreeCamera
  45798. */
  45799. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  45800. if (newPosition) {
  45801. this._positionOffset = newPosition;
  45802. }
  45803. else {
  45804. this._positionOffset.copyFrom(this.position);
  45805. }
  45806. };
  45807. return WebVRFreeCamera;
  45808. }(BABYLON.FreeCamera));
  45809. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  45810. })(BABYLON || (BABYLON = {}));
  45811. //# sourceMappingURL=babylon.webVRCamera.js.map
  45812. var BABYLON;
  45813. (function (BABYLON) {
  45814. // Standard optimizations
  45815. var SceneOptimization = (function () {
  45816. function SceneOptimization(priority) {
  45817. if (priority === void 0) { priority = 0; }
  45818. this.priority = priority;
  45819. this.apply = function (scene) {
  45820. return true; // Return true if everything that can be done was applied
  45821. };
  45822. }
  45823. return SceneOptimization;
  45824. }());
  45825. BABYLON.SceneOptimization = SceneOptimization;
  45826. var TextureOptimization = (function (_super) {
  45827. __extends(TextureOptimization, _super);
  45828. function TextureOptimization(priority, maximumSize) {
  45829. if (priority === void 0) { priority = 0; }
  45830. if (maximumSize === void 0) { maximumSize = 1024; }
  45831. var _this = _super.call(this, priority) || this;
  45832. _this.priority = priority;
  45833. _this.maximumSize = maximumSize;
  45834. _this.apply = function (scene) {
  45835. var allDone = true;
  45836. for (var index = 0; index < scene.textures.length; index++) {
  45837. var texture = scene.textures[index];
  45838. if (!texture.canRescale) {
  45839. continue;
  45840. }
  45841. var currentSize = texture.getSize();
  45842. var maxDimension = Math.max(currentSize.width, currentSize.height);
  45843. if (maxDimension > _this.maximumSize) {
  45844. texture.scale(0.5);
  45845. allDone = false;
  45846. }
  45847. }
  45848. return allDone;
  45849. };
  45850. return _this;
  45851. }
  45852. return TextureOptimization;
  45853. }(SceneOptimization));
  45854. BABYLON.TextureOptimization = TextureOptimization;
  45855. var HardwareScalingOptimization = (function (_super) {
  45856. __extends(HardwareScalingOptimization, _super);
  45857. function HardwareScalingOptimization(priority, maximumScale) {
  45858. if (priority === void 0) { priority = 0; }
  45859. if (maximumScale === void 0) { maximumScale = 2; }
  45860. var _this = _super.call(this, priority) || this;
  45861. _this.priority = priority;
  45862. _this.maximumScale = maximumScale;
  45863. _this._currentScale = 1;
  45864. _this.apply = function (scene) {
  45865. _this._currentScale++;
  45866. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  45867. return _this._currentScale >= _this.maximumScale;
  45868. };
  45869. return _this;
  45870. }
  45871. return HardwareScalingOptimization;
  45872. }(SceneOptimization));
  45873. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  45874. var ShadowsOptimization = (function (_super) {
  45875. __extends(ShadowsOptimization, _super);
  45876. function ShadowsOptimization() {
  45877. var _this = _super.apply(this, arguments) || this;
  45878. _this.apply = function (scene) {
  45879. scene.shadowsEnabled = false;
  45880. return true;
  45881. };
  45882. return _this;
  45883. }
  45884. return ShadowsOptimization;
  45885. }(SceneOptimization));
  45886. BABYLON.ShadowsOptimization = ShadowsOptimization;
  45887. var PostProcessesOptimization = (function (_super) {
  45888. __extends(PostProcessesOptimization, _super);
  45889. function PostProcessesOptimization() {
  45890. var _this = _super.apply(this, arguments) || this;
  45891. _this.apply = function (scene) {
  45892. scene.postProcessesEnabled = false;
  45893. return true;
  45894. };
  45895. return _this;
  45896. }
  45897. return PostProcessesOptimization;
  45898. }(SceneOptimization));
  45899. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  45900. var LensFlaresOptimization = (function (_super) {
  45901. __extends(LensFlaresOptimization, _super);
  45902. function LensFlaresOptimization() {
  45903. var _this = _super.apply(this, arguments) || this;
  45904. _this.apply = function (scene) {
  45905. scene.lensFlaresEnabled = false;
  45906. return true;
  45907. };
  45908. return _this;
  45909. }
  45910. return LensFlaresOptimization;
  45911. }(SceneOptimization));
  45912. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  45913. var ParticlesOptimization = (function (_super) {
  45914. __extends(ParticlesOptimization, _super);
  45915. function ParticlesOptimization() {
  45916. var _this = _super.apply(this, arguments) || this;
  45917. _this.apply = function (scene) {
  45918. scene.particlesEnabled = false;
  45919. return true;
  45920. };
  45921. return _this;
  45922. }
  45923. return ParticlesOptimization;
  45924. }(SceneOptimization));
  45925. BABYLON.ParticlesOptimization = ParticlesOptimization;
  45926. var RenderTargetsOptimization = (function (_super) {
  45927. __extends(RenderTargetsOptimization, _super);
  45928. function RenderTargetsOptimization() {
  45929. var _this = _super.apply(this, arguments) || this;
  45930. _this.apply = function (scene) {
  45931. scene.renderTargetsEnabled = false;
  45932. return true;
  45933. };
  45934. return _this;
  45935. }
  45936. return RenderTargetsOptimization;
  45937. }(SceneOptimization));
  45938. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  45939. var MergeMeshesOptimization = (function (_super) {
  45940. __extends(MergeMeshesOptimization, _super);
  45941. function MergeMeshesOptimization() {
  45942. var _this = _super.apply(this, arguments) || this;
  45943. _this._canBeMerged = function (abstractMesh) {
  45944. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  45945. return false;
  45946. }
  45947. var mesh = abstractMesh;
  45948. if (!mesh.isVisible || !mesh.isEnabled()) {
  45949. return false;
  45950. }
  45951. if (mesh.instances.length > 0) {
  45952. return false;
  45953. }
  45954. if (mesh.skeleton || mesh.hasLODLevels) {
  45955. return false;
  45956. }
  45957. if (mesh.parent) {
  45958. return false;
  45959. }
  45960. return true;
  45961. };
  45962. _this.apply = function (scene, updateSelectionTree) {
  45963. var globalPool = scene.meshes.slice(0);
  45964. var globalLength = globalPool.length;
  45965. for (var index = 0; index < globalLength; index++) {
  45966. var currentPool = new Array();
  45967. var current = globalPool[index];
  45968. // Checks
  45969. if (!_this._canBeMerged(current)) {
  45970. continue;
  45971. }
  45972. currentPool.push(current);
  45973. // Find compatible meshes
  45974. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  45975. var otherMesh = globalPool[subIndex];
  45976. if (!_this._canBeMerged(otherMesh)) {
  45977. continue;
  45978. }
  45979. if (otherMesh.material !== current.material) {
  45980. continue;
  45981. }
  45982. if (otherMesh.checkCollisions !== current.checkCollisions) {
  45983. continue;
  45984. }
  45985. currentPool.push(otherMesh);
  45986. globalLength--;
  45987. globalPool.splice(subIndex, 1);
  45988. subIndex--;
  45989. }
  45990. if (currentPool.length < 2) {
  45991. continue;
  45992. }
  45993. // Merge meshes
  45994. BABYLON.Mesh.MergeMeshes(currentPool);
  45995. }
  45996. if (updateSelectionTree != undefined) {
  45997. if (updateSelectionTree) {
  45998. scene.createOrUpdateSelectionOctree();
  45999. }
  46000. }
  46001. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  46002. scene.createOrUpdateSelectionOctree();
  46003. }
  46004. return true;
  46005. };
  46006. return _this;
  46007. }
  46008. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  46009. get: function () {
  46010. return MergeMeshesOptimization._UpdateSelectionTree;
  46011. },
  46012. set: function (value) {
  46013. MergeMeshesOptimization._UpdateSelectionTree = value;
  46014. },
  46015. enumerable: true,
  46016. configurable: true
  46017. });
  46018. return MergeMeshesOptimization;
  46019. }(SceneOptimization));
  46020. MergeMeshesOptimization._UpdateSelectionTree = false;
  46021. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  46022. // Options
  46023. var SceneOptimizerOptions = (function () {
  46024. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  46025. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  46026. if (trackerDuration === void 0) { trackerDuration = 2000; }
  46027. this.targetFrameRate = targetFrameRate;
  46028. this.trackerDuration = trackerDuration;
  46029. this.optimizations = new Array();
  46030. }
  46031. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  46032. var result = new SceneOptimizerOptions(targetFrameRate);
  46033. var priority = 0;
  46034. result.optimizations.push(new MergeMeshesOptimization(priority));
  46035. result.optimizations.push(new ShadowsOptimization(priority));
  46036. result.optimizations.push(new LensFlaresOptimization(priority));
  46037. // Next priority
  46038. priority++;
  46039. result.optimizations.push(new PostProcessesOptimization(priority));
  46040. result.optimizations.push(new ParticlesOptimization(priority));
  46041. // Next priority
  46042. priority++;
  46043. result.optimizations.push(new TextureOptimization(priority, 1024));
  46044. return result;
  46045. };
  46046. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  46047. var result = new SceneOptimizerOptions(targetFrameRate);
  46048. var priority = 0;
  46049. result.optimizations.push(new MergeMeshesOptimization(priority));
  46050. result.optimizations.push(new ShadowsOptimization(priority));
  46051. result.optimizations.push(new LensFlaresOptimization(priority));
  46052. // Next priority
  46053. priority++;
  46054. result.optimizations.push(new PostProcessesOptimization(priority));
  46055. result.optimizations.push(new ParticlesOptimization(priority));
  46056. // Next priority
  46057. priority++;
  46058. result.optimizations.push(new TextureOptimization(priority, 512));
  46059. // Next priority
  46060. priority++;
  46061. result.optimizations.push(new RenderTargetsOptimization(priority));
  46062. // Next priority
  46063. priority++;
  46064. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  46065. return result;
  46066. };
  46067. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  46068. var result = new SceneOptimizerOptions(targetFrameRate);
  46069. var priority = 0;
  46070. result.optimizations.push(new MergeMeshesOptimization(priority));
  46071. result.optimizations.push(new ShadowsOptimization(priority));
  46072. result.optimizations.push(new LensFlaresOptimization(priority));
  46073. // Next priority
  46074. priority++;
  46075. result.optimizations.push(new PostProcessesOptimization(priority));
  46076. result.optimizations.push(new ParticlesOptimization(priority));
  46077. // Next priority
  46078. priority++;
  46079. result.optimizations.push(new TextureOptimization(priority, 256));
  46080. // Next priority
  46081. priority++;
  46082. result.optimizations.push(new RenderTargetsOptimization(priority));
  46083. // Next priority
  46084. priority++;
  46085. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  46086. return result;
  46087. };
  46088. return SceneOptimizerOptions;
  46089. }());
  46090. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  46091. // Scene optimizer tool
  46092. var SceneOptimizer = (function () {
  46093. function SceneOptimizer() {
  46094. }
  46095. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  46096. // TODO: add an epsilon
  46097. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  46098. if (onSuccess) {
  46099. onSuccess();
  46100. }
  46101. return;
  46102. }
  46103. // Apply current level of optimizations
  46104. var allDone = true;
  46105. var noOptimizationApplied = true;
  46106. for (var index = 0; index < options.optimizations.length; index++) {
  46107. var optimization = options.optimizations[index];
  46108. if (optimization.priority === currentPriorityLevel) {
  46109. noOptimizationApplied = false;
  46110. allDone = allDone && optimization.apply(scene);
  46111. }
  46112. }
  46113. // If no optimization was applied, this is a failure :(
  46114. if (noOptimizationApplied) {
  46115. if (onFailure) {
  46116. onFailure();
  46117. }
  46118. return;
  46119. }
  46120. // If all optimizations were done, move to next level
  46121. if (allDone) {
  46122. currentPriorityLevel++;
  46123. }
  46124. // Let's the system running for a specific amount of time before checking FPS
  46125. scene.executeWhenReady(function () {
  46126. setTimeout(function () {
  46127. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  46128. }, options.trackerDuration);
  46129. });
  46130. };
  46131. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  46132. if (!options) {
  46133. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  46134. }
  46135. // Let's the system running for a specific amount of time before checking FPS
  46136. scene.executeWhenReady(function () {
  46137. setTimeout(function () {
  46138. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  46139. }, options.trackerDuration);
  46140. });
  46141. };
  46142. return SceneOptimizer;
  46143. }());
  46144. BABYLON.SceneOptimizer = SceneOptimizer;
  46145. })(BABYLON || (BABYLON = {}));
  46146. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  46147. var BABYLON;
  46148. (function (BABYLON) {
  46149. var Internals;
  46150. (function (Internals) {
  46151. var MeshLODLevel = (function () {
  46152. function MeshLODLevel(distance, mesh) {
  46153. this.distance = distance;
  46154. this.mesh = mesh;
  46155. }
  46156. return MeshLODLevel;
  46157. }());
  46158. Internals.MeshLODLevel = MeshLODLevel;
  46159. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  46160. })(BABYLON || (BABYLON = {}));
  46161. //# sourceMappingURL=babylon.meshLODLevel.js.map
  46162. var BABYLON;
  46163. (function (BABYLON) {
  46164. var RawTexture = (function (_super) {
  46165. __extends(RawTexture, _super);
  46166. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  46167. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46168. if (invertY === void 0) { invertY = false; }
  46169. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46170. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46171. _this.format = format;
  46172. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  46173. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46174. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46175. return _this;
  46176. }
  46177. RawTexture.prototype.update = function (data) {
  46178. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  46179. };
  46180. // Statics
  46181. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46182. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46183. if (invertY === void 0) { invertY = false; }
  46184. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46185. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  46186. };
  46187. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46188. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46189. if (invertY === void 0) { invertY = false; }
  46190. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46191. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46192. };
  46193. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46194. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46195. if (invertY === void 0) { invertY = false; }
  46196. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46197. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46198. };
  46199. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46200. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46201. if (invertY === void 0) { invertY = false; }
  46202. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46203. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  46204. };
  46205. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46206. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46207. if (invertY === void 0) { invertY = false; }
  46208. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46209. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  46210. };
  46211. return RawTexture;
  46212. }(BABYLON.Texture));
  46213. BABYLON.RawTexture = RawTexture;
  46214. })(BABYLON || (BABYLON = {}));
  46215. //# sourceMappingURL=babylon.rawTexture.js.map
  46216. var BABYLON;
  46217. (function (BABYLON) {
  46218. var IndexedVector2 = (function (_super) {
  46219. __extends(IndexedVector2, _super);
  46220. function IndexedVector2(original, index) {
  46221. var _this = _super.call(this, original.x, original.y) || this;
  46222. _this.index = index;
  46223. return _this;
  46224. }
  46225. return IndexedVector2;
  46226. }(BABYLON.Vector2));
  46227. var PolygonPoints = (function () {
  46228. function PolygonPoints() {
  46229. this.elements = new Array();
  46230. }
  46231. PolygonPoints.prototype.add = function (originalPoints) {
  46232. var _this = this;
  46233. var result = new Array();
  46234. originalPoints.forEach(function (point) {
  46235. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  46236. var newPoint = new IndexedVector2(point, _this.elements.length);
  46237. result.push(newPoint);
  46238. _this.elements.push(newPoint);
  46239. }
  46240. });
  46241. return result;
  46242. };
  46243. PolygonPoints.prototype.computeBounds = function () {
  46244. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  46245. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  46246. this.elements.forEach(function (point) {
  46247. // x
  46248. if (point.x < lmin.x) {
  46249. lmin.x = point.x;
  46250. }
  46251. else if (point.x > lmax.x) {
  46252. lmax.x = point.x;
  46253. }
  46254. // y
  46255. if (point.y < lmin.y) {
  46256. lmin.y = point.y;
  46257. }
  46258. else if (point.y > lmax.y) {
  46259. lmax.y = point.y;
  46260. }
  46261. });
  46262. return {
  46263. min: lmin,
  46264. max: lmax,
  46265. width: lmax.x - lmin.x,
  46266. height: lmax.y - lmin.y
  46267. };
  46268. };
  46269. return PolygonPoints;
  46270. }());
  46271. var Polygon = (function () {
  46272. function Polygon() {
  46273. }
  46274. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  46275. return [
  46276. new BABYLON.Vector2(xmin, ymin),
  46277. new BABYLON.Vector2(xmax, ymin),
  46278. new BABYLON.Vector2(xmax, ymax),
  46279. new BABYLON.Vector2(xmin, ymax)
  46280. ];
  46281. };
  46282. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  46283. if (cx === void 0) { cx = 0; }
  46284. if (cy === void 0) { cy = 0; }
  46285. if (numberOfSides === void 0) { numberOfSides = 32; }
  46286. var result = new Array();
  46287. var angle = 0;
  46288. var increment = (Math.PI * 2) / numberOfSides;
  46289. for (var i = 0; i < numberOfSides; i++) {
  46290. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  46291. angle -= increment;
  46292. }
  46293. return result;
  46294. };
  46295. Polygon.Parse = function (input) {
  46296. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  46297. var i, result = [];
  46298. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  46299. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  46300. }
  46301. return result;
  46302. };
  46303. Polygon.StartingAt = function (x, y) {
  46304. return BABYLON.Path2.StartingAt(x, y);
  46305. };
  46306. return Polygon;
  46307. }());
  46308. BABYLON.Polygon = Polygon;
  46309. var PolygonMeshBuilder = (function () {
  46310. function PolygonMeshBuilder(name, contours, scene) {
  46311. this._points = new PolygonPoints();
  46312. this._outlinepoints = new PolygonPoints();
  46313. this._holes = [];
  46314. this._epoints = new Array();
  46315. this._eholes = new Array();
  46316. this._name = name;
  46317. this._scene = scene;
  46318. var points;
  46319. if (contours instanceof BABYLON.Path2) {
  46320. points = contours.getPoints();
  46321. }
  46322. else {
  46323. points = contours;
  46324. }
  46325. this._addToepoint(points);
  46326. this._points.add(points);
  46327. this._outlinepoints.add(points);
  46328. }
  46329. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  46330. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  46331. var p = points_1[_i];
  46332. this._epoints.push(p.x, p.y);
  46333. }
  46334. };
  46335. PolygonMeshBuilder.prototype.addHole = function (hole) {
  46336. this._points.add(hole);
  46337. var holepoints = new PolygonPoints();
  46338. holepoints.add(hole);
  46339. this._holes.push(holepoints);
  46340. this._eholes.push(this._epoints.length / 2);
  46341. this._addToepoint(hole);
  46342. return this;
  46343. };
  46344. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  46345. var _this = this;
  46346. if (updatable === void 0) { updatable = false; }
  46347. var result = new BABYLON.Mesh(this._name, this._scene);
  46348. var normals = [];
  46349. var positions = [];
  46350. var uvs = [];
  46351. var bounds = this._points.computeBounds();
  46352. this._points.elements.forEach(function (p) {
  46353. normals.push(0, 1.0, 0);
  46354. positions.push(p.x, 0, p.y);
  46355. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  46356. });
  46357. var indices = [];
  46358. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  46359. for (var i = 0; i < res.length; i++) {
  46360. indices.push(res[i]);
  46361. }
  46362. if (depth > 0) {
  46363. var positionscount = (positions.length / 3); //get the current pointcount
  46364. this._points.elements.forEach(function (p) {
  46365. normals.push(0, -1.0, 0);
  46366. positions.push(p.x, -depth, p.y);
  46367. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  46368. });
  46369. var totalCount = indices.length;
  46370. for (var i = 0; i < totalCount; i += 3) {
  46371. var i0 = indices[i + 0];
  46372. var i1 = indices[i + 1];
  46373. var i2 = indices[i + 2];
  46374. indices.push(i2 + positionscount);
  46375. indices.push(i1 + positionscount);
  46376. indices.push(i0 + positionscount);
  46377. }
  46378. //Add the sides
  46379. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  46380. this._holes.forEach(function (hole) {
  46381. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  46382. });
  46383. }
  46384. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  46385. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  46386. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  46387. result.setIndices(indices);
  46388. return result;
  46389. };
  46390. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  46391. var StartIndex = positions.length / 3;
  46392. var ulength = 0;
  46393. for (var i = 0; i < points.elements.length; i++) {
  46394. var p = points.elements[i];
  46395. var p1;
  46396. if ((i + 1) > points.elements.length - 1) {
  46397. p1 = points.elements[0];
  46398. }
  46399. else {
  46400. p1 = points.elements[i + 1];
  46401. }
  46402. positions.push(p.x, 0, p.y);
  46403. positions.push(p.x, -depth, p.y);
  46404. positions.push(p1.x, 0, p1.y);
  46405. positions.push(p1.x, -depth, p1.y);
  46406. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  46407. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  46408. var v3 = v2.subtract(v1);
  46409. var v4 = new BABYLON.Vector3(0, 1, 0);
  46410. var vn = BABYLON.Vector3.Cross(v3, v4);
  46411. vn = vn.normalize();
  46412. uvs.push(ulength / bounds.width, 0);
  46413. uvs.push(ulength / bounds.width, 1);
  46414. ulength += v3.length();
  46415. uvs.push((ulength / bounds.width), 0);
  46416. uvs.push((ulength / bounds.width), 1);
  46417. if (!flip) {
  46418. normals.push(-vn.x, -vn.y, -vn.z);
  46419. normals.push(-vn.x, -vn.y, -vn.z);
  46420. normals.push(-vn.x, -vn.y, -vn.z);
  46421. normals.push(-vn.x, -vn.y, -vn.z);
  46422. indices.push(StartIndex);
  46423. indices.push(StartIndex + 1);
  46424. indices.push(StartIndex + 2);
  46425. indices.push(StartIndex + 1);
  46426. indices.push(StartIndex + 3);
  46427. indices.push(StartIndex + 2);
  46428. }
  46429. else {
  46430. normals.push(vn.x, vn.y, vn.z);
  46431. normals.push(vn.x, vn.y, vn.z);
  46432. normals.push(vn.x, vn.y, vn.z);
  46433. normals.push(vn.x, vn.y, vn.z);
  46434. indices.push(StartIndex);
  46435. indices.push(StartIndex + 2);
  46436. indices.push(StartIndex + 1);
  46437. indices.push(StartIndex + 1);
  46438. indices.push(StartIndex + 2);
  46439. indices.push(StartIndex + 3);
  46440. }
  46441. StartIndex += 4;
  46442. }
  46443. ;
  46444. };
  46445. return PolygonMeshBuilder;
  46446. }());
  46447. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  46448. })(BABYLON || (BABYLON = {}));
  46449. //# sourceMappingURL=babylon.polygonMesh.js.map
  46450. var BABYLON;
  46451. (function (BABYLON) {
  46452. var Octree = (function () {
  46453. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  46454. if (maxDepth === void 0) { maxDepth = 2; }
  46455. this.maxDepth = maxDepth;
  46456. this.dynamicContent = new Array();
  46457. this._maxBlockCapacity = maxBlockCapacity || 64;
  46458. this._selectionContent = new BABYLON.SmartArray(1024);
  46459. this._creationFunc = creationFunc;
  46460. }
  46461. // Methods
  46462. Octree.prototype.update = function (worldMin, worldMax, entries) {
  46463. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  46464. };
  46465. Octree.prototype.addMesh = function (entry) {
  46466. for (var index = 0; index < this.blocks.length; index++) {
  46467. var block = this.blocks[index];
  46468. block.addEntry(entry);
  46469. }
  46470. };
  46471. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  46472. this._selectionContent.reset();
  46473. for (var index = 0; index < this.blocks.length; index++) {
  46474. var block = this.blocks[index];
  46475. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  46476. }
  46477. if (allowDuplicate) {
  46478. this._selectionContent.concat(this.dynamicContent);
  46479. }
  46480. else {
  46481. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46482. }
  46483. return this._selectionContent;
  46484. };
  46485. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  46486. this._selectionContent.reset();
  46487. for (var index = 0; index < this.blocks.length; index++) {
  46488. var block = this.blocks[index];
  46489. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  46490. }
  46491. if (allowDuplicate) {
  46492. this._selectionContent.concat(this.dynamicContent);
  46493. }
  46494. else {
  46495. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46496. }
  46497. return this._selectionContent;
  46498. };
  46499. Octree.prototype.intersectsRay = function (ray) {
  46500. this._selectionContent.reset();
  46501. for (var index = 0; index < this.blocks.length; index++) {
  46502. var block = this.blocks[index];
  46503. block.intersectsRay(ray, this._selectionContent);
  46504. }
  46505. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  46506. return this._selectionContent;
  46507. };
  46508. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  46509. target.blocks = new Array();
  46510. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  46511. // Segmenting space
  46512. for (var x = 0; x < 2; x++) {
  46513. for (var y = 0; y < 2; y++) {
  46514. for (var z = 0; z < 2; z++) {
  46515. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  46516. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  46517. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  46518. block.addEntries(entries);
  46519. target.blocks.push(block);
  46520. }
  46521. }
  46522. }
  46523. };
  46524. return Octree;
  46525. }());
  46526. Octree.CreationFuncForMeshes = function (entry, block) {
  46527. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  46528. block.entries.push(entry);
  46529. }
  46530. };
  46531. Octree.CreationFuncForSubMeshes = function (entry, block) {
  46532. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  46533. block.entries.push(entry);
  46534. }
  46535. };
  46536. BABYLON.Octree = Octree;
  46537. })(BABYLON || (BABYLON = {}));
  46538. //# sourceMappingURL=babylon.octree.js.map
  46539. var BABYLON;
  46540. (function (BABYLON) {
  46541. var OctreeBlock = (function () {
  46542. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  46543. this.entries = new Array();
  46544. this._boundingVectors = new Array();
  46545. this._capacity = capacity;
  46546. this._depth = depth;
  46547. this._maxDepth = maxDepth;
  46548. this._creationFunc = creationFunc;
  46549. this._minPoint = minPoint;
  46550. this._maxPoint = maxPoint;
  46551. this._boundingVectors.push(minPoint.clone());
  46552. this._boundingVectors.push(maxPoint.clone());
  46553. this._boundingVectors.push(minPoint.clone());
  46554. this._boundingVectors[2].x = maxPoint.x;
  46555. this._boundingVectors.push(minPoint.clone());
  46556. this._boundingVectors[3].y = maxPoint.y;
  46557. this._boundingVectors.push(minPoint.clone());
  46558. this._boundingVectors[4].z = maxPoint.z;
  46559. this._boundingVectors.push(maxPoint.clone());
  46560. this._boundingVectors[5].z = minPoint.z;
  46561. this._boundingVectors.push(maxPoint.clone());
  46562. this._boundingVectors[6].x = minPoint.x;
  46563. this._boundingVectors.push(maxPoint.clone());
  46564. this._boundingVectors[7].y = minPoint.y;
  46565. }
  46566. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  46567. // Property
  46568. get: function () {
  46569. return this._capacity;
  46570. },
  46571. enumerable: true,
  46572. configurable: true
  46573. });
  46574. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  46575. get: function () {
  46576. return this._minPoint;
  46577. },
  46578. enumerable: true,
  46579. configurable: true
  46580. });
  46581. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  46582. get: function () {
  46583. return this._maxPoint;
  46584. },
  46585. enumerable: true,
  46586. configurable: true
  46587. });
  46588. // Methods
  46589. OctreeBlock.prototype.addEntry = function (entry) {
  46590. if (this.blocks) {
  46591. for (var index = 0; index < this.blocks.length; index++) {
  46592. var block = this.blocks[index];
  46593. block.addEntry(entry);
  46594. }
  46595. return;
  46596. }
  46597. this._creationFunc(entry, this);
  46598. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  46599. this.createInnerBlocks();
  46600. }
  46601. };
  46602. OctreeBlock.prototype.addEntries = function (entries) {
  46603. for (var index = 0; index < entries.length; index++) {
  46604. var mesh = entries[index];
  46605. this.addEntry(mesh);
  46606. }
  46607. };
  46608. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  46609. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  46610. if (this.blocks) {
  46611. for (var index = 0; index < this.blocks.length; index++) {
  46612. var block = this.blocks[index];
  46613. block.select(frustumPlanes, selection, allowDuplicate);
  46614. }
  46615. return;
  46616. }
  46617. if (allowDuplicate) {
  46618. selection.concat(this.entries);
  46619. }
  46620. else {
  46621. selection.concatWithNoDuplicate(this.entries);
  46622. }
  46623. }
  46624. };
  46625. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  46626. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  46627. if (this.blocks) {
  46628. for (var index = 0; index < this.blocks.length; index++) {
  46629. var block = this.blocks[index];
  46630. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  46631. }
  46632. return;
  46633. }
  46634. if (allowDuplicate) {
  46635. selection.concat(this.entries);
  46636. }
  46637. else {
  46638. selection.concatWithNoDuplicate(this.entries);
  46639. }
  46640. }
  46641. };
  46642. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  46643. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  46644. if (this.blocks) {
  46645. for (var index = 0; index < this.blocks.length; index++) {
  46646. var block = this.blocks[index];
  46647. block.intersectsRay(ray, selection);
  46648. }
  46649. return;
  46650. }
  46651. selection.concatWithNoDuplicate(this.entries);
  46652. }
  46653. };
  46654. OctreeBlock.prototype.createInnerBlocks = function () {
  46655. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  46656. };
  46657. return OctreeBlock;
  46658. }());
  46659. BABYLON.OctreeBlock = OctreeBlock;
  46660. })(BABYLON || (BABYLON = {}));
  46661. //# sourceMappingURL=babylon.octreeBlock.js.map
  46662. var BABYLON;
  46663. (function (BABYLON) {
  46664. var BlurPostProcess = (function (_super) {
  46665. __extends(BlurPostProcess, _super);
  46666. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  46667. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  46668. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  46669. _this.direction = direction;
  46670. _this.blurWidth = blurWidth;
  46671. _this.onApplyObservable.add(function (effect) {
  46672. effect.setFloat2("screenSize", _this.width, _this.height);
  46673. effect.setVector2("direction", _this.direction);
  46674. effect.setFloat("blurWidth", _this.blurWidth);
  46675. });
  46676. return _this;
  46677. }
  46678. return BlurPostProcess;
  46679. }(BABYLON.PostProcess));
  46680. BABYLON.BlurPostProcess = BlurPostProcess;
  46681. })(BABYLON || (BABYLON = {}));
  46682. //# sourceMappingURL=babylon.blurPostProcess.js.map
  46683. var BABYLON;
  46684. (function (BABYLON) {
  46685. var RefractionPostProcess = (function (_super) {
  46686. __extends(RefractionPostProcess, _super);
  46687. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  46688. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  46689. _this.color = color;
  46690. _this.depth = depth;
  46691. _this.colorLevel = colorLevel;
  46692. _this.onActivateObservable.add(function (cam) {
  46693. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  46694. });
  46695. _this.onApplyObservable.add(function (effect) {
  46696. effect.setColor3("baseColor", _this.color);
  46697. effect.setFloat("depth", _this.depth);
  46698. effect.setFloat("colorLevel", _this.colorLevel);
  46699. effect.setTexture("refractionSampler", _this._refRexture);
  46700. });
  46701. return _this;
  46702. }
  46703. // Methods
  46704. RefractionPostProcess.prototype.dispose = function (camera) {
  46705. if (this._refRexture) {
  46706. this._refRexture.dispose();
  46707. }
  46708. _super.prototype.dispose.call(this, camera);
  46709. };
  46710. return RefractionPostProcess;
  46711. }(BABYLON.PostProcess));
  46712. BABYLON.RefractionPostProcess = RefractionPostProcess;
  46713. })(BABYLON || (BABYLON = {}));
  46714. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  46715. var BABYLON;
  46716. (function (BABYLON) {
  46717. var BlackAndWhitePostProcess = (function (_super) {
  46718. __extends(BlackAndWhitePostProcess, _super);
  46719. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  46720. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  46721. }
  46722. return BlackAndWhitePostProcess;
  46723. }(BABYLON.PostProcess));
  46724. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  46725. })(BABYLON || (BABYLON = {}));
  46726. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  46727. var BABYLON;
  46728. (function (BABYLON) {
  46729. var ConvolutionPostProcess = (function (_super) {
  46730. __extends(ConvolutionPostProcess, _super);
  46731. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  46732. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  46733. _this.kernel = kernel;
  46734. _this.onApply = function (effect) {
  46735. effect.setFloat2("screenSize", _this.width, _this.height);
  46736. effect.setArray("kernel", _this.kernel);
  46737. };
  46738. return _this;
  46739. }
  46740. return ConvolutionPostProcess;
  46741. }(BABYLON.PostProcess));
  46742. // Statics
  46743. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  46744. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  46745. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  46746. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  46747. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  46748. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  46749. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  46750. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  46751. })(BABYLON || (BABYLON = {}));
  46752. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  46753. var BABYLON;
  46754. (function (BABYLON) {
  46755. var FilterPostProcess = (function (_super) {
  46756. __extends(FilterPostProcess, _super);
  46757. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  46758. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  46759. _this.kernelMatrix = kernelMatrix;
  46760. _this.onApply = function (effect) {
  46761. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  46762. };
  46763. return _this;
  46764. }
  46765. return FilterPostProcess;
  46766. }(BABYLON.PostProcess));
  46767. BABYLON.FilterPostProcess = FilterPostProcess;
  46768. })(BABYLON || (BABYLON = {}));
  46769. //# sourceMappingURL=babylon.filterPostProcess.js.map
  46770. var BABYLON;
  46771. (function (BABYLON) {
  46772. var FxaaPostProcess = (function (_super) {
  46773. __extends(FxaaPostProcess, _super);
  46774. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  46775. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable) || this;
  46776. _this.onSizeChangedObservable.add(function () {
  46777. _this.texelWidth = 1.0 / _this.width;
  46778. _this.texelHeight = 1.0 / _this.height;
  46779. });
  46780. _this.onApplyObservable.add(function (effect) {
  46781. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  46782. });
  46783. return _this;
  46784. }
  46785. return FxaaPostProcess;
  46786. }(BABYLON.PostProcess));
  46787. BABYLON.FxaaPostProcess = FxaaPostProcess;
  46788. })(BABYLON || (BABYLON = {}));
  46789. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  46790. var BABYLON;
  46791. (function (BABYLON) {
  46792. var StereoscopicInterlacePostProcess = (function (_super) {
  46793. __extends(StereoscopicInterlacePostProcess, _super);
  46794. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  46795. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  46796. _this._passedProcess = rigCameras[0]._rigPostProcess;
  46797. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  46798. _this.onSizeChangedObservable.add(function () {
  46799. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  46800. });
  46801. _this.onApplyObservable.add(function (effect) {
  46802. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  46803. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  46804. });
  46805. return _this;
  46806. }
  46807. return StereoscopicInterlacePostProcess;
  46808. }(BABYLON.PostProcess));
  46809. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  46810. })(BABYLON || (BABYLON = {}));
  46811. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  46812. var BABYLON;
  46813. (function (BABYLON) {
  46814. var LensFlare = (function () {
  46815. function LensFlare(size, position, color, imgUrl, system) {
  46816. this.size = size;
  46817. this.position = position;
  46818. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  46819. this.dispose = function () {
  46820. if (this.texture) {
  46821. this.texture.dispose();
  46822. }
  46823. // Remove from scene
  46824. var index = this._system.lensFlares.indexOf(this);
  46825. this._system.lensFlares.splice(index, 1);
  46826. };
  46827. this.color = color || new BABYLON.Color3(1, 1, 1);
  46828. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  46829. this._system = system;
  46830. system.lensFlares.push(this);
  46831. }
  46832. return LensFlare;
  46833. }());
  46834. BABYLON.LensFlare = LensFlare;
  46835. })(BABYLON || (BABYLON = {}));
  46836. //# sourceMappingURL=babylon.lensFlare.js.map
  46837. var BABYLON;
  46838. (function (BABYLON) {
  46839. var LensFlareSystem = (function () {
  46840. function LensFlareSystem(name, emitter, scene) {
  46841. this.name = name;
  46842. this.lensFlares = new Array();
  46843. this.borderLimit = 300;
  46844. this.viewportBorder = 0;
  46845. this.layerMask = 0x0FFFFFFF;
  46846. this._vertexBuffers = {};
  46847. this._isEnabled = true;
  46848. this._scene = scene;
  46849. this._emitter = emitter;
  46850. this.id = name;
  46851. scene.lensFlareSystems.push(this);
  46852. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  46853. var engine = scene.getEngine();
  46854. // VBO
  46855. var vertices = [];
  46856. vertices.push(1, 1);
  46857. vertices.push(-1, 1);
  46858. vertices.push(-1, -1);
  46859. vertices.push(1, -1);
  46860. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  46861. // Indices
  46862. var indices = [];
  46863. indices.push(0);
  46864. indices.push(1);
  46865. indices.push(2);
  46866. indices.push(0);
  46867. indices.push(2);
  46868. indices.push(3);
  46869. this._indexBuffer = engine.createIndexBuffer(indices);
  46870. // Effects
  46871. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  46872. }
  46873. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  46874. get: function () {
  46875. return this._isEnabled;
  46876. },
  46877. set: function (value) {
  46878. this._isEnabled = value;
  46879. },
  46880. enumerable: true,
  46881. configurable: true
  46882. });
  46883. LensFlareSystem.prototype.getScene = function () {
  46884. return this._scene;
  46885. };
  46886. LensFlareSystem.prototype.getEmitter = function () {
  46887. return this._emitter;
  46888. };
  46889. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  46890. this._emitter = newEmitter;
  46891. };
  46892. LensFlareSystem.prototype.getEmitterPosition = function () {
  46893. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  46894. };
  46895. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  46896. var position = this.getEmitterPosition();
  46897. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  46898. this._positionX = position.x;
  46899. this._positionY = position.y;
  46900. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  46901. if (this.viewportBorder > 0) {
  46902. globalViewport.x -= this.viewportBorder;
  46903. globalViewport.y -= this.viewportBorder;
  46904. globalViewport.width += this.viewportBorder * 2;
  46905. globalViewport.height += this.viewportBorder * 2;
  46906. position.x += this.viewportBorder;
  46907. position.y += this.viewportBorder;
  46908. this._positionX += this.viewportBorder;
  46909. this._positionY += this.viewportBorder;
  46910. }
  46911. if (position.z > 0) {
  46912. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  46913. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  46914. return true;
  46915. }
  46916. return true;
  46917. }
  46918. return false;
  46919. };
  46920. LensFlareSystem.prototype._isVisible = function () {
  46921. if (!this._isEnabled) {
  46922. return false;
  46923. }
  46924. var emitterPosition = this.getEmitterPosition();
  46925. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  46926. var distance = direction.length();
  46927. direction.normalize();
  46928. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  46929. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  46930. return !pickInfo.hit || pickInfo.distance > distance;
  46931. };
  46932. LensFlareSystem.prototype.render = function () {
  46933. if (!this._effect.isReady())
  46934. return false;
  46935. var engine = this._scene.getEngine();
  46936. var viewport = this._scene.activeCamera.viewport;
  46937. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  46938. // Position
  46939. if (!this.computeEffectivePosition(globalViewport)) {
  46940. return false;
  46941. }
  46942. // Visibility
  46943. if (!this._isVisible()) {
  46944. return false;
  46945. }
  46946. // Intensity
  46947. var awayX;
  46948. var awayY;
  46949. if (this._positionX < this.borderLimit + globalViewport.x) {
  46950. awayX = this.borderLimit + globalViewport.x - this._positionX;
  46951. }
  46952. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  46953. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  46954. }
  46955. else {
  46956. awayX = 0;
  46957. }
  46958. if (this._positionY < this.borderLimit + globalViewport.y) {
  46959. awayY = this.borderLimit + globalViewport.y - this._positionY;
  46960. }
  46961. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  46962. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  46963. }
  46964. else {
  46965. awayY = 0;
  46966. }
  46967. var away = (awayX > awayY) ? awayX : awayY;
  46968. away -= this.viewportBorder;
  46969. if (away > this.borderLimit) {
  46970. away = this.borderLimit;
  46971. }
  46972. var intensity = 1.0 - (away / this.borderLimit);
  46973. if (intensity < 0) {
  46974. return false;
  46975. }
  46976. if (intensity > 1.0) {
  46977. intensity = 1.0;
  46978. }
  46979. if (this.viewportBorder > 0) {
  46980. globalViewport.x += this.viewportBorder;
  46981. globalViewport.y += this.viewportBorder;
  46982. globalViewport.width -= this.viewportBorder * 2;
  46983. globalViewport.height -= this.viewportBorder * 2;
  46984. this._positionX -= this.viewportBorder;
  46985. this._positionY -= this.viewportBorder;
  46986. }
  46987. // Position
  46988. var centerX = globalViewport.x + globalViewport.width / 2;
  46989. var centerY = globalViewport.y + globalViewport.height / 2;
  46990. var distX = centerX - this._positionX;
  46991. var distY = centerY - this._positionY;
  46992. // Effects
  46993. engine.enableEffect(this._effect);
  46994. engine.setState(false);
  46995. engine.setDepthBuffer(false);
  46996. // VBOs
  46997. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46998. // Flares
  46999. for (var index = 0; index < this.lensFlares.length; index++) {
  47000. var flare = this.lensFlares[index];
  47001. engine.setAlphaMode(flare.alphaMode);
  47002. var x = centerX - (distX * flare.position);
  47003. var y = centerY - (distY * flare.position);
  47004. var cw = flare.size;
  47005. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  47006. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  47007. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  47008. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  47009. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  47010. // Texture
  47011. this._effect.setTexture("textureSampler", flare.texture);
  47012. // Color
  47013. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  47014. // Draw order
  47015. engine.draw(true, 0, 6);
  47016. }
  47017. engine.setDepthBuffer(true);
  47018. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47019. return true;
  47020. };
  47021. LensFlareSystem.prototype.dispose = function () {
  47022. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  47023. if (vertexBuffer) {
  47024. vertexBuffer.dispose();
  47025. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  47026. }
  47027. if (this._indexBuffer) {
  47028. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  47029. this._indexBuffer = null;
  47030. }
  47031. while (this.lensFlares.length) {
  47032. this.lensFlares[0].dispose();
  47033. }
  47034. // Remove from scene
  47035. var index = this._scene.lensFlareSystems.indexOf(this);
  47036. this._scene.lensFlareSystems.splice(index, 1);
  47037. };
  47038. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  47039. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  47040. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  47041. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  47042. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  47043. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  47044. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  47045. var parsedFlare = parsedLensFlareSystem.flares[index];
  47046. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  47047. }
  47048. return lensFlareSystem;
  47049. };
  47050. LensFlareSystem.prototype.serialize = function () {
  47051. var serializationObject = {};
  47052. serializationObject.id = this.id;
  47053. serializationObject.name = this.name;
  47054. serializationObject.emitterId = this.getEmitter().id;
  47055. serializationObject.borderLimit = this.borderLimit;
  47056. serializationObject.flares = [];
  47057. for (var index = 0; index < this.lensFlares.length; index++) {
  47058. var flare = this.lensFlares[index];
  47059. serializationObject.flares.push({
  47060. size: flare.size,
  47061. position: flare.position,
  47062. color: flare.color.asArray(),
  47063. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  47064. });
  47065. }
  47066. return serializationObject;
  47067. };
  47068. return LensFlareSystem;
  47069. }());
  47070. BABYLON.LensFlareSystem = LensFlareSystem;
  47071. })(BABYLON || (BABYLON = {}));
  47072. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  47073. var BABYLON;
  47074. (function (BABYLON) {
  47075. // We're mainly based on the logic defined into the FreeCamera code
  47076. var DeviceOrientationCamera = (function (_super) {
  47077. __extends(DeviceOrientationCamera, _super);
  47078. function DeviceOrientationCamera(name, position, scene) {
  47079. var _this = _super.call(this, name, position, scene) || this;
  47080. _this._quaternionCache = new BABYLON.Quaternion();
  47081. _this.inputs.addDeviceOrientation();
  47082. return _this;
  47083. }
  47084. DeviceOrientationCamera.prototype.getClassName = function () {
  47085. return "DeviceOrientationCamera";
  47086. };
  47087. DeviceOrientationCamera.prototype._checkInputs = function () {
  47088. _super.prototype._checkInputs.call(this);
  47089. this._quaternionCache.copyFrom(this.rotationQuaternion);
  47090. if (this._initialQuaternion) {
  47091. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  47092. }
  47093. };
  47094. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  47095. var _this = this;
  47096. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  47097. //can only work if this camera has a rotation quaternion already.
  47098. if (!this.rotationQuaternion)
  47099. return;
  47100. if (!this._initialQuaternion) {
  47101. this._initialQuaternion = new BABYLON.Quaternion();
  47102. }
  47103. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  47104. ['x', 'y', 'z'].forEach(function (axisName) {
  47105. if (!axis[axisName]) {
  47106. _this._initialQuaternion[axisName] = 0;
  47107. }
  47108. else {
  47109. _this._initialQuaternion[axisName] *= -1;
  47110. }
  47111. });
  47112. this._initialQuaternion.normalize();
  47113. //force rotation update
  47114. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  47115. };
  47116. return DeviceOrientationCamera;
  47117. }(BABYLON.FreeCamera));
  47118. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  47119. })(BABYLON || (BABYLON = {}));
  47120. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  47121. var BABYLON;
  47122. (function (BABYLON) {
  47123. var VRDeviceOrientationFreeCamera = (function (_super) {
  47124. __extends(VRDeviceOrientationFreeCamera, _super);
  47125. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  47126. if (compensateDistortion === void 0) { compensateDistortion = true; }
  47127. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  47128. var _this = _super.call(this, name, position, scene) || this;
  47129. vrCameraMetrics.compensateDistortion = compensateDistortion;
  47130. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  47131. return _this;
  47132. }
  47133. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  47134. return "VRDeviceOrientationFreeCamera";
  47135. };
  47136. return VRDeviceOrientationFreeCamera;
  47137. }(BABYLON.DeviceOrientationCamera));
  47138. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  47139. var VRDeviceOrientationGamepadCamera = (function (_super) {
  47140. __extends(VRDeviceOrientationGamepadCamera, _super);
  47141. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  47142. if (compensateDistortion === void 0) { compensateDistortion = true; }
  47143. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  47144. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  47145. _this.inputs.addGamepad();
  47146. return _this;
  47147. }
  47148. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  47149. return "VRDeviceOrientationGamepadCamera";
  47150. };
  47151. return VRDeviceOrientationGamepadCamera;
  47152. }(VRDeviceOrientationFreeCamera));
  47153. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  47154. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  47155. __extends(VRDeviceOrientationArcRotateCamera, _super);
  47156. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  47157. if (compensateDistortion === void 0) { compensateDistortion = true; }
  47158. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  47159. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  47160. vrCameraMetrics.compensateDistortion = compensateDistortion;
  47161. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  47162. _this.inputs.addVRDeviceOrientation();
  47163. return _this;
  47164. }
  47165. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  47166. return "VRDeviceOrientationArcRotateCamera";
  47167. };
  47168. return VRDeviceOrientationArcRotateCamera;
  47169. }(BABYLON.ArcRotateCamera));
  47170. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  47171. })(BABYLON || (BABYLON = {}));
  47172. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  47173. var BABYLON;
  47174. (function (BABYLON) {
  47175. // We're mainly based on the logic defined into the FreeCamera code
  47176. var UniversalCamera = (function (_super) {
  47177. __extends(UniversalCamera, _super);
  47178. //-- end properties for backward compatibility for inputs
  47179. function UniversalCamera(name, position, scene) {
  47180. var _this = _super.call(this, name, position, scene) || this;
  47181. _this.inputs.addGamepad();
  47182. return _this;
  47183. }
  47184. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  47185. //-- Begin properties for backward compatibility for inputs
  47186. get: function () {
  47187. var gamepad = this.inputs.attached["gamepad"];
  47188. if (gamepad)
  47189. return gamepad.gamepadAngularSensibility;
  47190. },
  47191. set: function (value) {
  47192. var gamepad = this.inputs.attached["gamepad"];
  47193. if (gamepad)
  47194. gamepad.gamepadAngularSensibility = value;
  47195. },
  47196. enumerable: true,
  47197. configurable: true
  47198. });
  47199. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  47200. get: function () {
  47201. var gamepad = this.inputs.attached["gamepad"];
  47202. if (gamepad)
  47203. return gamepad.gamepadMoveSensibility;
  47204. },
  47205. set: function (value) {
  47206. var gamepad = this.inputs.attached["gamepad"];
  47207. if (gamepad)
  47208. gamepad.gamepadMoveSensibility = value;
  47209. },
  47210. enumerable: true,
  47211. configurable: true
  47212. });
  47213. UniversalCamera.prototype.getClassName = function () {
  47214. return "UniversalCamera";
  47215. };
  47216. return UniversalCamera;
  47217. }(BABYLON.TouchCamera));
  47218. BABYLON.UniversalCamera = UniversalCamera;
  47219. })(BABYLON || (BABYLON = {}));
  47220. //# sourceMappingURL=babylon.universalCamera.js.map
  47221. var BABYLON;
  47222. (function (BABYLON) {
  47223. var Gamepads = (function () {
  47224. function Gamepads(ongamedpadconnected) {
  47225. var _this = this;
  47226. this.babylonGamepads = [];
  47227. this.oneGamepadConnected = false;
  47228. this.isMonitoring = false;
  47229. this.gamepadEventSupported = 'GamepadEvent' in window;
  47230. this.gamepadSupportAvailable = (navigator.getGamepads ||
  47231. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  47232. this._callbackGamepadConnected = ongamedpadconnected;
  47233. if (this.gamepadSupportAvailable) {
  47234. // Checking if the gamepad connected event is supported (like in Firefox)
  47235. if (this.gamepadEventSupported) {
  47236. this._onGamepadConnectedEvent = function (evt) {
  47237. _this._onGamepadConnected(evt);
  47238. };
  47239. this._onGamepadDisonnectedEvent = function (evt) {
  47240. _this._onGamepadDisconnected(evt);
  47241. };
  47242. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  47243. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  47244. }
  47245. else {
  47246. this._startMonitoringGamepads();
  47247. }
  47248. }
  47249. }
  47250. Gamepads.prototype.dispose = function () {
  47251. if (Gamepads.gamepadDOMInfo) {
  47252. document.body.removeChild(Gamepads.gamepadDOMInfo);
  47253. }
  47254. if (this._onGamepadConnectedEvent) {
  47255. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  47256. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  47257. this._onGamepadConnectedEvent = null;
  47258. this._onGamepadDisonnectedEvent = null;
  47259. }
  47260. };
  47261. Gamepads.prototype._onGamepadConnected = function (evt) {
  47262. var newGamepad = this._addNewGamepad(evt.gamepad);
  47263. if (this._callbackGamepadConnected)
  47264. this._callbackGamepadConnected(newGamepad);
  47265. this._startMonitoringGamepads();
  47266. };
  47267. Gamepads.prototype._addNewGamepad = function (gamepad) {
  47268. if (!this.oneGamepadConnected) {
  47269. this.oneGamepadConnected = true;
  47270. if (Gamepads.gamepadDOMInfo) {
  47271. document.body.removeChild(Gamepads.gamepadDOMInfo);
  47272. Gamepads.gamepadDOMInfo = null;
  47273. }
  47274. }
  47275. var newGamepad;
  47276. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  47277. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  47278. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  47279. }
  47280. else {
  47281. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  47282. }
  47283. this.babylonGamepads.push(newGamepad);
  47284. return newGamepad;
  47285. };
  47286. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  47287. // Remove the gamepad from the list of gamepads to monitor.
  47288. for (var i in this.babylonGamepads) {
  47289. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  47290. this.babylonGamepads.splice(+i, 1);
  47291. break;
  47292. }
  47293. }
  47294. // If no gamepads are left, stop the polling loop.
  47295. if (this.babylonGamepads.length == 0) {
  47296. this._stopMonitoringGamepads();
  47297. }
  47298. };
  47299. Gamepads.prototype._startMonitoringGamepads = function () {
  47300. if (!this.isMonitoring) {
  47301. this.isMonitoring = true;
  47302. this._checkGamepadsStatus();
  47303. }
  47304. };
  47305. Gamepads.prototype._stopMonitoringGamepads = function () {
  47306. this.isMonitoring = false;
  47307. };
  47308. Gamepads.prototype._checkGamepadsStatus = function () {
  47309. var _this = this;
  47310. // updating gamepad objects
  47311. this._updateGamepadObjects();
  47312. for (var i in this.babylonGamepads) {
  47313. this.babylonGamepads[i].update();
  47314. }
  47315. if (this.isMonitoring) {
  47316. if (window.requestAnimationFrame) {
  47317. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47318. }
  47319. else if (window.mozRequestAnimationFrame) {
  47320. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47321. }
  47322. else if (window.webkitRequestAnimationFrame) {
  47323. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  47324. }
  47325. }
  47326. };
  47327. // This function is called only on Chrome, which does not yet support
  47328. // connection/disconnection events, but requires you to monitor
  47329. // an array for changes.
  47330. Gamepads.prototype._updateGamepadObjects = function () {
  47331. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  47332. for (var i = 0; i < gamepads.length; i++) {
  47333. if (gamepads[i]) {
  47334. if (!(gamepads[i].index in this.babylonGamepads)) {
  47335. var newGamepad = this._addNewGamepad(gamepads[i]);
  47336. if (this._callbackGamepadConnected) {
  47337. this._callbackGamepadConnected(newGamepad);
  47338. }
  47339. }
  47340. else {
  47341. this.babylonGamepads[i].browserGamepad = gamepads[i];
  47342. }
  47343. }
  47344. }
  47345. };
  47346. return Gamepads;
  47347. }());
  47348. BABYLON.Gamepads = Gamepads;
  47349. var StickValues = (function () {
  47350. function StickValues(x, y) {
  47351. this.x = x;
  47352. this.y = y;
  47353. }
  47354. return StickValues;
  47355. }());
  47356. BABYLON.StickValues = StickValues;
  47357. var Gamepad = (function () {
  47358. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  47359. if (leftStickX === void 0) { leftStickX = 0; }
  47360. if (leftStickY === void 0) { leftStickY = 1; }
  47361. if (rightStickX === void 0) { rightStickX = 2; }
  47362. if (rightStickY === void 0) { rightStickY = 3; }
  47363. this.id = id;
  47364. this.index = index;
  47365. this.browserGamepad = browserGamepad;
  47366. this._leftStickAxisX = leftStickX;
  47367. this._leftStickAxisY = leftStickY;
  47368. this._rightStickAxisX = rightStickX;
  47369. this._rightStickAxisY = rightStickY;
  47370. if (this.browserGamepad.axes.length >= 2) {
  47371. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47372. }
  47373. if (this.browserGamepad.axes.length >= 4) {
  47374. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47375. }
  47376. }
  47377. Gamepad.prototype.onleftstickchanged = function (callback) {
  47378. this._onleftstickchanged = callback;
  47379. };
  47380. Gamepad.prototype.onrightstickchanged = function (callback) {
  47381. this._onrightstickchanged = callback;
  47382. };
  47383. Object.defineProperty(Gamepad.prototype, "leftStick", {
  47384. get: function () {
  47385. return this._leftStick;
  47386. },
  47387. set: function (newValues) {
  47388. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  47389. this._onleftstickchanged(newValues);
  47390. }
  47391. this._leftStick = newValues;
  47392. },
  47393. enumerable: true,
  47394. configurable: true
  47395. });
  47396. Object.defineProperty(Gamepad.prototype, "rightStick", {
  47397. get: function () {
  47398. return this._rightStick;
  47399. },
  47400. set: function (newValues) {
  47401. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  47402. this._onrightstickchanged(newValues);
  47403. }
  47404. this._rightStick = newValues;
  47405. },
  47406. enumerable: true,
  47407. configurable: true
  47408. });
  47409. Gamepad.prototype.update = function () {
  47410. if (this._leftStick) {
  47411. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  47412. }
  47413. if (this._rightStick) {
  47414. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  47415. }
  47416. };
  47417. return Gamepad;
  47418. }());
  47419. BABYLON.Gamepad = Gamepad;
  47420. var GenericPad = (function (_super) {
  47421. __extends(GenericPad, _super);
  47422. function GenericPad(id, index, gamepad) {
  47423. var _this = _super.call(this, id, index, gamepad) || this;
  47424. _this.id = id;
  47425. _this.index = index;
  47426. _this.gamepad = gamepad;
  47427. _this._buttons = new Array(gamepad.buttons.length);
  47428. return _this;
  47429. }
  47430. GenericPad.prototype.onbuttondown = function (callback) {
  47431. this._onbuttondown = callback;
  47432. };
  47433. GenericPad.prototype.onbuttonup = function (callback) {
  47434. this._onbuttonup = callback;
  47435. };
  47436. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  47437. if (newValue !== currentValue) {
  47438. if (this._onbuttondown && newValue === 1) {
  47439. this._onbuttondown(buttonIndex);
  47440. }
  47441. if (this._onbuttonup && newValue === 0) {
  47442. this._onbuttonup(buttonIndex);
  47443. }
  47444. }
  47445. return newValue;
  47446. };
  47447. GenericPad.prototype.update = function () {
  47448. _super.prototype.update.call(this);
  47449. for (var index = 0; index < this._buttons.length; index++) {
  47450. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  47451. }
  47452. };
  47453. return GenericPad;
  47454. }(Gamepad));
  47455. BABYLON.GenericPad = GenericPad;
  47456. var Xbox360Button;
  47457. (function (Xbox360Button) {
  47458. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  47459. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  47460. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  47461. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  47462. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  47463. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  47464. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  47465. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  47466. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  47467. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  47468. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  47469. var Xbox360Dpad;
  47470. (function (Xbox360Dpad) {
  47471. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  47472. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  47473. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  47474. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  47475. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  47476. var Xbox360Pad = (function (_super) {
  47477. __extends(Xbox360Pad, _super);
  47478. function Xbox360Pad(id, index, gamepad, xboxOne) {
  47479. if (xboxOne === void 0) { xboxOne = false; }
  47480. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  47481. _this._leftTrigger = 0;
  47482. _this._rightTrigger = 0;
  47483. _this._buttonA = 0;
  47484. _this._buttonB = 0;
  47485. _this._buttonX = 0;
  47486. _this._buttonY = 0;
  47487. _this._buttonBack = 0;
  47488. _this._buttonStart = 0;
  47489. _this._buttonLB = 0;
  47490. _this._buttonRB = 0;
  47491. _this._buttonLeftStick = 0;
  47492. _this._buttonRightStick = 0;
  47493. _this._dPadUp = 0;
  47494. _this._dPadDown = 0;
  47495. _this._dPadLeft = 0;
  47496. _this._dPadRight = 0;
  47497. _this._isXboxOnePad = false;
  47498. _this._isXboxOnePad = xboxOne;
  47499. return _this;
  47500. }
  47501. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  47502. this._onlefttriggerchanged = callback;
  47503. };
  47504. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  47505. this._onrighttriggerchanged = callback;
  47506. };
  47507. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  47508. get: function () {
  47509. return this._leftTrigger;
  47510. },
  47511. set: function (newValue) {
  47512. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  47513. this._onlefttriggerchanged(newValue);
  47514. }
  47515. this._leftTrigger = newValue;
  47516. },
  47517. enumerable: true,
  47518. configurable: true
  47519. });
  47520. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  47521. get: function () {
  47522. return this._rightTrigger;
  47523. },
  47524. set: function (newValue) {
  47525. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  47526. this._onrighttriggerchanged(newValue);
  47527. }
  47528. this._rightTrigger = newValue;
  47529. },
  47530. enumerable: true,
  47531. configurable: true
  47532. });
  47533. Xbox360Pad.prototype.onbuttondown = function (callback) {
  47534. this._onbuttondown = callback;
  47535. };
  47536. Xbox360Pad.prototype.onbuttonup = function (callback) {
  47537. this._onbuttonup = callback;
  47538. };
  47539. Xbox360Pad.prototype.ondpaddown = function (callback) {
  47540. this._ondpaddown = callback;
  47541. };
  47542. Xbox360Pad.prototype.ondpadup = function (callback) {
  47543. this._ondpadup = callback;
  47544. };
  47545. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  47546. if (newValue !== currentValue) {
  47547. if (this._onbuttondown && newValue === 1) {
  47548. this._onbuttondown(buttonType);
  47549. }
  47550. if (this._onbuttonup && newValue === 0) {
  47551. this._onbuttonup(buttonType);
  47552. }
  47553. }
  47554. return newValue;
  47555. };
  47556. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  47557. if (newValue !== currentValue) {
  47558. if (this._ondpaddown && newValue === 1) {
  47559. this._ondpaddown(buttonType);
  47560. }
  47561. if (this._ondpadup && newValue === 0) {
  47562. this._ondpadup(buttonType);
  47563. }
  47564. }
  47565. return newValue;
  47566. };
  47567. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  47568. get: function () {
  47569. return this._buttonA;
  47570. },
  47571. set: function (value) {
  47572. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  47573. },
  47574. enumerable: true,
  47575. configurable: true
  47576. });
  47577. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  47578. get: function () {
  47579. return this._buttonB;
  47580. },
  47581. set: function (value) {
  47582. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  47583. },
  47584. enumerable: true,
  47585. configurable: true
  47586. });
  47587. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  47588. get: function () {
  47589. return this._buttonX;
  47590. },
  47591. set: function (value) {
  47592. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  47593. },
  47594. enumerable: true,
  47595. configurable: true
  47596. });
  47597. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  47598. get: function () {
  47599. return this._buttonY;
  47600. },
  47601. set: function (value) {
  47602. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  47603. },
  47604. enumerable: true,
  47605. configurable: true
  47606. });
  47607. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  47608. get: function () {
  47609. return this._buttonStart;
  47610. },
  47611. set: function (value) {
  47612. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  47613. },
  47614. enumerable: true,
  47615. configurable: true
  47616. });
  47617. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  47618. get: function () {
  47619. return this._buttonBack;
  47620. },
  47621. set: function (value) {
  47622. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  47623. },
  47624. enumerable: true,
  47625. configurable: true
  47626. });
  47627. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  47628. get: function () {
  47629. return this._buttonLB;
  47630. },
  47631. set: function (value) {
  47632. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  47633. },
  47634. enumerable: true,
  47635. configurable: true
  47636. });
  47637. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  47638. get: function () {
  47639. return this._buttonRB;
  47640. },
  47641. set: function (value) {
  47642. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  47643. },
  47644. enumerable: true,
  47645. configurable: true
  47646. });
  47647. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  47648. get: function () {
  47649. return this._buttonLeftStick;
  47650. },
  47651. set: function (value) {
  47652. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  47653. },
  47654. enumerable: true,
  47655. configurable: true
  47656. });
  47657. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  47658. get: function () {
  47659. return this._buttonRightStick;
  47660. },
  47661. set: function (value) {
  47662. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  47663. },
  47664. enumerable: true,
  47665. configurable: true
  47666. });
  47667. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  47668. get: function () {
  47669. return this._dPadUp;
  47670. },
  47671. set: function (value) {
  47672. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  47673. },
  47674. enumerable: true,
  47675. configurable: true
  47676. });
  47677. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  47678. get: function () {
  47679. return this._dPadDown;
  47680. },
  47681. set: function (value) {
  47682. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  47683. },
  47684. enumerable: true,
  47685. configurable: true
  47686. });
  47687. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  47688. get: function () {
  47689. return this._dPadLeft;
  47690. },
  47691. set: function (value) {
  47692. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  47693. },
  47694. enumerable: true,
  47695. configurable: true
  47696. });
  47697. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  47698. get: function () {
  47699. return this._dPadRight;
  47700. },
  47701. set: function (value) {
  47702. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  47703. },
  47704. enumerable: true,
  47705. configurable: true
  47706. });
  47707. Xbox360Pad.prototype.update = function () {
  47708. _super.prototype.update.call(this);
  47709. if (this._isXboxOnePad) {
  47710. this.buttonA = this.browserGamepad.buttons[0].value;
  47711. this.buttonB = this.browserGamepad.buttons[1].value;
  47712. this.buttonX = this.browserGamepad.buttons[2].value;
  47713. this.buttonY = this.browserGamepad.buttons[3].value;
  47714. this.buttonLB = this.browserGamepad.buttons[4].value;
  47715. this.buttonRB = this.browserGamepad.buttons[5].value;
  47716. this.leftTrigger = this.browserGamepad.axes[2];
  47717. this.rightTrigger = this.browserGamepad.axes[5];
  47718. this.buttonBack = this.browserGamepad.buttons[9].value;
  47719. this.buttonStart = this.browserGamepad.buttons[8].value;
  47720. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  47721. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  47722. this.dPadUp = this.browserGamepad.buttons[11].value;
  47723. this.dPadDown = this.browserGamepad.buttons[12].value;
  47724. this.dPadLeft = this.browserGamepad.buttons[13].value;
  47725. this.dPadRight = this.browserGamepad.buttons[14].value;
  47726. }
  47727. else {
  47728. this.buttonA = this.browserGamepad.buttons[0].value;
  47729. this.buttonB = this.browserGamepad.buttons[1].value;
  47730. this.buttonX = this.browserGamepad.buttons[2].value;
  47731. this.buttonY = this.browserGamepad.buttons[3].value;
  47732. this.buttonLB = this.browserGamepad.buttons[4].value;
  47733. this.buttonRB = this.browserGamepad.buttons[5].value;
  47734. this.leftTrigger = this.browserGamepad.buttons[6].value;
  47735. this.rightTrigger = this.browserGamepad.buttons[7].value;
  47736. this.buttonBack = this.browserGamepad.buttons[8].value;
  47737. this.buttonStart = this.browserGamepad.buttons[9].value;
  47738. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  47739. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  47740. this.dPadUp = this.browserGamepad.buttons[12].value;
  47741. this.dPadDown = this.browserGamepad.buttons[13].value;
  47742. this.dPadLeft = this.browserGamepad.buttons[14].value;
  47743. this.dPadRight = this.browserGamepad.buttons[15].value;
  47744. }
  47745. };
  47746. return Xbox360Pad;
  47747. }(Gamepad));
  47748. BABYLON.Xbox360Pad = Xbox360Pad;
  47749. })(BABYLON || (BABYLON = {}));
  47750. //# sourceMappingURL=babylon.gamepads.js.map
  47751. var BABYLON;
  47752. (function (BABYLON) {
  47753. // We're mainly based on the logic defined into the FreeCamera code
  47754. var GamepadCamera = (function (_super) {
  47755. __extends(GamepadCamera, _super);
  47756. //-- end properties for backward compatibility for inputs
  47757. function GamepadCamera(name, position, scene) {
  47758. var _this;
  47759. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  47760. _this = _super.call(this, name, position, scene) || this;
  47761. return _this;
  47762. }
  47763. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  47764. //-- Begin properties for backward compatibility for inputs
  47765. get: function () {
  47766. var gamepad = this.inputs.attached["gamepad"];
  47767. if (gamepad)
  47768. return gamepad.gamepadAngularSensibility;
  47769. },
  47770. set: function (value) {
  47771. var gamepad = this.inputs.attached["gamepad"];
  47772. if (gamepad)
  47773. gamepad.gamepadAngularSensibility = value;
  47774. },
  47775. enumerable: true,
  47776. configurable: true
  47777. });
  47778. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  47779. get: function () {
  47780. var gamepad = this.inputs.attached["gamepad"];
  47781. if (gamepad)
  47782. return gamepad.gamepadMoveSensibility;
  47783. },
  47784. set: function (value) {
  47785. var gamepad = this.inputs.attached["gamepad"];
  47786. if (gamepad)
  47787. gamepad.gamepadMoveSensibility = value;
  47788. },
  47789. enumerable: true,
  47790. configurable: true
  47791. });
  47792. GamepadCamera.prototype.getClassName = function () {
  47793. return "GamepadCamera";
  47794. };
  47795. return GamepadCamera;
  47796. }(BABYLON.UniversalCamera));
  47797. BABYLON.GamepadCamera = GamepadCamera;
  47798. })(BABYLON || (BABYLON = {}));
  47799. //# sourceMappingURL=babylon.gamepadCamera.js.map
  47800. var BABYLON;
  47801. (function (BABYLON) {
  47802. var Analyser = (function () {
  47803. function Analyser(scene) {
  47804. this.SMOOTHING = 0.75;
  47805. this.FFT_SIZE = 512;
  47806. this.BARGRAPHAMPLITUDE = 256;
  47807. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  47808. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  47809. this._scene = scene;
  47810. this._audioEngine = BABYLON.Engine.audioEngine;
  47811. if (this._audioEngine.canUseWebAudio) {
  47812. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  47813. this._webAudioAnalyser.minDecibels = -140;
  47814. this._webAudioAnalyser.maxDecibels = 0;
  47815. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47816. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47817. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  47818. }
  47819. }
  47820. Analyser.prototype.getFrequencyBinCount = function () {
  47821. if (this._audioEngine.canUseWebAudio) {
  47822. return this._webAudioAnalyser.frequencyBinCount;
  47823. }
  47824. else {
  47825. return 0;
  47826. }
  47827. };
  47828. Analyser.prototype.getByteFrequencyData = function () {
  47829. if (this._audioEngine.canUseWebAudio) {
  47830. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47831. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47832. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  47833. }
  47834. return this._byteFreqs;
  47835. };
  47836. Analyser.prototype.getByteTimeDomainData = function () {
  47837. if (this._audioEngine.canUseWebAudio) {
  47838. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47839. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47840. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  47841. }
  47842. return this._byteTime;
  47843. };
  47844. Analyser.prototype.getFloatFrequencyData = function () {
  47845. if (this._audioEngine.canUseWebAudio) {
  47846. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47847. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47848. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  47849. }
  47850. return this._floatFreqs;
  47851. };
  47852. Analyser.prototype.drawDebugCanvas = function () {
  47853. var _this = this;
  47854. if (this._audioEngine.canUseWebAudio) {
  47855. if (!this._debugCanvas) {
  47856. this._debugCanvas = document.createElement("canvas");
  47857. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  47858. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  47859. this._debugCanvas.style.position = "absolute";
  47860. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  47861. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  47862. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  47863. document.body.appendChild(this._debugCanvas);
  47864. this._registerFunc = function () {
  47865. _this.drawDebugCanvas();
  47866. };
  47867. this._scene.registerBeforeRender(this._registerFunc);
  47868. }
  47869. if (this._registerFunc) {
  47870. var workingArray = this.getByteFrequencyData();
  47871. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  47872. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  47873. // Draw the frequency domain chart.
  47874. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  47875. var value = workingArray[i];
  47876. var percent = value / this.BARGRAPHAMPLITUDE;
  47877. var height = this.DEBUGCANVASSIZE.height * percent;
  47878. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  47879. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  47880. var hue = i / this.getFrequencyBinCount() * 360;
  47881. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  47882. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  47883. }
  47884. }
  47885. }
  47886. };
  47887. Analyser.prototype.stopDebugCanvas = function () {
  47888. if (this._debugCanvas) {
  47889. this._scene.unregisterBeforeRender(this._registerFunc);
  47890. this._registerFunc = null;
  47891. document.body.removeChild(this._debugCanvas);
  47892. this._debugCanvas = null;
  47893. this._debugCanvasContext = null;
  47894. }
  47895. };
  47896. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  47897. if (this._audioEngine.canUseWebAudio) {
  47898. inputAudioNode.connect(this._webAudioAnalyser);
  47899. this._webAudioAnalyser.connect(outputAudioNode);
  47900. }
  47901. };
  47902. Analyser.prototype.dispose = function () {
  47903. if (this._audioEngine.canUseWebAudio) {
  47904. this._webAudioAnalyser.disconnect();
  47905. }
  47906. };
  47907. return Analyser;
  47908. }());
  47909. BABYLON.Analyser = Analyser;
  47910. })(BABYLON || (BABYLON = {}));
  47911. //# sourceMappingURL=babylon.analyser.js.map
  47912. var BABYLON;
  47913. (function (BABYLON) {
  47914. var DepthRenderer = (function () {
  47915. function DepthRenderer(scene, type) {
  47916. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  47917. var _this = this;
  47918. this._viewMatrix = BABYLON.Matrix.Zero();
  47919. this._projectionMatrix = BABYLON.Matrix.Zero();
  47920. this._transformMatrix = BABYLON.Matrix.Zero();
  47921. this._worldViewProjection = BABYLON.Matrix.Zero();
  47922. this._scene = scene;
  47923. var engine = scene.getEngine();
  47924. // Render target
  47925. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  47926. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47927. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47928. this._depthMap.refreshRate = 1;
  47929. this._depthMap.renderParticles = false;
  47930. this._depthMap.renderList = null;
  47931. // set default depth value to 1.0 (far away)
  47932. this._depthMap.onClearObservable.add(function (engine) {
  47933. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47934. });
  47935. // Custom render function
  47936. var renderSubMesh = function (subMesh) {
  47937. var mesh = subMesh.getRenderingMesh();
  47938. var scene = _this._scene;
  47939. var engine = scene.getEngine();
  47940. // Culling
  47941. engine.setState(subMesh.getMaterial().backFaceCulling);
  47942. // Managing instances
  47943. var batch = mesh._getInstancesRenderList(subMesh._id);
  47944. if (batch.mustReturn) {
  47945. return;
  47946. }
  47947. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47948. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47949. engine.enableEffect(_this._effect);
  47950. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  47951. var material = subMesh.getMaterial();
  47952. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47953. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  47954. // Alpha test
  47955. if (material && material.needAlphaTesting()) {
  47956. var alphaTexture = material.getAlphaTestTexture();
  47957. _this._effect.setTexture("diffuseSampler", alphaTexture);
  47958. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47959. }
  47960. // Bones
  47961. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47962. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47963. }
  47964. // Draw
  47965. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47966. }
  47967. };
  47968. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  47969. var index;
  47970. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47971. renderSubMesh(opaqueSubMeshes.data[index]);
  47972. }
  47973. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47974. renderSubMesh(alphaTestSubMeshes.data[index]);
  47975. }
  47976. };
  47977. }
  47978. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  47979. var material = subMesh.getMaterial();
  47980. if (material.disableDepthWrite) {
  47981. return false;
  47982. }
  47983. var defines = [];
  47984. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47985. var mesh = subMesh.getMesh();
  47986. var scene = mesh.getScene();
  47987. // Alpha test
  47988. if (material && material.needAlphaTesting()) {
  47989. defines.push("#define ALPHATEST");
  47990. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47991. attribs.push(BABYLON.VertexBuffer.UVKind);
  47992. defines.push("#define UV1");
  47993. }
  47994. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47995. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47996. defines.push("#define UV2");
  47997. }
  47998. }
  47999. // Bones
  48000. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48001. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48002. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48003. if (mesh.numBoneInfluencers > 4) {
  48004. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  48005. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  48006. }
  48007. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48008. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48009. }
  48010. else {
  48011. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48012. }
  48013. // Instances
  48014. if (useInstances) {
  48015. defines.push("#define INSTANCES");
  48016. attribs.push("world0");
  48017. attribs.push("world1");
  48018. attribs.push("world2");
  48019. attribs.push("world3");
  48020. }
  48021. // Get correct effect
  48022. var join = defines.join("\n");
  48023. if (this._cachedDefines !== join) {
  48024. this._cachedDefines = join;
  48025. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  48026. }
  48027. return this._effect.isReady();
  48028. };
  48029. DepthRenderer.prototype.getDepthMap = function () {
  48030. return this._depthMap;
  48031. };
  48032. // Methods
  48033. DepthRenderer.prototype.dispose = function () {
  48034. this._depthMap.dispose();
  48035. };
  48036. return DepthRenderer;
  48037. }());
  48038. BABYLON.DepthRenderer = DepthRenderer;
  48039. })(BABYLON || (BABYLON = {}));
  48040. //# sourceMappingURL=babylon.depthRenderer.js.map
  48041. var BABYLON;
  48042. (function (BABYLON) {
  48043. var SSAORenderingPipeline = (function (_super) {
  48044. __extends(SSAORenderingPipeline, _super);
  48045. /**
  48046. * @constructor
  48047. * @param {string} name - The rendering pipeline name
  48048. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48049. * @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 }
  48050. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48051. */
  48052. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  48053. var _this = _super.call(this, scene.getEngine(), name) || this;
  48054. // Members
  48055. /**
  48056. * The PassPostProcess id in the pipeline that contains the original scene color
  48057. * @type {string}
  48058. */
  48059. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  48060. /**
  48061. * The SSAO PostProcess id in the pipeline
  48062. * @type {string}
  48063. */
  48064. _this.SSAORenderEffect = "SSAORenderEffect";
  48065. /**
  48066. * The horizontal blur PostProcess id in the pipeline
  48067. * @type {string}
  48068. */
  48069. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  48070. /**
  48071. * The vertical blur PostProcess id in the pipeline
  48072. * @type {string}
  48073. */
  48074. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  48075. /**
  48076. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  48077. * @type {string}
  48078. */
  48079. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  48080. /**
  48081. * The output strength of the SSAO post-process. Default value is 1.0.
  48082. * @type {number}
  48083. */
  48084. _this.totalStrength = 1.0;
  48085. /**
  48086. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  48087. * @type {number}
  48088. */
  48089. _this.radius = 0.0001;
  48090. /**
  48091. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  48092. * Must not be equal to fallOff and superior to fallOff.
  48093. * Default value is 0.975
  48094. * @type {number}
  48095. */
  48096. _this.area = 0.0075;
  48097. /**
  48098. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  48099. * Must not be equal to area and inferior to area.
  48100. * Default value is 0.0
  48101. * @type {number}
  48102. */
  48103. _this.fallOff = 0.000001;
  48104. /**
  48105. * The base color of the SSAO post-process
  48106. * The final result is "base + ssao" between [0, 1]
  48107. * @type {number}
  48108. */
  48109. _this.base = 0.5;
  48110. _this._firstUpdate = true;
  48111. _this._scene = scene;
  48112. // Set up assets
  48113. _this._createRandomTexture();
  48114. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  48115. var ssaoRatio = ratio.ssaoRatio || ratio;
  48116. var combineRatio = ratio.combineRatio || ratio;
  48117. _this._ratio = {
  48118. ssaoRatio: ssaoRatio,
  48119. combineRatio: combineRatio
  48120. };
  48121. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48122. _this._createSSAOPostProcess(ssaoRatio);
  48123. _this._createBlurPostProcess(ssaoRatio);
  48124. _this._createSSAOCombinePostProcess(combineRatio);
  48125. // Set up pipeline
  48126. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  48127. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  48128. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  48129. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  48130. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  48131. // Finish
  48132. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48133. if (cameras)
  48134. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48135. return _this;
  48136. }
  48137. // Public Methods
  48138. /**
  48139. * Returns the horizontal blur PostProcess
  48140. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  48141. */
  48142. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  48143. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  48144. return null;
  48145. };
  48146. /**
  48147. * Returns the vertical blur PostProcess
  48148. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  48149. */
  48150. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  48151. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  48152. return null;
  48153. };
  48154. /**
  48155. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  48156. */
  48157. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  48158. if (disableDepthRender === void 0) { disableDepthRender = false; }
  48159. for (var i = 0; i < this._scene.cameras.length; i++) {
  48160. var camera = this._scene.cameras[i];
  48161. this._originalColorPostProcess.dispose(camera);
  48162. this._ssaoPostProcess.dispose(camera);
  48163. this._blurHPostProcess.dispose(camera);
  48164. this._blurVPostProcess.dispose(camera);
  48165. this._ssaoCombinePostProcess.dispose(camera);
  48166. }
  48167. this._randomTexture.dispose();
  48168. if (disableDepthRender)
  48169. this._scene.disableDepthRenderer();
  48170. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48171. _super.prototype.dispose.call(this);
  48172. };
  48173. // Private Methods
  48174. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  48175. var _this = this;
  48176. /*
  48177. var samplerOffsets = [
  48178. -8.0, -6.0, -4.0, -2.0,
  48179. 0.0,
  48180. 2.0, 4.0, 6.0, 8.0
  48181. ];
  48182. */
  48183. var samples = 16;
  48184. var samplerOffsets = [];
  48185. for (var i = -8; i < 8; i++) {
  48186. samplerOffsets.push(i * 2);
  48187. }
  48188. 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");
  48189. this._blurHPostProcess.onApply = function (effect) {
  48190. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  48191. effect.setTexture("depthSampler", _this._depthTexture);
  48192. if (_this._firstUpdate) {
  48193. effect.setArray("samplerOffsets", samplerOffsets);
  48194. }
  48195. };
  48196. 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");
  48197. this._blurVPostProcess.onApply = function (effect) {
  48198. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  48199. effect.setTexture("depthSampler", _this._depthTexture);
  48200. if (_this._firstUpdate) {
  48201. effect.setArray("samplerOffsets", samplerOffsets);
  48202. _this._firstUpdate = false;
  48203. }
  48204. };
  48205. };
  48206. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  48207. var _this = this;
  48208. var numSamples = 16;
  48209. var sampleSphere = [
  48210. 0.5381, 0.1856, -0.4319,
  48211. 0.1379, 0.2486, 0.4430,
  48212. 0.3371, 0.5679, -0.0057,
  48213. -0.6999, -0.0451, -0.0019,
  48214. 0.0689, -0.1598, -0.8547,
  48215. 0.0560, 0.0069, -0.1843,
  48216. -0.0146, 0.1402, 0.0762,
  48217. 0.0100, -0.1924, -0.0344,
  48218. -0.3577, -0.5301, -0.4358,
  48219. -0.3169, 0.1063, 0.0158,
  48220. 0.0103, -0.5869, 0.0046,
  48221. -0.0897, -0.4940, 0.3287,
  48222. 0.7119, -0.0154, -0.0918,
  48223. -0.0533, 0.0596, -0.5411,
  48224. 0.0352, -0.0631, 0.5460,
  48225. -0.4776, 0.2847, -0.0271
  48226. ];
  48227. var samplesFactor = 1.0 / numSamples;
  48228. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  48229. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  48230. "area", "fallOff", "base", "range", "viewport"
  48231. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  48232. var viewport = new BABYLON.Vector2(0, 0);
  48233. this._ssaoPostProcess.onApply = function (effect) {
  48234. if (_this._firstUpdate) {
  48235. effect.setArray3("sampleSphere", sampleSphere);
  48236. effect.setFloat("samplesFactor", samplesFactor);
  48237. effect.setFloat("randTextureTiles", 4.0);
  48238. }
  48239. effect.setFloat("totalStrength", _this.totalStrength);
  48240. effect.setFloat("radius", _this.radius);
  48241. effect.setFloat("area", _this.area);
  48242. effect.setFloat("fallOff", _this.fallOff);
  48243. effect.setFloat("base", _this.base);
  48244. effect.setTexture("textureSampler", _this._depthTexture);
  48245. effect.setTexture("randomSampler", _this._randomTexture);
  48246. };
  48247. };
  48248. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  48249. var _this = this;
  48250. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48251. this._ssaoCombinePostProcess.onApply = function (effect) {
  48252. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  48253. };
  48254. };
  48255. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  48256. var size = 512;
  48257. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48258. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48259. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48260. var context = this._randomTexture.getContext();
  48261. var rand = function (min, max) {
  48262. return Math.random() * (max - min) + min;
  48263. };
  48264. var randVector = BABYLON.Vector3.Zero();
  48265. for (var x = 0; x < size; x++) {
  48266. for (var y = 0; y < size; y++) {
  48267. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  48268. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  48269. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  48270. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  48271. context.fillRect(x, y, 1, 1);
  48272. }
  48273. }
  48274. this._randomTexture.update(false);
  48275. };
  48276. return SSAORenderingPipeline;
  48277. }(BABYLON.PostProcessRenderPipeline));
  48278. __decorate([
  48279. BABYLON.serialize()
  48280. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  48281. __decorate([
  48282. BABYLON.serialize()
  48283. ], SSAORenderingPipeline.prototype, "radius", void 0);
  48284. __decorate([
  48285. BABYLON.serialize()
  48286. ], SSAORenderingPipeline.prototype, "area", void 0);
  48287. __decorate([
  48288. BABYLON.serialize()
  48289. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  48290. __decorate([
  48291. BABYLON.serialize()
  48292. ], SSAORenderingPipeline.prototype, "base", void 0);
  48293. __decorate([
  48294. BABYLON.serialize()
  48295. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  48296. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  48297. })(BABYLON || (BABYLON = {}));
  48298. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  48299. var BABYLON;
  48300. (function (BABYLON) {
  48301. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  48302. var VolumetricLightScatteringPostProcess = (function (_super) {
  48303. __extends(VolumetricLightScatteringPostProcess, _super);
  48304. /**
  48305. * @constructor
  48306. * @param {string} name - The post-process name
  48307. * @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)
  48308. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  48309. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  48310. * @param {number} samples - The post-process quality, default 100
  48311. * @param {number} samplingMode - The post-process filtering mode
  48312. * @param {BABYLON.Engine} engine - The babylon engine
  48313. * @param {boolean} reusable - If the post-process is reusable
  48314. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  48315. */
  48316. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  48317. if (samples === void 0) { samples = 100; }
  48318. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48319. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  48320. _this._screenCoordinates = BABYLON.Vector2.Zero();
  48321. /**
  48322. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  48323. * @type {Vector3}
  48324. */
  48325. _this.customMeshPosition = BABYLON.Vector3.Zero();
  48326. /**
  48327. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  48328. * @type {boolean}
  48329. */
  48330. _this.useCustomMeshPosition = false;
  48331. /**
  48332. * If the post-process should inverse the light scattering direction
  48333. * @type {boolean}
  48334. */
  48335. _this.invert = true;
  48336. /**
  48337. * Array containing the excluded meshes not rendered in the internal pass
  48338. */
  48339. _this.excludedMeshes = new Array();
  48340. /**
  48341. * Controls the overall intensity of the post-process
  48342. * @type {number}
  48343. */
  48344. _this.exposure = 0.3;
  48345. /**
  48346. * Dissipates each sample's contribution in range [0, 1]
  48347. * @type {number}
  48348. */
  48349. _this.decay = 0.96815;
  48350. /**
  48351. * Controls the overall intensity of each sample
  48352. * @type {number}
  48353. */
  48354. _this.weight = 0.58767;
  48355. /**
  48356. * Controls the density of each sample
  48357. * @type {number}
  48358. */
  48359. _this.density = 0.926;
  48360. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  48361. var engine = scene.getEngine();
  48362. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  48363. // Configure mesh
  48364. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  48365. // Configure
  48366. _this._createPass(scene, ratio.passRatio || ratio);
  48367. _this.onActivate = function (camera) {
  48368. if (!_this.isSupported) {
  48369. _this.dispose(camera);
  48370. }
  48371. _this.onActivate = null;
  48372. };
  48373. _this.onApplyObservable.add(function (effect) {
  48374. _this._updateMeshScreenCoordinates(scene);
  48375. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  48376. effect.setFloat("exposure", _this.exposure);
  48377. effect.setFloat("decay", _this.decay);
  48378. effect.setFloat("weight", _this.weight);
  48379. effect.setFloat("density", _this.density);
  48380. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  48381. });
  48382. return _this;
  48383. }
  48384. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  48385. get: function () {
  48386. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48387. return false;
  48388. },
  48389. set: function (useDiffuseColor) {
  48390. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  48391. },
  48392. enumerable: true,
  48393. configurable: true
  48394. });
  48395. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  48396. var mesh = subMesh.getMesh();
  48397. // Render this.mesh as default
  48398. if (mesh === this.mesh) {
  48399. return mesh.material.isReady(mesh);
  48400. }
  48401. var defines = [];
  48402. var attribs = [BABYLON.VertexBuffer.PositionKind];
  48403. var material = subMesh.getMaterial();
  48404. var needUV = false;
  48405. // Alpha test
  48406. if (material) {
  48407. if (material.needAlphaTesting()) {
  48408. defines.push("#define ALPHATEST");
  48409. }
  48410. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  48411. attribs.push(BABYLON.VertexBuffer.UVKind);
  48412. defines.push("#define UV1");
  48413. }
  48414. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  48415. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  48416. defines.push("#define UV2");
  48417. }
  48418. }
  48419. // Bones
  48420. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48421. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  48422. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  48423. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  48424. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  48425. }
  48426. else {
  48427. defines.push("#define NUM_BONE_INFLUENCERS 0");
  48428. }
  48429. // Instances
  48430. if (useInstances) {
  48431. defines.push("#define INSTANCES");
  48432. attribs.push("world0");
  48433. attribs.push("world1");
  48434. attribs.push("world2");
  48435. attribs.push("world3");
  48436. }
  48437. // Get correct effect
  48438. var join = defines.join("\n");
  48439. if (this._cachedDefines !== join) {
  48440. this._cachedDefines = join;
  48441. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  48442. }
  48443. return this._volumetricLightScatteringPass.isReady();
  48444. };
  48445. /**
  48446. * Sets the new light position for light scattering effect
  48447. * @param {BABYLON.Vector3} The new custom light position
  48448. */
  48449. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  48450. this.customMeshPosition = position;
  48451. };
  48452. /**
  48453. * Returns the light position for light scattering effect
  48454. * @return {BABYLON.Vector3} The custom light position
  48455. */
  48456. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  48457. return this.customMeshPosition;
  48458. };
  48459. /**
  48460. * Disposes the internal assets and detaches the post-process from the camera
  48461. */
  48462. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  48463. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  48464. if (rttIndex !== -1) {
  48465. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  48466. }
  48467. this._volumetricLightScatteringRTT.dispose();
  48468. _super.prototype.dispose.call(this, camera);
  48469. };
  48470. /**
  48471. * Returns the render target texture used by the post-process
  48472. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  48473. */
  48474. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  48475. return this._volumetricLightScatteringRTT;
  48476. };
  48477. // Private methods
  48478. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  48479. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  48480. return true;
  48481. }
  48482. return false;
  48483. };
  48484. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  48485. var _this = this;
  48486. var engine = scene.getEngine();
  48487. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  48488. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48489. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48490. this._volumetricLightScatteringRTT.renderList = null;
  48491. this._volumetricLightScatteringRTT.renderParticles = false;
  48492. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  48493. // Custom render function for submeshes
  48494. var renderSubMesh = function (subMesh) {
  48495. var mesh = subMesh.getRenderingMesh();
  48496. if (_this._meshExcluded(mesh)) {
  48497. return;
  48498. }
  48499. var scene = mesh.getScene();
  48500. var engine = scene.getEngine();
  48501. // Culling
  48502. engine.setState(subMesh.getMaterial().backFaceCulling);
  48503. // Managing instances
  48504. var batch = mesh._getInstancesRenderList(subMesh._id);
  48505. if (batch.mustReturn) {
  48506. return;
  48507. }
  48508. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  48509. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  48510. var effect = _this._volumetricLightScatteringPass;
  48511. if (mesh === _this.mesh) {
  48512. effect = subMesh.getMaterial().getEffect();
  48513. }
  48514. engine.enableEffect(effect);
  48515. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  48516. if (mesh === _this.mesh) {
  48517. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  48518. }
  48519. else {
  48520. var material = subMesh.getMaterial();
  48521. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  48522. // Alpha test
  48523. if (material && material.needAlphaTesting()) {
  48524. var alphaTexture = material.getAlphaTestTexture();
  48525. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  48526. if (alphaTexture) {
  48527. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  48528. }
  48529. }
  48530. // Bones
  48531. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  48532. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  48533. }
  48534. }
  48535. // Draw
  48536. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  48537. }
  48538. };
  48539. // Render target texture callbacks
  48540. var savedSceneClearColor;
  48541. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  48542. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  48543. savedSceneClearColor = scene.clearColor;
  48544. scene.clearColor = sceneClearColor;
  48545. });
  48546. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  48547. scene.clearColor = savedSceneClearColor;
  48548. });
  48549. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  48550. var engine = scene.getEngine();
  48551. var index;
  48552. for (index = 0; index < opaqueSubMeshes.length; index++) {
  48553. renderSubMesh(opaqueSubMeshes.data[index]);
  48554. }
  48555. engine.setAlphaTesting(true);
  48556. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  48557. renderSubMesh(alphaTestSubMeshes.data[index]);
  48558. }
  48559. engine.setAlphaTesting(false);
  48560. if (transparentSubMeshes.length) {
  48561. // Sort sub meshes
  48562. for (index = 0; index < transparentSubMeshes.length; index++) {
  48563. var submesh = transparentSubMeshes.data[index];
  48564. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  48565. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  48566. }
  48567. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  48568. sortedArray.sort(function (a, b) {
  48569. // Alpha index first
  48570. if (a._alphaIndex > b._alphaIndex) {
  48571. return 1;
  48572. }
  48573. if (a._alphaIndex < b._alphaIndex) {
  48574. return -1;
  48575. }
  48576. // Then distance to camera
  48577. if (a._distanceToCamera < b._distanceToCamera) {
  48578. return 1;
  48579. }
  48580. if (a._distanceToCamera > b._distanceToCamera) {
  48581. return -1;
  48582. }
  48583. return 0;
  48584. });
  48585. // Render sub meshes
  48586. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  48587. for (index = 0; index < sortedArray.length; index++) {
  48588. renderSubMesh(sortedArray[index]);
  48589. }
  48590. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  48591. }
  48592. };
  48593. };
  48594. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  48595. var transform = scene.getTransformMatrix();
  48596. var meshPosition;
  48597. if (this.useCustomMeshPosition) {
  48598. meshPosition = this.customMeshPosition;
  48599. }
  48600. else if (this.attachedNode) {
  48601. meshPosition = this.attachedNode.position;
  48602. }
  48603. else {
  48604. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  48605. }
  48606. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  48607. this._screenCoordinates.x = pos.x / this._viewPort.width;
  48608. this._screenCoordinates.y = pos.y / this._viewPort.height;
  48609. if (this.invert)
  48610. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  48611. };
  48612. // Static methods
  48613. /**
  48614. * Creates a default mesh for the Volumeric Light Scattering post-process
  48615. * @param {string} The mesh name
  48616. * @param {BABYLON.Scene} The scene where to create the mesh
  48617. * @return {BABYLON.Mesh} the default mesh
  48618. */
  48619. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  48620. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  48621. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  48622. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  48623. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  48624. mesh.material = material;
  48625. return mesh;
  48626. };
  48627. return VolumetricLightScatteringPostProcess;
  48628. }(BABYLON.PostProcess));
  48629. __decorate([
  48630. BABYLON.serializeAsVector3()
  48631. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  48632. __decorate([
  48633. BABYLON.serialize()
  48634. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  48635. __decorate([
  48636. BABYLON.serialize()
  48637. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  48638. __decorate([
  48639. BABYLON.serializeAsMeshReference()
  48640. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  48641. __decorate([
  48642. BABYLON.serialize()
  48643. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  48644. __decorate([
  48645. BABYLON.serialize()
  48646. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  48647. __decorate([
  48648. BABYLON.serialize()
  48649. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  48650. __decorate([
  48651. BABYLON.serialize()
  48652. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  48653. __decorate([
  48654. BABYLON.serialize()
  48655. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  48656. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  48657. })(BABYLON || (BABYLON = {}));
  48658. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  48659. // BABYLON.JS Chromatic Aberration GLSL Shader
  48660. // Author: Olivier Guyot
  48661. // Separates very slightly R, G and B colors on the edges of the screen
  48662. // Inspired by Francois Tarlier & Martins Upitis
  48663. var BABYLON;
  48664. (function (BABYLON) {
  48665. var LensRenderingPipeline = (function (_super) {
  48666. __extends(LensRenderingPipeline, _super);
  48667. /**
  48668. * @constructor
  48669. *
  48670. * Effect parameters are as follow:
  48671. * {
  48672. * chromatic_aberration: number; // from 0 to x (1 for realism)
  48673. * edge_blur: number; // from 0 to x (1 for realism)
  48674. * distortion: number; // from 0 to x (1 for realism)
  48675. * grain_amount: number; // from 0 to 1
  48676. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  48677. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  48678. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  48679. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  48680. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  48681. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  48682. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  48683. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  48684. * }
  48685. * Note: if an effect parameter is unset, effect is disabled
  48686. *
  48687. * @param {string} name - The rendering pipeline name
  48688. * @param {object} parameters - An object containing all parameters (see above)
  48689. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48690. * @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)
  48691. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48692. */
  48693. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  48694. if (ratio === void 0) { ratio = 1.0; }
  48695. var _this = _super.call(this, scene.getEngine(), name) || this;
  48696. // Lens effects can be of the following:
  48697. // - chromatic aberration (slight shift of RGB colors)
  48698. // - blur on the edge of the lens
  48699. // - lens distortion
  48700. // - depth-of-field blur & highlights enhancing
  48701. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  48702. // - grain effect (noise or custom texture)
  48703. // Two additional texture samplers are needed:
  48704. // - depth map (for depth-of-field)
  48705. // - grain texture
  48706. /**
  48707. * The chromatic aberration PostProcess id in the pipeline
  48708. * @type {string}
  48709. */
  48710. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  48711. /**
  48712. * The highlights enhancing PostProcess id in the pipeline
  48713. * @type {string}
  48714. */
  48715. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  48716. /**
  48717. * The depth-of-field PostProcess id in the pipeline
  48718. * @type {string}
  48719. */
  48720. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  48721. _this._scene = scene;
  48722. // Fetch texture samplers
  48723. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  48724. if (parameters.grain_texture) {
  48725. _this._grainTexture = parameters.grain_texture;
  48726. }
  48727. else {
  48728. _this._createGrainTexture();
  48729. }
  48730. // save parameters
  48731. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  48732. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  48733. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  48734. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  48735. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  48736. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  48737. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  48738. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  48739. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  48740. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  48741. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  48742. // Create effects
  48743. _this._createChromaticAberrationPostProcess(ratio);
  48744. _this._createHighlightsPostProcess(ratio);
  48745. _this._createDepthOfFieldPostProcess(ratio / 4);
  48746. // Set up pipeline
  48747. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  48748. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  48749. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  48750. if (_this._highlightsGain === -1) {
  48751. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  48752. }
  48753. // Finish
  48754. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48755. if (cameras) {
  48756. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48757. }
  48758. return _this;
  48759. }
  48760. // public methods (self explanatory)
  48761. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  48762. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  48763. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  48764. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  48765. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  48766. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  48767. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  48768. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  48769. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  48770. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  48771. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  48772. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  48773. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  48774. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  48775. };
  48776. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  48777. this._highlightsPostProcess.updateEffect();
  48778. };
  48779. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  48780. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  48781. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  48782. this._highlightsGain = amount;
  48783. };
  48784. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  48785. if (this._highlightsGain === -1) {
  48786. this._highlightsGain = 1.0;
  48787. }
  48788. this._highlightsThreshold = amount;
  48789. };
  48790. LensRenderingPipeline.prototype.disableHighlights = function () {
  48791. this._highlightsGain = -1;
  48792. };
  48793. /**
  48794. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  48795. */
  48796. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  48797. if (disableDepthRender === void 0) { disableDepthRender = false; }
  48798. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48799. this._chromaticAberrationPostProcess = undefined;
  48800. this._highlightsPostProcess = undefined;
  48801. this._depthOfFieldPostProcess = undefined;
  48802. this._grainTexture.dispose();
  48803. if (disableDepthRender)
  48804. this._scene.disableDepthRenderer();
  48805. };
  48806. // colors shifting and distortion
  48807. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  48808. var _this = this;
  48809. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  48810. [], // samplers
  48811. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48812. this._chromaticAberrationPostProcess.onApply = function (effect) {
  48813. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  48814. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48815. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48816. };
  48817. };
  48818. // highlights enhancing
  48819. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  48820. var _this = this;
  48821. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  48822. [], // samplers
  48823. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  48824. this._highlightsPostProcess.onApply = function (effect) {
  48825. effect.setFloat('gain', _this._highlightsGain);
  48826. effect.setFloat('threshold', _this._highlightsThreshold);
  48827. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  48828. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48829. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48830. };
  48831. };
  48832. // colors shifting and distortion
  48833. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  48834. var _this = this;
  48835. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  48836. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  48837. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  48838. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48839. this._depthOfFieldPostProcess.onApply = function (effect) {
  48840. effect.setTexture("depthSampler", _this._depthTexture);
  48841. effect.setTexture("grainSampler", _this._grainTexture);
  48842. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  48843. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  48844. effect.setFloat('grain_amount', _this._grainAmount);
  48845. effect.setBool('blur_noise', _this._blurNoise);
  48846. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48847. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48848. effect.setFloat('distortion', _this._distortion);
  48849. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  48850. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  48851. effect.setFloat('aperture', _this._dofAperture);
  48852. effect.setFloat('darken', _this._dofDarken);
  48853. effect.setFloat('edge_blur', _this._edgeBlur);
  48854. effect.setBool('highlights', (_this._highlightsGain !== -1));
  48855. effect.setFloat('near', _this._scene.activeCamera.minZ);
  48856. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  48857. };
  48858. };
  48859. // creates a black and white random noise texture, 512x512
  48860. LensRenderingPipeline.prototype._createGrainTexture = function () {
  48861. var size = 512;
  48862. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48863. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48864. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48865. var context = this._grainTexture.getContext();
  48866. var rand = function (min, max) {
  48867. return Math.random() * (max - min) + min;
  48868. };
  48869. var value;
  48870. for (var x = 0; x < size; x++) {
  48871. for (var y = 0; y < size; y++) {
  48872. value = Math.floor(rand(0.42, 0.58) * 255);
  48873. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  48874. context.fillRect(x, y, 1, 1);
  48875. }
  48876. }
  48877. this._grainTexture.update(false);
  48878. };
  48879. return LensRenderingPipeline;
  48880. }(BABYLON.PostProcessRenderPipeline));
  48881. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  48882. })(BABYLON || (BABYLON = {}));
  48883. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  48884. //
  48885. // This post-process allows the modification of rendered colors by using
  48886. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48887. //
  48888. // The object needs to be provided an url to a texture containing the color
  48889. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48890. // Use an image editing software to tweak the LUT to match your needs.
  48891. //
  48892. // For an example of a color LUT, see here:
  48893. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48894. // For explanations on color grading, see here:
  48895. // http://udn.epicgames.com/Three/ColorGrading.html
  48896. //
  48897. var BABYLON;
  48898. (function (BABYLON) {
  48899. var ColorCorrectionPostProcess = (function (_super) {
  48900. __extends(ColorCorrectionPostProcess, _super);
  48901. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48902. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  48903. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48904. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  48905. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48906. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48907. _this.onApply = function (effect) {
  48908. effect.setTexture("colorTable", _this._colorTableTexture);
  48909. };
  48910. return _this;
  48911. }
  48912. return ColorCorrectionPostProcess;
  48913. }(BABYLON.PostProcess));
  48914. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48915. })(BABYLON || (BABYLON = {}));
  48916. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  48917. var BABYLON;
  48918. (function (BABYLON) {
  48919. var AnaglyphFreeCamera = (function (_super) {
  48920. __extends(AnaglyphFreeCamera, _super);
  48921. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  48922. var _this = _super.call(this, name, position, scene) || this;
  48923. _this.interaxialDistance = interaxialDistance;
  48924. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48925. return _this;
  48926. }
  48927. AnaglyphFreeCamera.prototype.getClassName = function () {
  48928. return "AnaglyphFreeCamera";
  48929. };
  48930. return AnaglyphFreeCamera;
  48931. }(BABYLON.FreeCamera));
  48932. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  48933. var AnaglyphArcRotateCamera = (function (_super) {
  48934. __extends(AnaglyphArcRotateCamera, _super);
  48935. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  48936. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48937. _this.interaxialDistance = interaxialDistance;
  48938. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48939. return _this;
  48940. }
  48941. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  48942. return "AnaglyphArcRotateCamera";
  48943. };
  48944. return AnaglyphArcRotateCamera;
  48945. }(BABYLON.ArcRotateCamera));
  48946. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  48947. var AnaglyphGamepadCamera = (function (_super) {
  48948. __extends(AnaglyphGamepadCamera, _super);
  48949. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  48950. var _this = _super.call(this, name, position, scene) || this;
  48951. _this.interaxialDistance = interaxialDistance;
  48952. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48953. return _this;
  48954. }
  48955. AnaglyphGamepadCamera.prototype.getClassName = function () {
  48956. return "AnaglyphGamepadCamera";
  48957. };
  48958. return AnaglyphGamepadCamera;
  48959. }(BABYLON.GamepadCamera));
  48960. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  48961. var AnaglyphUniversalCamera = (function (_super) {
  48962. __extends(AnaglyphUniversalCamera, _super);
  48963. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  48964. var _this = _super.call(this, name, position, scene) || this;
  48965. _this.interaxialDistance = interaxialDistance;
  48966. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48967. return _this;
  48968. }
  48969. AnaglyphUniversalCamera.prototype.getClassName = function () {
  48970. return "AnaglyphUniversalCamera";
  48971. };
  48972. return AnaglyphUniversalCamera;
  48973. }(BABYLON.UniversalCamera));
  48974. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  48975. var StereoscopicFreeCamera = (function (_super) {
  48976. __extends(StereoscopicFreeCamera, _super);
  48977. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48978. var _this = _super.call(this, name, position, scene) || this;
  48979. _this.interaxialDistance = interaxialDistance;
  48980. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48981. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48982. return _this;
  48983. }
  48984. StereoscopicFreeCamera.prototype.getClassName = function () {
  48985. return "StereoscopicFreeCamera";
  48986. };
  48987. return StereoscopicFreeCamera;
  48988. }(BABYLON.FreeCamera));
  48989. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  48990. var StereoscopicArcRotateCamera = (function (_super) {
  48991. __extends(StereoscopicArcRotateCamera, _super);
  48992. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  48993. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48994. _this.interaxialDistance = interaxialDistance;
  48995. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48996. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48997. return _this;
  48998. }
  48999. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  49000. return "StereoscopicArcRotateCamera";
  49001. };
  49002. return StereoscopicArcRotateCamera;
  49003. }(BABYLON.ArcRotateCamera));
  49004. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  49005. var StereoscopicGamepadCamera = (function (_super) {
  49006. __extends(StereoscopicGamepadCamera, _super);
  49007. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  49008. var _this = _super.call(this, name, position, scene) || this;
  49009. _this.interaxialDistance = interaxialDistance;
  49010. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  49011. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  49012. return _this;
  49013. }
  49014. StereoscopicGamepadCamera.prototype.getClassName = function () {
  49015. return "StereoscopicGamepadCamera";
  49016. };
  49017. return StereoscopicGamepadCamera;
  49018. }(BABYLON.GamepadCamera));
  49019. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  49020. var StereoscopicUniversalCamera = (function (_super) {
  49021. __extends(StereoscopicUniversalCamera, _super);
  49022. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  49023. var _this = _super.call(this, name, position, scene) || this;
  49024. _this.interaxialDistance = interaxialDistance;
  49025. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  49026. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  49027. return _this;
  49028. }
  49029. StereoscopicUniversalCamera.prototype.getClassName = function () {
  49030. return "StereoscopicUniversalCamera";
  49031. };
  49032. return StereoscopicUniversalCamera;
  49033. }(BABYLON.UniversalCamera));
  49034. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  49035. })(BABYLON || (BABYLON = {}));
  49036. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  49037. var BABYLON;
  49038. (function (BABYLON) {
  49039. var HolographicCamera = (function (_super) {
  49040. __extends(HolographicCamera, _super);
  49041. function HolographicCamera(name, scene) {
  49042. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  49043. scene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
  49044. _this._holographicViewMatrix = new BABYLON.Matrix();
  49045. _this._identityProjection = BABYLON.Matrix.Identity();
  49046. _this._scriptProjection = BABYLON.Matrix.Transpose(BABYLON.Matrix.PerspectiveFovLH(30, window.innerWidth / window.innerHeight, 1, 20));
  49047. _this._scriptViewProjection = BABYLON.Matrix.Identity();
  49048. _this.fov = 30;
  49049. _this.minZ = 1.0;
  49050. _this.maxZ = 20;
  49051. _this.mode = BABYLON.Camera.PERSPECTIVE_CAMERA;
  49052. _this.isIntermediate = false;
  49053. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  49054. _this.layerMask = 0x0FFFFFFF;
  49055. _this.fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED;
  49056. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_NONE;
  49057. var self = _this;
  49058. _this._onBeforeRenderObserver = scene.onBeforeRenderObservable.add(function (scene) {
  49059. self._holographicViewMatrix.m = window.getViewMatrix();
  49060. self.setViewMatrix(self._holographicViewMatrix);
  49061. var position = window.getCameraPositionVector();
  49062. self.position.copyFromFloats(-position[0], position[1], -position[2]);
  49063. });
  49064. _this._onBeforeCameraRenderObserver = scene.onBeforeCameraRenderObservable.add(function () {
  49065. if (scene.frustumPlanes) {
  49066. self.getFrustumPlanesToRef(scene.frustumPlanes);
  49067. }
  49068. });
  49069. scene.addCamera(_this);
  49070. if (!scene.activeCamera) {
  49071. scene.activeCamera = _this;
  49072. }
  49073. return _this;
  49074. }
  49075. HolographicCamera.prototype.getTypeName = function () {
  49076. return "HolographicCamera";
  49077. };
  49078. ;
  49079. HolographicCamera.prototype.getProjectionMatrix = function () {
  49080. return this._identityProjection;
  49081. };
  49082. ;
  49083. HolographicCamera.prototype.getViewMatrix = function () {
  49084. return this._holographicViewMatrix;
  49085. };
  49086. ;
  49087. HolographicCamera.prototype.setViewMatrix = function (view) {
  49088. this._holographicViewMatrix = view;
  49089. view.m[0] = -view.m[0];
  49090. view.m[1] = -view.m[1];
  49091. view.m[2] = -view.m[2];
  49092. view.m[3] = -view.m[3];
  49093. view.m[8] = -view.m[8];
  49094. view.m[9] = -view.m[9];
  49095. view.m[10] = -view.m[10];
  49096. view.m[11] = -view.m[11];
  49097. };
  49098. ;
  49099. HolographicCamera.prototype._initCache = function () { };
  49100. ;
  49101. HolographicCamera.prototype._updateCache = function () { };
  49102. ;
  49103. HolographicCamera.prototype._updateFromScene = function () { };
  49104. ;
  49105. // Synchronized
  49106. HolographicCamera.prototype._isSynchronizedViewMatrix = function () {
  49107. return true;
  49108. };
  49109. ;
  49110. HolographicCamera.prototype._isSynchronizedProjectionMatrix = function () {
  49111. return true;
  49112. };
  49113. ;
  49114. HolographicCamera.prototype.getFrustumPlanesToRef = function (result) {
  49115. this._holographicViewMatrix.multiplyToRef(this._scriptProjection, this._scriptViewProjection);
  49116. BABYLON.Frustum.GetPlanesToRef(this._scriptViewProjection, result);
  49117. return result;
  49118. };
  49119. ;
  49120. HolographicCamera.prototype.dispose = function () {
  49121. this.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  49122. this.getScene().onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  49123. _super.prototype.dispose.call(this);
  49124. };
  49125. return HolographicCamera;
  49126. }(BABYLON.Camera));
  49127. BABYLON.HolographicCamera = HolographicCamera;
  49128. })(BABYLON || (BABYLON = {}));
  49129. //# sourceMappingURL=babylon.holographicCamera.js.map
  49130. var BABYLON;
  49131. (function (BABYLON) {
  49132. var HDRRenderingPipeline = (function (_super) {
  49133. __extends(HDRRenderingPipeline, _super);
  49134. /**
  49135. * @constructor
  49136. * @param {string} name - The rendering pipeline name
  49137. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  49138. * @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)
  49139. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  49140. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  49141. */
  49142. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  49143. if (originalPostProcess === void 0) { originalPostProcess = null; }
  49144. var _this = _super.call(this, scene.getEngine(), name) || this;
  49145. /**
  49146. * Public members
  49147. */
  49148. // Gaussian Blur
  49149. /**
  49150. * Gaussian blur coefficient
  49151. * @type {number}
  49152. */
  49153. _this.gaussCoeff = 0.3;
  49154. /**
  49155. * Gaussian blur mean
  49156. * @type {number}
  49157. */
  49158. _this.gaussMean = 1.0;
  49159. /**
  49160. * Gaussian blur standard deviation
  49161. * @type {number}
  49162. */
  49163. _this.gaussStandDev = 0.8;
  49164. /**
  49165. * Gaussian blur multiplier. Multiplies the blur effect
  49166. * @type {number}
  49167. */
  49168. _this.gaussMultiplier = 4.0;
  49169. // HDR
  49170. /**
  49171. * Exposure, controls the overall intensity of the pipeline
  49172. * @type {number}
  49173. */
  49174. _this.exposure = 1.0;
  49175. /**
  49176. * Minimum luminance that the post-process can output. Luminance is >= 0
  49177. * @type {number}
  49178. */
  49179. _this.minimumLuminance = 1.0;
  49180. /**
  49181. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  49182. * @type {number}
  49183. */
  49184. _this.maximumLuminance = 1e20;
  49185. /**
  49186. * Increase rate for luminance: eye adaptation speed to dark
  49187. * @type {number}
  49188. */
  49189. _this.luminanceIncreaserate = 0.5;
  49190. /**
  49191. * Decrease rate for luminance: eye adaptation speed to bright
  49192. * @type {number}
  49193. */
  49194. _this.luminanceDecreaseRate = 0.5;
  49195. // Bright pass
  49196. /**
  49197. * Minimum luminance needed to compute HDR
  49198. * @type {number}
  49199. */
  49200. _this.brightThreshold = 0.8;
  49201. _this._needUpdate = true;
  49202. _this._scene = scene;
  49203. // Bright pass
  49204. _this._createBrightPassPostProcess(scene, ratio);
  49205. // Down sample X4
  49206. _this._createDownSampleX4PostProcess(scene, ratio);
  49207. // Create gaussian blur post-processes
  49208. _this._createGaussianBlurPostProcess(scene, ratio);
  49209. // Texture adder
  49210. _this._createTextureAdderPostProcess(scene, ratio);
  49211. // Luminance generator
  49212. _this._createLuminanceGeneratorPostProcess(scene);
  49213. // HDR
  49214. _this._createHDRPostProcess(scene, ratio);
  49215. // Pass postprocess
  49216. if (originalPostProcess === null) {
  49217. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  49218. }
  49219. else {
  49220. _this._originalPostProcess = originalPostProcess;
  49221. }
  49222. // Configure pipeline
  49223. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  49224. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  49225. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  49226. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  49227. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  49228. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  49229. var addDownSamplerPostProcess = function (id) {
  49230. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  49231. };
  49232. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  49233. addDownSamplerPostProcess(i);
  49234. }
  49235. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  49236. // Finish
  49237. scene.postProcessRenderPipelineManager.addPipeline(_this);
  49238. if (cameras !== null) {
  49239. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  49240. }
  49241. _this.update();
  49242. return _this;
  49243. }
  49244. /**
  49245. * Tells the pipeline to update its post-processes
  49246. */
  49247. HDRRenderingPipeline.prototype.update = function () {
  49248. this._needUpdate = true;
  49249. };
  49250. /**
  49251. * Returns the current calculated luminance
  49252. */
  49253. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  49254. return this._hdrCurrentLuminance;
  49255. };
  49256. /**
  49257. * Returns the currently drawn luminance
  49258. */
  49259. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  49260. return this._hdrOutputLuminance;
  49261. };
  49262. /**
  49263. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  49264. */
  49265. HDRRenderingPipeline.prototype.dispose = function () {
  49266. for (var i = 0; i < this._scene.cameras.length; i++) {
  49267. var camera = this._scene.cameras[i];
  49268. this._originalPostProcess.dispose(camera);
  49269. this._brightPassPostProcess.dispose(camera);
  49270. this._downSampleX4PostProcess.dispose(camera);
  49271. this._guassianBlurHPostProcess.dispose(camera);
  49272. this._guassianBlurVPostProcess.dispose(camera);
  49273. this._textureAdderPostProcess.dispose(camera);
  49274. for (var j = HDRRenderingPipeline.LUM_STEPS - 1; j >= 0; j--) {
  49275. this._downSamplePostProcesses[j].dispose(camera);
  49276. }
  49277. this._hdrPostProcess.dispose(camera);
  49278. }
  49279. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  49280. _super.prototype.dispose.call(this);
  49281. };
  49282. /**
  49283. * Creates the HDR post-process and computes the luminance adaptation
  49284. */
  49285. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  49286. var _this = this;
  49287. var hdrLastLuminance = 0.0;
  49288. this._hdrOutputLuminance = -1.0;
  49289. this._hdrCurrentLuminance = 1.0;
  49290. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  49291. this._hdrPostProcess.onApply = function (effect) {
  49292. if (_this._hdrOutputLuminance < 0.0) {
  49293. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  49294. }
  49295. else {
  49296. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  49297. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  49298. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  49299. }
  49300. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  49301. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  49302. }
  49303. else {
  49304. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  49305. }
  49306. }
  49307. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  49308. hdrLastLuminance += scene.getEngine().getDeltaTime();
  49309. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  49310. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  49311. effect.setFloat("exposure", _this.exposure);
  49312. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  49313. _this._needUpdate = false;
  49314. };
  49315. };
  49316. /**
  49317. * Texture Adder post-process
  49318. */
  49319. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  49320. var _this = this;
  49321. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  49322. this._textureAdderPostProcess.onApply = function (effect) {
  49323. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  49324. };
  49325. };
  49326. /**
  49327. * Down sample X4 post-process
  49328. */
  49329. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  49330. var _this = this;
  49331. var downSampleX4Offsets = new Array(32);
  49332. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  49333. this._downSampleX4PostProcess.onApply = function (effect) {
  49334. if (_this._needUpdate) {
  49335. var id = 0;
  49336. for (var i = -2; i < 2; i++) {
  49337. for (var j = -2; j < 2; j++) {
  49338. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  49339. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  49340. id += 2;
  49341. }
  49342. }
  49343. }
  49344. effect.setArray2("dsOffsets", downSampleX4Offsets);
  49345. };
  49346. };
  49347. /**
  49348. * Bright pass post-process
  49349. */
  49350. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  49351. var _this = this;
  49352. var brightOffsets = new Array(8);
  49353. var brightPassCallback = function (effect) {
  49354. if (_this._needUpdate) {
  49355. var sU = (1.0 / _this._brightPassPostProcess.width);
  49356. var sV = (1.0 / _this._brightPassPostProcess.height);
  49357. brightOffsets[0] = -0.5 * sU;
  49358. brightOffsets[1] = 0.5 * sV;
  49359. brightOffsets[2] = 0.5 * sU;
  49360. brightOffsets[3] = 0.5 * sV;
  49361. brightOffsets[4] = -0.5 * sU;
  49362. brightOffsets[5] = -0.5 * sV;
  49363. brightOffsets[6] = 0.5 * sU;
  49364. brightOffsets[7] = -0.5 * sV;
  49365. }
  49366. effect.setArray2("dsOffsets", brightOffsets);
  49367. effect.setFloat("brightThreshold", _this.brightThreshold);
  49368. };
  49369. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  49370. this._brightPassPostProcess.onApply = brightPassCallback;
  49371. };
  49372. /**
  49373. * Luminance generator. Creates the luminance post-process and down sample post-processes
  49374. */
  49375. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  49376. var _this = this;
  49377. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  49378. var luminanceOffsets = new Array(8);
  49379. var downSampleOffsets = new Array(18);
  49380. var halfDestPixelSize;
  49381. this._downSamplePostProcesses = new Array(lumSteps);
  49382. // Utils for luminance
  49383. var luminanceUpdateSourceOffsets = function (width, height) {
  49384. var sU = (1.0 / width);
  49385. var sV = (1.0 / height);
  49386. luminanceOffsets[0] = -0.5 * sU;
  49387. luminanceOffsets[1] = 0.5 * sV;
  49388. luminanceOffsets[2] = 0.5 * sU;
  49389. luminanceOffsets[3] = 0.5 * sV;
  49390. luminanceOffsets[4] = -0.5 * sU;
  49391. luminanceOffsets[5] = -0.5 * sV;
  49392. luminanceOffsets[6] = 0.5 * sU;
  49393. luminanceOffsets[7] = -0.5 * sV;
  49394. };
  49395. var luminanceUpdateDestOffsets = function (width, height) {
  49396. var id = 0;
  49397. for (var x = -1; x < 2; x++) {
  49398. for (var y = -1; y < 2; y++) {
  49399. downSampleOffsets[id] = (x) / width;
  49400. downSampleOffsets[id + 1] = (y) / height;
  49401. id += 2;
  49402. }
  49403. }
  49404. };
  49405. // Luminance callback
  49406. var luminanceCallback = function (effect) {
  49407. if (_this._needUpdate) {
  49408. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  49409. }
  49410. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  49411. effect.setArray2("lumOffsets", luminanceOffsets);
  49412. };
  49413. // Down sample callbacks
  49414. var downSampleCallback = function (indice) {
  49415. var i = indice;
  49416. return function (effect) {
  49417. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  49418. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  49419. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  49420. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  49421. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  49422. effect.setArray2("dsOffsets", downSampleOffsets);
  49423. };
  49424. };
  49425. var downSampleAfterRenderCallback = function (effect) {
  49426. // Unpack result
  49427. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  49428. 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);
  49429. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  49430. };
  49431. // Create luminance post-process
  49432. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  49433. 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);
  49434. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  49435. // Create down sample post-processes
  49436. for (var i = lumSteps - 2; i >= 0; i--) {
  49437. var length = Math.pow(3, i);
  49438. ratio = { width: length, height: length };
  49439. var defines = "#define DOWN_SAMPLE\n";
  49440. if (i === 0) {
  49441. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  49442. }
  49443. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  49444. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  49445. if (i === 0) {
  49446. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  49447. }
  49448. }
  49449. };
  49450. /**
  49451. * Gaussian blur post-processes. Horizontal and Vertical
  49452. */
  49453. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  49454. var _this = this;
  49455. var blurOffsetsW = new Array(9);
  49456. var blurOffsetsH = new Array(9);
  49457. var blurWeights = new Array(9);
  49458. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  49459. // Utils for gaussian blur
  49460. var calculateBlurOffsets = function (height) {
  49461. var lastOutputDimensions = {
  49462. width: scene.getEngine().getRenderWidth(),
  49463. height: scene.getEngine().getRenderHeight()
  49464. };
  49465. for (var i = 0; i < 9; i++) {
  49466. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  49467. if (height) {
  49468. blurOffsetsH[i] = value;
  49469. }
  49470. else {
  49471. blurOffsetsW[i] = value;
  49472. }
  49473. }
  49474. };
  49475. var calculateWeights = function () {
  49476. var x = 0.0;
  49477. for (var i = 0; i < 9; i++) {
  49478. x = (i - 4.0) / 4.0;
  49479. 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));
  49480. }
  49481. };
  49482. // Callback
  49483. var gaussianBlurCallback = function (height) {
  49484. return function (effect) {
  49485. if (_this._needUpdate) {
  49486. calculateWeights();
  49487. calculateBlurOffsets(height);
  49488. }
  49489. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  49490. effect.setArray("blurWeights", blurWeights);
  49491. effect.setFloat("multiplier", _this.gaussMultiplier);
  49492. };
  49493. };
  49494. // Create horizontal gaussian blur post-processes
  49495. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  49496. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  49497. // Create vertical gaussian blur post-process
  49498. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  49499. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  49500. };
  49501. return HDRRenderingPipeline;
  49502. }(BABYLON.PostProcessRenderPipeline));
  49503. // Luminance generator
  49504. HDRRenderingPipeline.LUM_STEPS = 6;
  49505. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  49506. })(BABYLON || (BABYLON = {}));
  49507. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  49508. var BABYLON;
  49509. (function (BABYLON) {
  49510. var FaceAdjacencies = (function () {
  49511. function FaceAdjacencies() {
  49512. this.edges = new Array();
  49513. this.edgesConnectedCount = 0;
  49514. }
  49515. return FaceAdjacencies;
  49516. }());
  49517. var EdgesRenderer = (function () {
  49518. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  49519. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  49520. if (epsilon === void 0) { epsilon = 0.95; }
  49521. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  49522. this.edgesWidthScalerForOrthographic = 1000.0;
  49523. this.edgesWidthScalerForPerspective = 50.0;
  49524. this._linesPositions = new Array();
  49525. this._linesNormals = new Array();
  49526. this._linesIndices = new Array();
  49527. this._buffers = {};
  49528. this._checkVerticesInsteadOfIndices = false;
  49529. this._source = source;
  49530. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  49531. this._epsilon = epsilon;
  49532. this._prepareRessources();
  49533. this._generateEdgesLines();
  49534. }
  49535. EdgesRenderer.prototype._prepareRessources = function () {
  49536. if (this._lineShader) {
  49537. return;
  49538. }
  49539. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  49540. attributes: ["position", "normal"],
  49541. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  49542. });
  49543. this._lineShader.disableDepthWrite = true;
  49544. this._lineShader.backFaceCulling = false;
  49545. };
  49546. EdgesRenderer.prototype.dispose = function () {
  49547. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  49548. if (buffer) {
  49549. buffer.dispose();
  49550. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  49551. }
  49552. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  49553. if (buffer) {
  49554. buffer.dispose();
  49555. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  49556. }
  49557. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  49558. this._lineShader.dispose();
  49559. };
  49560. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  49561. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  49562. return 0;
  49563. }
  49564. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  49565. return 1;
  49566. }
  49567. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  49568. return 2;
  49569. }
  49570. return -1;
  49571. };
  49572. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  49573. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  49574. return 0;
  49575. }
  49576. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  49577. return 1;
  49578. }
  49579. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  49580. return 2;
  49581. }
  49582. return -1;
  49583. };
  49584. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  49585. var needToCreateLine;
  49586. if (edge === undefined) {
  49587. needToCreateLine = true;
  49588. }
  49589. else {
  49590. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  49591. needToCreateLine = dotProduct < this._epsilon;
  49592. }
  49593. if (needToCreateLine) {
  49594. var offset = this._linesPositions.length / 3;
  49595. var normal = p0.subtract(p1);
  49596. normal.normalize();
  49597. // Positions
  49598. this._linesPositions.push(p0.x);
  49599. this._linesPositions.push(p0.y);
  49600. this._linesPositions.push(p0.z);
  49601. this._linesPositions.push(p0.x);
  49602. this._linesPositions.push(p0.y);
  49603. this._linesPositions.push(p0.z);
  49604. this._linesPositions.push(p1.x);
  49605. this._linesPositions.push(p1.y);
  49606. this._linesPositions.push(p1.z);
  49607. this._linesPositions.push(p1.x);
  49608. this._linesPositions.push(p1.y);
  49609. this._linesPositions.push(p1.z);
  49610. // Normals
  49611. this._linesNormals.push(p1.x);
  49612. this._linesNormals.push(p1.y);
  49613. this._linesNormals.push(p1.z);
  49614. this._linesNormals.push(-1);
  49615. this._linesNormals.push(p1.x);
  49616. this._linesNormals.push(p1.y);
  49617. this._linesNormals.push(p1.z);
  49618. this._linesNormals.push(1);
  49619. this._linesNormals.push(p0.x);
  49620. this._linesNormals.push(p0.y);
  49621. this._linesNormals.push(p0.z);
  49622. this._linesNormals.push(-1);
  49623. this._linesNormals.push(p0.x);
  49624. this._linesNormals.push(p0.y);
  49625. this._linesNormals.push(p0.z);
  49626. this._linesNormals.push(1);
  49627. // Indices
  49628. this._linesIndices.push(offset);
  49629. this._linesIndices.push(offset + 1);
  49630. this._linesIndices.push(offset + 2);
  49631. this._linesIndices.push(offset);
  49632. this._linesIndices.push(offset + 2);
  49633. this._linesIndices.push(offset + 3);
  49634. }
  49635. };
  49636. EdgesRenderer.prototype._generateEdgesLines = function () {
  49637. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49638. var indices = this._source.getIndices();
  49639. // First let's find adjacencies
  49640. var adjacencies = new Array();
  49641. var faceNormals = new Array();
  49642. var index;
  49643. var faceAdjacencies;
  49644. // Prepare faces
  49645. for (index = 0; index < indices.length; index += 3) {
  49646. faceAdjacencies = new FaceAdjacencies();
  49647. var p0Index = indices[index];
  49648. var p1Index = indices[index + 1];
  49649. var p2Index = indices[index + 2];
  49650. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  49651. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  49652. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  49653. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  49654. faceNormal.normalize();
  49655. faceNormals.push(faceNormal);
  49656. adjacencies.push(faceAdjacencies);
  49657. }
  49658. // Scan
  49659. for (index = 0; index < adjacencies.length; index++) {
  49660. faceAdjacencies = adjacencies[index];
  49661. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  49662. var otherFaceAdjacencies = adjacencies[otherIndex];
  49663. if (faceAdjacencies.edgesConnectedCount === 3) {
  49664. break;
  49665. }
  49666. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  49667. continue;
  49668. }
  49669. var otherP0 = indices[otherIndex * 3];
  49670. var otherP1 = indices[otherIndex * 3 + 1];
  49671. var otherP2 = indices[otherIndex * 3 + 2];
  49672. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  49673. var otherEdgeIndex;
  49674. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  49675. continue;
  49676. }
  49677. switch (edgeIndex) {
  49678. case 0:
  49679. if (this._checkVerticesInsteadOfIndices) {
  49680. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49681. }
  49682. else {
  49683. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  49684. }
  49685. break;
  49686. case 1:
  49687. if (this._checkVerticesInsteadOfIndices) {
  49688. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49689. }
  49690. else {
  49691. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  49692. }
  49693. break;
  49694. case 2:
  49695. if (this._checkVerticesInsteadOfIndices) {
  49696. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  49697. }
  49698. else {
  49699. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  49700. }
  49701. break;
  49702. }
  49703. if (otherEdgeIndex === -1) {
  49704. continue;
  49705. }
  49706. faceAdjacencies.edges[edgeIndex] = otherIndex;
  49707. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  49708. faceAdjacencies.edgesConnectedCount++;
  49709. otherFaceAdjacencies.edgesConnectedCount++;
  49710. if (faceAdjacencies.edgesConnectedCount === 3) {
  49711. break;
  49712. }
  49713. }
  49714. }
  49715. }
  49716. // Create lines
  49717. for (index = 0; index < adjacencies.length; index++) {
  49718. // 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
  49719. var current = adjacencies[index];
  49720. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  49721. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  49722. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  49723. }
  49724. // Merge into a single mesh
  49725. var engine = this._source.getScene().getEngine();
  49726. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  49727. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  49728. this._ib = engine.createIndexBuffer(this._linesIndices);
  49729. this._indicesCount = this._linesIndices.length;
  49730. };
  49731. EdgesRenderer.prototype.render = function () {
  49732. if (!this._lineShader.isReady()) {
  49733. return;
  49734. }
  49735. var scene = this._source.getScene();
  49736. var engine = scene.getEngine();
  49737. this._lineShader._preBind();
  49738. // VBOs
  49739. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  49740. scene.resetCachedMaterial();
  49741. this._lineShader.setColor4("color", this._source.edgesColor);
  49742. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  49743. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  49744. }
  49745. else {
  49746. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  49747. }
  49748. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  49749. this._lineShader.bind(this._source.getWorldMatrix());
  49750. // Draw order
  49751. engine.draw(true, 0, this._indicesCount);
  49752. this._lineShader.unbind();
  49753. engine.setDepthWrite(true);
  49754. };
  49755. return EdgesRenderer;
  49756. }());
  49757. BABYLON.EdgesRenderer = EdgesRenderer;
  49758. })(BABYLON || (BABYLON = {}));
  49759. //# sourceMappingURL=babylon.edgesRenderer.js.map
  49760. var BABYLON;
  49761. (function (BABYLON) {
  49762. var TonemappingOperator;
  49763. (function (TonemappingOperator) {
  49764. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  49765. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  49766. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  49767. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  49768. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  49769. ;
  49770. var TonemapPostProcess = (function (_super) {
  49771. __extends(TonemapPostProcess, _super);
  49772. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  49773. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  49774. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  49775. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  49776. _this._operator = _operator;
  49777. _this.exposureAdjustment = exposureAdjustment;
  49778. var defines = "#define ";
  49779. if (_this._operator === TonemappingOperator.Hable)
  49780. defines += "HABLE_TONEMAPPING";
  49781. else if (_this._operator === TonemappingOperator.Reinhard)
  49782. defines += "REINHARD_TONEMAPPING";
  49783. else if (_this._operator === TonemappingOperator.HejiDawson)
  49784. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  49785. else if (_this._operator === TonemappingOperator.Photographic)
  49786. defines += "PHOTOGRAPHIC_TONEMAPPING";
  49787. //sadly a second call to create the effect.
  49788. _this.updateEffect(defines);
  49789. _this.onApply = function (effect) {
  49790. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  49791. };
  49792. return _this;
  49793. }
  49794. return TonemapPostProcess;
  49795. }(BABYLON.PostProcess));
  49796. BABYLON.TonemapPostProcess = TonemapPostProcess;
  49797. })(BABYLON || (BABYLON = {}));
  49798. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  49799. var BABYLON;
  49800. (function (BABYLON) {
  49801. var ReflectionProbe = (function () {
  49802. function ReflectionProbe(name, size, scene, generateMipMaps) {
  49803. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49804. var _this = this;
  49805. this.name = name;
  49806. this._viewMatrix = BABYLON.Matrix.Identity();
  49807. this._target = BABYLON.Vector3.Zero();
  49808. this._add = BABYLON.Vector3.Zero();
  49809. this.invertYAxis = false;
  49810. this.position = BABYLON.Vector3.Zero();
  49811. this._scene = scene;
  49812. this._scene.reflectionProbes.push(this);
  49813. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  49814. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  49815. switch (faceIndex) {
  49816. case 0:
  49817. _this._add.copyFromFloats(1, 0, 0);
  49818. break;
  49819. case 1:
  49820. _this._add.copyFromFloats(-1, 0, 0);
  49821. break;
  49822. case 2:
  49823. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  49824. break;
  49825. case 3:
  49826. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  49827. break;
  49828. case 4:
  49829. _this._add.copyFromFloats(0, 0, 1);
  49830. break;
  49831. case 5:
  49832. _this._add.copyFromFloats(0, 0, -1);
  49833. break;
  49834. }
  49835. if (_this._attachedMesh) {
  49836. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  49837. }
  49838. _this.position.addToRef(_this._add, _this._target);
  49839. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  49840. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  49841. });
  49842. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  49843. scene.updateTransformMatrix(true);
  49844. });
  49845. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  49846. }
  49847. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  49848. get: function () {
  49849. return this._renderTargetTexture.refreshRate;
  49850. },
  49851. set: function (value) {
  49852. this._renderTargetTexture.refreshRate = value;
  49853. },
  49854. enumerable: true,
  49855. configurable: true
  49856. });
  49857. ReflectionProbe.prototype.getScene = function () {
  49858. return this._scene;
  49859. };
  49860. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  49861. get: function () {
  49862. return this._renderTargetTexture;
  49863. },
  49864. enumerable: true,
  49865. configurable: true
  49866. });
  49867. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  49868. get: function () {
  49869. return this._renderTargetTexture.renderList;
  49870. },
  49871. enumerable: true,
  49872. configurable: true
  49873. });
  49874. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  49875. this._attachedMesh = mesh;
  49876. };
  49877. ReflectionProbe.prototype.dispose = function () {
  49878. var index = this._scene.reflectionProbes.indexOf(this);
  49879. if (index !== -1) {
  49880. // Remove from the scene if found
  49881. this._scene.reflectionProbes.splice(index, 1);
  49882. }
  49883. if (this._renderTargetTexture) {
  49884. this._renderTargetTexture.dispose();
  49885. this._renderTargetTexture = null;
  49886. }
  49887. };
  49888. return ReflectionProbe;
  49889. }());
  49890. BABYLON.ReflectionProbe = ReflectionProbe;
  49891. })(BABYLON || (BABYLON = {}));
  49892. //# sourceMappingURL=babylon.reflectionProbe.js.map
  49893. var BABYLON;
  49894. (function (BABYLON) {
  49895. var SolidParticle = (function () {
  49896. /**
  49897. * Creates a Solid Particle object.
  49898. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49899. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49900. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49901. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  49902. * `shapeId` (integer) is the model shape identifier in the SPS.
  49903. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49904. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  49905. */
  49906. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49907. this.idx = 0; // particle global index
  49908. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  49909. this.position = BABYLON.Vector3.Zero(); // position
  49910. this.rotation = BABYLON.Vector3.Zero(); // rotation
  49911. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  49912. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  49913. this.velocity = BABYLON.Vector3.Zero(); // velocity
  49914. this.alive = true; // alive
  49915. this.isVisible = true; // visibility
  49916. this._pos = 0; // index of this particle in the global "positions" array
  49917. this.shapeId = 0; // model shape id
  49918. this.idxInShape = 0; // index of the particle in its shape id
  49919. this.idx = particleIndex;
  49920. this._pos = positionIndex;
  49921. this._model = model;
  49922. this.shapeId = shapeId;
  49923. this.idxInShape = idxInShape;
  49924. this._sps = sps;
  49925. if (modelBoundingInfo) {
  49926. this._modelBoundingInfo = modelBoundingInfo;
  49927. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49928. }
  49929. }
  49930. Object.defineProperty(SolidParticle.prototype, "scale", {
  49931. /**
  49932. * legacy support, changed scale to scaling
  49933. */
  49934. get: function () {
  49935. return this.scaling;
  49936. },
  49937. set: function (scale) {
  49938. this.scaling = scale;
  49939. },
  49940. enumerable: true,
  49941. configurable: true
  49942. });
  49943. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49944. /**
  49945. * legacy support, changed quaternion to rotationQuaternion
  49946. */
  49947. get: function () {
  49948. return this.rotationQuaternion;
  49949. },
  49950. set: function (q) {
  49951. this.rotationQuaternion = q;
  49952. },
  49953. enumerable: true,
  49954. configurable: true
  49955. });
  49956. /**
  49957. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49958. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49959. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  49960. */
  49961. SolidParticle.prototype.intersectsMesh = function (target) {
  49962. if (!this._boundingInfo || !target._boundingInfo) {
  49963. return false;
  49964. }
  49965. if (this._sps._bSphereOnly) {
  49966. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49967. }
  49968. return this._boundingInfo.intersects(target._boundingInfo, false);
  49969. };
  49970. return SolidParticle;
  49971. }());
  49972. BABYLON.SolidParticle = SolidParticle;
  49973. var ModelShape = (function () {
  49974. /**
  49975. * 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.
  49976. * SPS internal tool, don't use it manually.
  49977. */
  49978. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  49979. this.shapeID = id;
  49980. this._shape = shape;
  49981. this._shapeUV = shapeUV;
  49982. this._positionFunction = posFunction;
  49983. this._vertexFunction = vtxFunction;
  49984. }
  49985. return ModelShape;
  49986. }());
  49987. BABYLON.ModelShape = ModelShape;
  49988. })(BABYLON || (BABYLON = {}));
  49989. //# sourceMappingURL=babylon.solidParticle.js.map
  49990. var BABYLON;
  49991. (function (BABYLON) {
  49992. /**
  49993. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49994. */
  49995. var SolidParticleSystem = (function () {
  49996. /**
  49997. * Creates a SPS (Solid Particle System) object.
  49998. * `name` (String) is the SPS name, this will be the underlying mesh name.
  49999. * `scene` (Scene) is the scene in which the SPS is added.
  50000. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  50001. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  50002. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  50003. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  50004. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  50005. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  50006. */
  50007. function SolidParticleSystem(name, scene, options) {
  50008. // public members
  50009. /**
  50010. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  50011. * Example : var p = SPS.particles[i];
  50012. */
  50013. this.particles = new Array();
  50014. /**
  50015. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  50016. */
  50017. this.nbParticles = 0;
  50018. /**
  50019. * If the particles must ever face the camera (default false). Useful for planar particles.
  50020. */
  50021. this.billboard = false;
  50022. /**
  50023. * Recompute normals when adding a shape
  50024. */
  50025. this.recomputeNormals = true;
  50026. /**
  50027. * This a counter ofr your own usage. It's not set by any SPS functions.
  50028. */
  50029. this.counter = 0;
  50030. /**
  50031. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  50032. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  50033. */
  50034. this.vars = {};
  50035. this._positions = new Array();
  50036. this._indices = new Array();
  50037. this._normals = new Array();
  50038. this._colors = new Array();
  50039. this._uvs = new Array();
  50040. this._index = 0; // indices index
  50041. this._updatable = true;
  50042. this._pickable = false;
  50043. this._isVisibilityBoxLocked = false;
  50044. this._alwaysVisible = false;
  50045. this._shapeCounter = 0;
  50046. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  50047. this._color = new BABYLON.Color4(0, 0, 0, 0);
  50048. this._computeParticleColor = true;
  50049. this._computeParticleTexture = true;
  50050. this._computeParticleRotation = true;
  50051. this._computeParticleVertex = false;
  50052. this._computeBoundingBox = false;
  50053. this._cam_axisZ = BABYLON.Vector3.Zero();
  50054. this._cam_axisY = BABYLON.Vector3.Zero();
  50055. this._cam_axisX = BABYLON.Vector3.Zero();
  50056. this._axisX = BABYLON.Axis.X;
  50057. this._axisY = BABYLON.Axis.Y;
  50058. this._axisZ = BABYLON.Axis.Z;
  50059. this._camDir = BABYLON.Vector3.Zero();
  50060. this._rotMatrix = new BABYLON.Matrix();
  50061. this._invertMatrix = new BABYLON.Matrix();
  50062. this._rotated = BABYLON.Vector3.Zero();
  50063. this._quaternion = new BABYLON.Quaternion();
  50064. this._vertex = BABYLON.Vector3.Zero();
  50065. this._normal = BABYLON.Vector3.Zero();
  50066. this._yaw = 0.0;
  50067. this._pitch = 0.0;
  50068. this._roll = 0.0;
  50069. this._halfroll = 0.0;
  50070. this._halfpitch = 0.0;
  50071. this._halfyaw = 0.0;
  50072. this._sinRoll = 0.0;
  50073. this._cosRoll = 0.0;
  50074. this._sinPitch = 0.0;
  50075. this._cosPitch = 0.0;
  50076. this._sinYaw = 0.0;
  50077. this._cosYaw = 0.0;
  50078. this._w = 0.0;
  50079. this._minimum = BABYLON.Tmp.Vector3[0];
  50080. this._maximum = BABYLON.Tmp.Vector3[1];
  50081. this._scale = BABYLON.Tmp.Vector3[2];
  50082. this._translation = BABYLON.Tmp.Vector3[3];
  50083. this._minBbox = BABYLON.Tmp.Vector3[4];
  50084. this._maxBbox = BABYLON.Tmp.Vector3[5];
  50085. this._particlesIntersect = false;
  50086. this._bSphereOnly = false;
  50087. this._bSphereRadiusFactor = 1.0;
  50088. this.name = name;
  50089. this._scene = scene;
  50090. this._camera = scene.activeCamera;
  50091. this._pickable = options ? options.isPickable : false;
  50092. this._particlesIntersect = options ? options.particleIntersection : false;
  50093. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  50094. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  50095. if (options && options.updatable) {
  50096. this._updatable = options.updatable;
  50097. }
  50098. else {
  50099. this._updatable = true;
  50100. }
  50101. if (this._pickable) {
  50102. this.pickedParticles = [];
  50103. }
  50104. }
  50105. /**
  50106. * Builds the SPS underlying mesh. Returns a standard Mesh.
  50107. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  50108. */
  50109. SolidParticleSystem.prototype.buildMesh = function () {
  50110. if (this.nbParticles === 0) {
  50111. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  50112. this.addShape(triangle, 1);
  50113. triangle.dispose();
  50114. }
  50115. this._positions32 = new Float32Array(this._positions);
  50116. this._uvs32 = new Float32Array(this._uvs);
  50117. this._colors32 = new Float32Array(this._colors);
  50118. if (this.recomputeNormals) {
  50119. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  50120. }
  50121. this._normals32 = new Float32Array(this._normals);
  50122. this._fixedNormal32 = new Float32Array(this._normals);
  50123. var vertexData = new BABYLON.VertexData();
  50124. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  50125. vertexData.indices = this._indices;
  50126. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  50127. if (this._uvs32) {
  50128. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  50129. ;
  50130. }
  50131. if (this._colors32) {
  50132. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  50133. }
  50134. var mesh = new BABYLON.Mesh(this.name, this._scene);
  50135. vertexData.applyToMesh(mesh, this._updatable);
  50136. this.mesh = mesh;
  50137. this.mesh.isPickable = this._pickable;
  50138. // free memory
  50139. this._positions = null;
  50140. this._normals = null;
  50141. this._uvs = null;
  50142. this._colors = null;
  50143. if (!this._updatable) {
  50144. this.particles.length = 0;
  50145. }
  50146. return mesh;
  50147. };
  50148. /**
  50149. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  50150. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  50151. * Thus the particles generated from `digest()` have their property `position` set yet.
  50152. * `mesh` ( Mesh ) is the mesh to be digested
  50153. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  50154. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  50155. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  50156. */
  50157. SolidParticleSystem.prototype.digest = function (mesh, options) {
  50158. var size = (options && options.facetNb) || 1;
  50159. var number = (options && options.number);
  50160. var delta = (options && options.delta) || 0;
  50161. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50162. var meshInd = mesh.getIndices();
  50163. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50164. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50165. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50166. var f = 0; // facet counter
  50167. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  50168. // compute size from number
  50169. if (number) {
  50170. number = (number > totalFacets) ? totalFacets : number;
  50171. size = Math.round(totalFacets / number);
  50172. delta = 0;
  50173. }
  50174. else {
  50175. size = (size > totalFacets) ? totalFacets : size;
  50176. }
  50177. var facetPos = []; // submesh positions
  50178. var facetInd = []; // submesh indices
  50179. var facetUV = []; // submesh UV
  50180. var facetCol = []; // submesh colors
  50181. var barycenter = BABYLON.Tmp.Vector3[0];
  50182. var rand;
  50183. var sizeO = size;
  50184. while (f < totalFacets) {
  50185. size = sizeO + Math.floor((1 + delta) * Math.random());
  50186. if (f > totalFacets - size) {
  50187. size = totalFacets - f;
  50188. }
  50189. // reset temp arrays
  50190. facetPos.length = 0;
  50191. facetInd.length = 0;
  50192. facetUV.length = 0;
  50193. facetCol.length = 0;
  50194. // iterate over "size" facets
  50195. var fi = 0;
  50196. for (var j = f * 3; j < (f + size) * 3; j++) {
  50197. facetInd.push(fi);
  50198. var i = meshInd[j];
  50199. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  50200. if (meshUV) {
  50201. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  50202. }
  50203. if (meshCol) {
  50204. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  50205. }
  50206. fi++;
  50207. }
  50208. // create a model shape for each single particle
  50209. var idx = this.nbParticles;
  50210. var shape = this._posToShape(facetPos);
  50211. var shapeUV = this._uvsToShapeUV(facetUV);
  50212. // compute the barycenter of the shape
  50213. var v;
  50214. for (v = 0; v < shape.length; v++) {
  50215. barycenter.addInPlace(shape[v]);
  50216. }
  50217. barycenter.scaleInPlace(1 / shape.length);
  50218. // shift the shape from its barycenter to the origin
  50219. for (v = 0; v < shape.length; v++) {
  50220. shape[v].subtractInPlace(barycenter);
  50221. }
  50222. var bInfo;
  50223. if (this._particlesIntersect) {
  50224. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  50225. }
  50226. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  50227. // add the particle in the SPS
  50228. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  50229. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  50230. // initialize the particle position
  50231. this.particles[this.nbParticles].position.addInPlace(barycenter);
  50232. this._index += shape.length;
  50233. idx++;
  50234. this.nbParticles++;
  50235. this._shapeCounter++;
  50236. f += size;
  50237. }
  50238. return this;
  50239. };
  50240. //reset copy
  50241. SolidParticleSystem.prototype._resetCopy = function () {
  50242. this._copy.position.x = 0;
  50243. this._copy.position.y = 0;
  50244. this._copy.position.z = 0;
  50245. this._copy.rotation.x = 0;
  50246. this._copy.rotation.y = 0;
  50247. this._copy.rotation.z = 0;
  50248. this._copy.rotationQuaternion = null;
  50249. this._copy.scaling.x = 1;
  50250. this._copy.scaling.y = 1;
  50251. this._copy.scaling.z = 1;
  50252. this._copy.uvs.x = 0;
  50253. this._copy.uvs.y = 0;
  50254. this._copy.uvs.z = 1;
  50255. this._copy.uvs.w = 1;
  50256. this._copy.color = null;
  50257. };
  50258. // _meshBuilder : inserts the shape model in the global SPS mesh
  50259. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  50260. var i;
  50261. var u = 0;
  50262. var c = 0;
  50263. var n = 0;
  50264. this._resetCopy();
  50265. if (options && options.positionFunction) {
  50266. options.positionFunction(this._copy, idx, idxInShape);
  50267. }
  50268. if (this._copy.rotationQuaternion) {
  50269. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50270. }
  50271. else {
  50272. this._yaw = this._copy.rotation.y;
  50273. this._pitch = this._copy.rotation.x;
  50274. this._roll = this._copy.rotation.z;
  50275. this._quaternionRotationYPR();
  50276. }
  50277. this._quaternionToRotationMatrix();
  50278. for (i = 0; i < shape.length; i++) {
  50279. this._vertex.x = shape[i].x;
  50280. this._vertex.y = shape[i].y;
  50281. this._vertex.z = shape[i].z;
  50282. if (options && options.vertexFunction) {
  50283. options.vertexFunction(this._copy, this._vertex, i);
  50284. }
  50285. this._vertex.x *= this._copy.scaling.x;
  50286. this._vertex.y *= this._copy.scaling.y;
  50287. this._vertex.z *= this._copy.scaling.z;
  50288. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50289. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  50290. if (meshUV) {
  50291. 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);
  50292. u += 2;
  50293. }
  50294. if (this._copy.color) {
  50295. this._color = this._copy.color;
  50296. }
  50297. else if (meshCol && meshCol[c] !== undefined) {
  50298. this._color.r = meshCol[c];
  50299. this._color.g = meshCol[c + 1];
  50300. this._color.b = meshCol[c + 2];
  50301. this._color.a = meshCol[c + 3];
  50302. }
  50303. else {
  50304. this._color.r = 1;
  50305. this._color.g = 1;
  50306. this._color.b = 1;
  50307. this._color.a = 1;
  50308. }
  50309. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  50310. c += 4;
  50311. if (!this.recomputeNormals && meshNor) {
  50312. this._normal.x = meshNor[n];
  50313. this._normal.y = meshNor[n + 1];
  50314. this._normal.z = meshNor[n + 2];
  50315. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  50316. normals.push(this._normal.x, this._normal.y, this._normal.z);
  50317. n += 3;
  50318. }
  50319. }
  50320. for (i = 0; i < meshInd.length; i++) {
  50321. indices.push(p + meshInd[i]);
  50322. }
  50323. if (this._pickable) {
  50324. var nbfaces = meshInd.length / 3;
  50325. for (i = 0; i < nbfaces; i++) {
  50326. this.pickedParticles.push({ idx: idx, faceId: i });
  50327. }
  50328. }
  50329. };
  50330. // returns a shape array from positions array
  50331. SolidParticleSystem.prototype._posToShape = function (positions) {
  50332. var shape = [];
  50333. for (var i = 0; i < positions.length; i += 3) {
  50334. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  50335. }
  50336. return shape;
  50337. };
  50338. // returns a shapeUV array from a Vector4 uvs
  50339. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  50340. var shapeUV = [];
  50341. if (uvs) {
  50342. for (var i = 0; i < uvs.length; i++)
  50343. shapeUV.push(uvs[i]);
  50344. }
  50345. return shapeUV;
  50346. };
  50347. // adds a new particle object in the particles array
  50348. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  50349. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  50350. };
  50351. /**
  50352. * Adds some particles to the SPS from the model shape. Returns the shape id.
  50353. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  50354. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  50355. * `nb` (positive integer) the number of particles to be created from this model
  50356. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  50357. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  50358. */
  50359. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  50360. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  50361. var meshInd = mesh.getIndices();
  50362. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  50363. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  50364. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  50365. var bbInfo;
  50366. if (this._particlesIntersect) {
  50367. bbInfo = mesh.getBoundingInfo();
  50368. }
  50369. var shape = this._posToShape(meshPos);
  50370. var shapeUV = this._uvsToShapeUV(meshUV);
  50371. var posfunc = options ? options.positionFunction : null;
  50372. var vtxfunc = options ? options.vertexFunction : null;
  50373. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  50374. // particles
  50375. var idx = this.nbParticles;
  50376. for (var i = 0; i < nb; i++) {
  50377. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  50378. if (this._updatable) {
  50379. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  50380. }
  50381. this._index += shape.length;
  50382. idx++;
  50383. }
  50384. this.nbParticles += nb;
  50385. this._shapeCounter++;
  50386. return this._shapeCounter - 1;
  50387. };
  50388. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  50389. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  50390. this._resetCopy();
  50391. if (particle._model._positionFunction) {
  50392. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  50393. }
  50394. if (this._copy.rotationQuaternion) {
  50395. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  50396. }
  50397. else {
  50398. this._yaw = this._copy.rotation.y;
  50399. this._pitch = this._copy.rotation.x;
  50400. this._roll = this._copy.rotation.z;
  50401. this._quaternionRotationYPR();
  50402. }
  50403. this._quaternionToRotationMatrix();
  50404. this._shape = particle._model._shape;
  50405. for (var pt = 0; pt < this._shape.length; pt++) {
  50406. this._vertex.x = this._shape[pt].x;
  50407. this._vertex.y = this._shape[pt].y;
  50408. this._vertex.z = this._shape[pt].z;
  50409. if (particle._model._vertexFunction) {
  50410. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  50411. }
  50412. this._vertex.x *= this._copy.scaling.x;
  50413. this._vertex.y *= this._copy.scaling.y;
  50414. this._vertex.z *= this._copy.scaling.z;
  50415. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  50416. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  50417. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  50418. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  50419. }
  50420. particle.position.x = 0.0;
  50421. particle.position.y = 0.0;
  50422. particle.position.z = 0.0;
  50423. particle.rotation.x = 0.0;
  50424. particle.rotation.y = 0.0;
  50425. particle.rotation.z = 0.0;
  50426. particle.rotationQuaternion = null;
  50427. particle.scaling.x = 1.0;
  50428. particle.scaling.y = 1.0;
  50429. particle.scaling.z = 1.0;
  50430. };
  50431. /**
  50432. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  50433. */
  50434. SolidParticleSystem.prototype.rebuildMesh = function () {
  50435. for (var p = 0; p < this.particles.length; p++) {
  50436. this._rebuildParticle(this.particles[p]);
  50437. }
  50438. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50439. };
  50440. /**
  50441. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  50442. * This method calls `updateParticle()` for each particle of the SPS.
  50443. * For an animated SPS, it is usually called within the render loop.
  50444. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  50445. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  50446. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  50447. */
  50448. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  50449. if (start === void 0) { start = 0; }
  50450. if (end === void 0) { end = this.nbParticles - 1; }
  50451. if (update === void 0) { update = true; }
  50452. if (!this._updatable) {
  50453. return;
  50454. }
  50455. // custom beforeUpdate
  50456. this.beforeUpdateParticles(start, end, update);
  50457. this._cam_axisX.x = 1.0;
  50458. this._cam_axisX.y = 0.0;
  50459. this._cam_axisX.z = 0.0;
  50460. this._cam_axisY.x = 0.0;
  50461. this._cam_axisY.y = 1.0;
  50462. this._cam_axisY.z = 0.0;
  50463. this._cam_axisZ.x = 0.0;
  50464. this._cam_axisZ.y = 0.0;
  50465. this._cam_axisZ.z = 1.0;
  50466. // if the particles will always face the camera
  50467. if (this.billboard) {
  50468. // compute the camera position and un-rotate it by the current mesh rotation
  50469. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  50470. this._quaternionToRotationMatrix();
  50471. this._rotMatrix.invertToRef(this._invertMatrix);
  50472. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  50473. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  50474. this._cam_axisZ.normalize();
  50475. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  50476. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  50477. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  50478. this._cam_axisY.normalize();
  50479. this._cam_axisX.normalize();
  50480. }
  50481. }
  50482. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  50483. var idx = 0; // current position index in the global array positions32
  50484. var index = 0; // position start index in the global array positions32 of the current particle
  50485. var colidx = 0; // current color index in the global array colors32
  50486. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  50487. var uvidx = 0; // current uv index in the global array uvs32
  50488. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  50489. var pt = 0; // current index in the particle model shape
  50490. if (this.mesh.isFacetDataEnabled) {
  50491. this._computeBoundingBox = true;
  50492. }
  50493. if (this._computeBoundingBox) {
  50494. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  50495. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  50496. }
  50497. // particle loop
  50498. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  50499. for (var p = start; p <= end; p++) {
  50500. this._particle = this.particles[p];
  50501. this._shape = this._particle._model._shape;
  50502. this._shapeUV = this._particle._model._shapeUV;
  50503. // call to custom user function to update the particle properties
  50504. this.updateParticle(this._particle);
  50505. if (this._particle.isVisible) {
  50506. // particle rotation matrix
  50507. if (this.billboard) {
  50508. this._particle.rotation.x = 0.0;
  50509. this._particle.rotation.y = 0.0;
  50510. }
  50511. if (this._computeParticleRotation || this.billboard) {
  50512. if (this._particle.rotationQuaternion) {
  50513. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  50514. }
  50515. else {
  50516. this._yaw = this._particle.rotation.y;
  50517. this._pitch = this._particle.rotation.x;
  50518. this._roll = this._particle.rotation.z;
  50519. this._quaternionRotationYPR();
  50520. }
  50521. this._quaternionToRotationMatrix();
  50522. }
  50523. // particle vertex loop
  50524. for (pt = 0; pt < this._shape.length; pt++) {
  50525. idx = index + pt * 3;
  50526. colidx = colorIndex + pt * 4;
  50527. uvidx = uvIndex + pt * 2;
  50528. this._vertex.x = this._shape[pt].x;
  50529. this._vertex.y = this._shape[pt].y;
  50530. this._vertex.z = this._shape[pt].z;
  50531. if (this._computeParticleVertex) {
  50532. this.updateParticleVertex(this._particle, this._vertex, pt);
  50533. }
  50534. // positions
  50535. this._vertex.x *= this._particle.scaling.x;
  50536. this._vertex.y *= this._particle.scaling.y;
  50537. this._vertex.z *= this._particle.scaling.z;
  50538. 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];
  50539. 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;
  50540. 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;
  50541. 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;
  50542. 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;
  50543. 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;
  50544. 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;
  50545. if (this._computeBoundingBox) {
  50546. if (this._positions32[idx] < this._minimum.x) {
  50547. this._minimum.x = this._positions32[idx];
  50548. }
  50549. if (this._positions32[idx] > this._maximum.x) {
  50550. this._maximum.x = this._positions32[idx];
  50551. }
  50552. if (this._positions32[idx + 1] < this._minimum.y) {
  50553. this._minimum.y = this._positions32[idx + 1];
  50554. }
  50555. if (this._positions32[idx + 1] > this._maximum.y) {
  50556. this._maximum.y = this._positions32[idx + 1];
  50557. }
  50558. if (this._positions32[idx + 2] < this._minimum.z) {
  50559. this._minimum.z = this._positions32[idx + 2];
  50560. }
  50561. if (this._positions32[idx + 2] > this._maximum.z) {
  50562. this._maximum.z = this._positions32[idx + 2];
  50563. }
  50564. }
  50565. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  50566. if (!this._computeParticleVertex) {
  50567. this._normal.x = this._fixedNormal32[idx];
  50568. this._normal.y = this._fixedNormal32[idx + 1];
  50569. this._normal.z = this._fixedNormal32[idx + 2];
  50570. 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]);
  50571. 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]);
  50572. 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]);
  50573. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  50574. 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;
  50575. 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;
  50576. }
  50577. if (this._computeParticleColor) {
  50578. this._colors32[colidx] = this._particle.color.r;
  50579. this._colors32[colidx + 1] = this._particle.color.g;
  50580. this._colors32[colidx + 2] = this._particle.color.b;
  50581. this._colors32[colidx + 3] = this._particle.color.a;
  50582. }
  50583. if (this._computeParticleTexture) {
  50584. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50585. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50586. }
  50587. }
  50588. }
  50589. else {
  50590. for (pt = 0; pt < this._shape.length; pt++) {
  50591. idx = index + pt * 3;
  50592. colidx = colorIndex + pt * 4;
  50593. uvidx = uvIndex + pt * 2;
  50594. this._positions32[idx] = this._camera.position.x;
  50595. this._positions32[idx + 1] = this._camera.position.y;
  50596. this._positions32[idx + 2] = this._camera.position.z;
  50597. this._normals32[idx] = 0.0;
  50598. this._normals32[idx + 1] = 0.0;
  50599. this._normals32[idx + 2] = 0.0;
  50600. if (this._computeParticleColor) {
  50601. this._colors32[colidx] = this._particle.color.r;
  50602. this._colors32[colidx + 1] = this._particle.color.g;
  50603. this._colors32[colidx + 2] = this._particle.color.b;
  50604. this._colors32[colidx + 3] = this._particle.color.a;
  50605. }
  50606. if (this._computeParticleTexture) {
  50607. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  50608. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  50609. }
  50610. }
  50611. }
  50612. // if the particle intersections must be computed : update the bbInfo
  50613. if (this._particlesIntersect) {
  50614. var bInfo = this._particle._boundingInfo;
  50615. var bBox = bInfo.boundingBox;
  50616. var bSphere = bInfo.boundingSphere;
  50617. if (!this._bSphereOnly) {
  50618. // place, scale and rotate the particle bbox within the SPS local system, then update it
  50619. for (var b = 0; b < bBox.vectors.length; b++) {
  50620. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  50621. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  50622. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  50623. 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];
  50624. 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;
  50625. 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;
  50626. 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;
  50627. 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;
  50628. 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;
  50629. 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;
  50630. }
  50631. bBox._update(this.mesh._worldMatrix);
  50632. }
  50633. // place and scale the particle bouding sphere in the SPS local system, then update it
  50634. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  50635. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  50636. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  50637. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  50638. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  50639. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  50640. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  50641. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  50642. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  50643. 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));
  50644. bSphere._update(this.mesh._worldMatrix);
  50645. }
  50646. // increment indexes for the next particle
  50647. index = idx + 3;
  50648. colorIndex = colidx + 4;
  50649. uvIndex = uvidx + 2;
  50650. }
  50651. // if the VBO must be updated
  50652. if (update) {
  50653. if (this._computeParticleColor) {
  50654. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  50655. }
  50656. if (this._computeParticleTexture) {
  50657. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  50658. }
  50659. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  50660. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  50661. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  50662. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  50663. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  50664. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  50665. for (var i = 0; i < this._normals32.length; i++) {
  50666. this._fixedNormal32[i] = this._normals32[i];
  50667. }
  50668. }
  50669. if (!this.mesh.areNormalsFrozen) {
  50670. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  50671. }
  50672. }
  50673. }
  50674. if (this._computeBoundingBox) {
  50675. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  50676. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  50677. }
  50678. this.afterUpdateParticles(start, end, update);
  50679. };
  50680. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  50681. this._halfroll = this._roll * 0.5;
  50682. this._halfpitch = this._pitch * 0.5;
  50683. this._halfyaw = this._yaw * 0.5;
  50684. this._sinRoll = Math.sin(this._halfroll);
  50685. this._cosRoll = Math.cos(this._halfroll);
  50686. this._sinPitch = Math.sin(this._halfpitch);
  50687. this._cosPitch = Math.cos(this._halfpitch);
  50688. this._sinYaw = Math.sin(this._halfyaw);
  50689. this._cosYaw = Math.cos(this._halfyaw);
  50690. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  50691. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  50692. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  50693. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  50694. };
  50695. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  50696. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  50697. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  50698. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  50699. this._rotMatrix.m[3] = 0;
  50700. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  50701. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  50702. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  50703. this._rotMatrix.m[7] = 0;
  50704. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  50705. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  50706. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  50707. this._rotMatrix.m[11] = 0;
  50708. this._rotMatrix.m[12] = 0;
  50709. this._rotMatrix.m[13] = 0;
  50710. this._rotMatrix.m[14] = 0;
  50711. this._rotMatrix.m[15] = 1.0;
  50712. };
  50713. /**
  50714. * Disposes the SPS
  50715. */
  50716. SolidParticleSystem.prototype.dispose = function () {
  50717. this.mesh.dispose();
  50718. this.vars = null;
  50719. // drop references to internal big arrays for the GC
  50720. this._positions = null;
  50721. this._indices = null;
  50722. this._normals = null;
  50723. this._uvs = null;
  50724. this._colors = null;
  50725. this._positions32 = null;
  50726. this._normals32 = null;
  50727. this._fixedNormal32 = null;
  50728. this._uvs32 = null;
  50729. this._colors32 = null;
  50730. this.pickedParticles = null;
  50731. };
  50732. /**
  50733. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  50734. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50735. */
  50736. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  50737. if (!this._isVisibilityBoxLocked) {
  50738. this.mesh.refreshBoundingInfo();
  50739. }
  50740. };
  50741. /**
  50742. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  50743. * @param size the size (float) of the visibility box
  50744. * note : this doesn't lock the SPS mesh bounding box.
  50745. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50746. */
  50747. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  50748. var vis = size / 2;
  50749. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  50750. };
  50751. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  50752. // getter and setter
  50753. get: function () {
  50754. return this._alwaysVisible;
  50755. },
  50756. /**
  50757. * Sets the SPS as always visible or not
  50758. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50759. */
  50760. set: function (val) {
  50761. this._alwaysVisible = val;
  50762. this.mesh.alwaysSelectAsActiveMesh = val;
  50763. },
  50764. enumerable: true,
  50765. configurable: true
  50766. });
  50767. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  50768. get: function () {
  50769. return this._isVisibilityBoxLocked;
  50770. },
  50771. /**
  50772. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  50773. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  50774. */
  50775. set: function (val) {
  50776. this._isVisibilityBoxLocked = val;
  50777. this.mesh.getBoundingInfo().isLocked = val;
  50778. },
  50779. enumerable: true,
  50780. configurable: true
  50781. });
  50782. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  50783. // getters
  50784. get: function () {
  50785. return this._computeParticleRotation;
  50786. },
  50787. // Optimizer setters
  50788. /**
  50789. * Tells to `setParticles()` to compute the particle rotations or not.
  50790. * Default value : true. The SPS is faster when it's set to false.
  50791. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  50792. */
  50793. set: function (val) {
  50794. this._computeParticleRotation = val;
  50795. },
  50796. enumerable: true,
  50797. configurable: true
  50798. });
  50799. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  50800. get: function () {
  50801. return this._computeParticleColor;
  50802. },
  50803. /**
  50804. * Tells to `setParticles()` to compute the particle colors or not.
  50805. * Default value : true. The SPS is faster when it's set to false.
  50806. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  50807. */
  50808. set: function (val) {
  50809. this._computeParticleColor = val;
  50810. },
  50811. enumerable: true,
  50812. configurable: true
  50813. });
  50814. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  50815. get: function () {
  50816. return this._computeParticleTexture;
  50817. },
  50818. /**
  50819. * Tells to `setParticles()` to compute the particle textures or not.
  50820. * Default value : true. The SPS is faster when it's set to false.
  50821. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  50822. */
  50823. set: function (val) {
  50824. this._computeParticleTexture = val;
  50825. },
  50826. enumerable: true,
  50827. configurable: true
  50828. });
  50829. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50830. get: function () {
  50831. return this._computeParticleVertex;
  50832. },
  50833. /**
  50834. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50835. * Default value : false. The SPS is faster when it's set to false.
  50836. * Note : the particle custom vertex positions aren't stored values.
  50837. */
  50838. set: function (val) {
  50839. this._computeParticleVertex = val;
  50840. },
  50841. enumerable: true,
  50842. configurable: true
  50843. });
  50844. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50845. get: function () {
  50846. return this._computeBoundingBox;
  50847. },
  50848. /**
  50849. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50850. */
  50851. set: function (val) {
  50852. this._computeBoundingBox = val;
  50853. },
  50854. enumerable: true,
  50855. configurable: true
  50856. });
  50857. // =======================================================================
  50858. // Particle behavior logic
  50859. // these following methods may be overwritten by the user to fit his needs
  50860. /**
  50861. * This function does nothing. It may be overwritten to set all the particle first values.
  50862. * The SPS doesn't call this function, you may have to call it by your own.
  50863. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50864. */
  50865. SolidParticleSystem.prototype.initParticles = function () {
  50866. };
  50867. /**
  50868. * This function does nothing. It may be overwritten to recycle a particle.
  50869. * The SPS doesn't call this function, you may have to call it by your own.
  50870. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50871. */
  50872. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50873. return particle;
  50874. };
  50875. /**
  50876. * Updates a particle : this function should be overwritten by the user.
  50877. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50878. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50879. * ex : just set a particle position or velocity and recycle conditions
  50880. */
  50881. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50882. return particle;
  50883. };
  50884. /**
  50885. * Updates a vertex of a particle : it can be overwritten by the user.
  50886. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50887. * @param particle the current particle
  50888. * @param vertex the current index of the current particle
  50889. * @param pt the index of the current vertex in the particle shape
  50890. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50891. * ex : just set a vertex particle position
  50892. */
  50893. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50894. return vertex;
  50895. };
  50896. /**
  50897. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50898. * This does nothing and may be overwritten by the user.
  50899. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50900. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50901. * @param update the boolean update value actually passed to setParticles()
  50902. */
  50903. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50904. };
  50905. /**
  50906. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50907. * This will be passed three parameters.
  50908. * This does nothing and may be overwritten by the user.
  50909. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50910. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50911. * @param update the boolean update value actually passed to setParticles()
  50912. */
  50913. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50914. };
  50915. return SolidParticleSystem;
  50916. }());
  50917. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50918. })(BABYLON || (BABYLON = {}));
  50919. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50920. var BABYLON;
  50921. (function (BABYLON) {
  50922. var Internals;
  50923. (function (Internals) {
  50924. var FileFaceOrientation = (function () {
  50925. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  50926. this.name = name;
  50927. this.worldAxisForNormal = worldAxisForNormal;
  50928. this.worldAxisForFileX = worldAxisForFileX;
  50929. this.worldAxisForFileY = worldAxisForFileY;
  50930. }
  50931. return FileFaceOrientation;
  50932. }());
  50933. ;
  50934. /**
  50935. * Helper class dealing with the extraction of spherical polynomial dataArray
  50936. * from a cube map.
  50937. */
  50938. var CubeMapToSphericalPolynomialTools = (function () {
  50939. function CubeMapToSphericalPolynomialTools() {
  50940. }
  50941. /**
  50942. * Converts a cubemap to the according Spherical Polynomial data.
  50943. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50944. *
  50945. * @param cubeInfo The Cube map to extract the information from.
  50946. * @return The Spherical Polynomial data.
  50947. */
  50948. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50949. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50950. var totalSolidAngle = 0.0;
  50951. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50952. var du = 2.0 / cubeInfo.size;
  50953. var dv = du;
  50954. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50955. var minUV = du * 0.5 - 1.0;
  50956. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50957. var fileFace = this.FileFaces[faceIndex];
  50958. var dataArray = cubeInfo[fileFace.name];
  50959. var v = minUV;
  50960. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50961. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50962. // Because SP is still linear, so summation is fine in that basis.
  50963. for (var y = 0; y < cubeInfo.size; y++) {
  50964. var u = minUV;
  50965. for (var x = 0; x < cubeInfo.size; x++) {
  50966. // World direction (not normalised)
  50967. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50968. worldDirection.normalize();
  50969. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50970. if (1) {
  50971. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50972. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50973. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50974. var color = new BABYLON.Color3(r, g, b);
  50975. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50976. }
  50977. else {
  50978. if (faceIndex == 0) {
  50979. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50980. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50981. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50982. }
  50983. else if (faceIndex == 1) {
  50984. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50985. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50986. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50987. }
  50988. else if (faceIndex == 2) {
  50989. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50990. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50991. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50992. }
  50993. else if (faceIndex == 3) {
  50994. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50995. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50996. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50997. }
  50998. else if (faceIndex == 4) {
  50999. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  51000. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  51001. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  51002. }
  51003. else if (faceIndex == 5) {
  51004. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  51005. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  51006. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  51007. }
  51008. 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]);
  51009. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  51010. }
  51011. totalSolidAngle += deltaSolidAngle;
  51012. u += du;
  51013. }
  51014. v += dv;
  51015. }
  51016. }
  51017. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  51018. var correction = correctSolidAngle / totalSolidAngle;
  51019. sphericalHarmonics.scale(correction);
  51020. // Additionally scale by pi -- audit needed
  51021. sphericalHarmonics.scale(1.0 / Math.PI);
  51022. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  51023. };
  51024. return CubeMapToSphericalPolynomialTools;
  51025. }());
  51026. CubeMapToSphericalPolynomialTools.FileFaces = [
  51027. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  51028. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  51029. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  51030. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  51031. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  51032. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  51033. ];
  51034. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  51035. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51036. })(BABYLON || (BABYLON = {}));
  51037. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  51038. var BABYLON;
  51039. (function (BABYLON) {
  51040. var Internals;
  51041. (function (Internals) {
  51042. /**
  51043. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  51044. */
  51045. var PanoramaToCubeMapTools = (function () {
  51046. function PanoramaToCubeMapTools() {
  51047. }
  51048. /**
  51049. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  51050. *
  51051. * @param float32Array The source data.
  51052. * @param inputWidth The width of the input panorama.
  51053. * @param inputhHeight The height of the input panorama.
  51054. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  51055. * @return The cubemap data
  51056. */
  51057. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  51058. if (!float32Array) {
  51059. throw "ConvertPanoramaToCubemap: input cannot be null";
  51060. }
  51061. if (float32Array.length != inputWidth * inputHeight * 3) {
  51062. throw "ConvertPanoramaToCubemap: input size is wrong";
  51063. }
  51064. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  51065. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  51066. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  51067. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  51068. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  51069. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  51070. return {
  51071. front: textureFront,
  51072. back: textureBack,
  51073. left: textureLeft,
  51074. right: textureRight,
  51075. up: textureUp,
  51076. down: textureDown,
  51077. size: size
  51078. };
  51079. };
  51080. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  51081. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  51082. var textureArray = new Float32Array(buffer);
  51083. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  51084. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  51085. var dy = 1 / texSize;
  51086. var fy = 0;
  51087. for (var y = 0; y < texSize; y++) {
  51088. var xv1 = faceData[0];
  51089. var xv2 = faceData[2];
  51090. for (var x = 0; x < texSize; x++) {
  51091. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  51092. v.normalize();
  51093. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  51094. // 3 channels per pixels
  51095. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  51096. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  51097. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  51098. xv1 = xv1.add(rotDX1);
  51099. xv2 = xv2.add(rotDX2);
  51100. }
  51101. fy += dy;
  51102. }
  51103. return textureArray;
  51104. };
  51105. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  51106. var theta = Math.atan2(vDir.z, vDir.x);
  51107. var phi = Math.acos(vDir.y);
  51108. while (theta < -Math.PI)
  51109. theta += 2 * Math.PI;
  51110. while (theta > Math.PI)
  51111. theta -= 2 * Math.PI;
  51112. var dx = theta / Math.PI;
  51113. var dy = phi / Math.PI;
  51114. // recenter.
  51115. dx = dx * 0.5 + 0.5;
  51116. var px = Math.round(dx * inputWidth);
  51117. if (px < 0)
  51118. px = 0;
  51119. else if (px >= inputWidth)
  51120. px = inputWidth - 1;
  51121. var py = Math.round(dy * inputHeight);
  51122. if (py < 0)
  51123. py = 0;
  51124. else if (py >= inputHeight)
  51125. py = inputHeight - 1;
  51126. var inputY = (inputHeight - py - 1);
  51127. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  51128. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  51129. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  51130. return {
  51131. r: r,
  51132. g: g,
  51133. b: b
  51134. };
  51135. };
  51136. return PanoramaToCubeMapTools;
  51137. }());
  51138. PanoramaToCubeMapTools.FACE_FRONT = [
  51139. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  51140. new BABYLON.Vector3(1.0, -1.0, -1.0),
  51141. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  51142. new BABYLON.Vector3(1.0, 1.0, -1.0)
  51143. ];
  51144. PanoramaToCubeMapTools.FACE_BACK = [
  51145. new BABYLON.Vector3(1.0, -1.0, 1.0),
  51146. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  51147. new BABYLON.Vector3(1.0, 1.0, 1.0),
  51148. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  51149. ];
  51150. PanoramaToCubeMapTools.FACE_RIGHT = [
  51151. new BABYLON.Vector3(1.0, -1.0, -1.0),
  51152. new BABYLON.Vector3(1.0, -1.0, 1.0),
  51153. new BABYLON.Vector3(1.0, 1.0, -1.0),
  51154. new BABYLON.Vector3(1.0, 1.0, 1.0)
  51155. ];
  51156. PanoramaToCubeMapTools.FACE_LEFT = [
  51157. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  51158. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  51159. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  51160. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  51161. ];
  51162. PanoramaToCubeMapTools.FACE_DOWN = [
  51163. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  51164. new BABYLON.Vector3(1.0, 1.0, -1.0),
  51165. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  51166. new BABYLON.Vector3(1.0, 1.0, 1.0)
  51167. ];
  51168. PanoramaToCubeMapTools.FACE_UP = [
  51169. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  51170. new BABYLON.Vector3(1.0, -1.0, 1.0),
  51171. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  51172. new BABYLON.Vector3(1.0, -1.0, -1.0)
  51173. ];
  51174. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  51175. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51176. })(BABYLON || (BABYLON = {}));
  51177. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  51178. var BABYLON;
  51179. (function (BABYLON) {
  51180. var Internals;
  51181. (function (Internals) {
  51182. ;
  51183. /**
  51184. * This groups tools to convert HDR texture to native colors array.
  51185. */
  51186. var HDRTools = (function () {
  51187. function HDRTools() {
  51188. }
  51189. HDRTools.Ldexp = function (mantissa, exponent) {
  51190. if (exponent > 1023) {
  51191. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  51192. }
  51193. if (exponent < -1074) {
  51194. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  51195. }
  51196. return mantissa * Math.pow(2, exponent);
  51197. };
  51198. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  51199. if (exponent > 0) {
  51200. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  51201. float32array[index + 0] = red * exponent;
  51202. float32array[index + 1] = green * exponent;
  51203. float32array[index + 2] = blue * exponent;
  51204. }
  51205. else {
  51206. float32array[index + 0] = 0;
  51207. float32array[index + 1] = 0;
  51208. float32array[index + 2] = 0;
  51209. }
  51210. };
  51211. HDRTools.readStringLine = function (uint8array, startIndex) {
  51212. var line = "";
  51213. var character = "";
  51214. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  51215. character = String.fromCharCode(uint8array[i]);
  51216. if (character == "\n") {
  51217. break;
  51218. }
  51219. line += character;
  51220. }
  51221. return line;
  51222. };
  51223. /**
  51224. * Reads header information from an RGBE texture stored in a native array.
  51225. * More information on this format are available here:
  51226. * https://en.wikipedia.org/wiki/RGBE_image_format
  51227. *
  51228. * @param uint8array The binary file stored in native array.
  51229. * @return The header information.
  51230. */
  51231. HDRTools.RGBE_ReadHeader = function (uint8array) {
  51232. var height = 0;
  51233. var width = 0;
  51234. var line = this.readStringLine(uint8array, 0);
  51235. if (line[0] != '#' || line[1] != '?') {
  51236. throw "Bad HDR Format.";
  51237. }
  51238. var endOfHeader = false;
  51239. var findFormat = false;
  51240. var lineIndex = 0;
  51241. do {
  51242. lineIndex += (line.length + 1);
  51243. line = this.readStringLine(uint8array, lineIndex);
  51244. if (line == "FORMAT=32-bit_rle_rgbe") {
  51245. findFormat = true;
  51246. }
  51247. else if (line.length == 0) {
  51248. endOfHeader = true;
  51249. }
  51250. } while (!endOfHeader);
  51251. if (!findFormat) {
  51252. throw "HDR Bad header format, unsupported FORMAT";
  51253. }
  51254. lineIndex += (line.length + 1);
  51255. line = this.readStringLine(uint8array, lineIndex);
  51256. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  51257. var match = sizeRegexp.exec(line);
  51258. // TODO. Support +Y and -X if needed.
  51259. if (match.length < 3) {
  51260. throw "HDR Bad header format, no size";
  51261. }
  51262. width = parseInt(match[2]);
  51263. height = parseInt(match[1]);
  51264. if (width < 8 || width > 0x7fff) {
  51265. throw "HDR Bad header format, unsupported size";
  51266. }
  51267. lineIndex += (line.length + 1);
  51268. return {
  51269. height: height,
  51270. width: width,
  51271. dataPosition: lineIndex
  51272. };
  51273. };
  51274. /**
  51275. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  51276. * This RGBE texture needs to store the information as a panorama.
  51277. *
  51278. * More information on this format are available here:
  51279. * https://en.wikipedia.org/wiki/RGBE_image_format
  51280. *
  51281. * @param buffer The binary file stored in an array buffer.
  51282. * @param size The expected size of the extracted cubemap.
  51283. * @return The Cube Map information.
  51284. */
  51285. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  51286. var uint8array = new Uint8Array(buffer);
  51287. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  51288. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51289. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  51290. return cubeMapData;
  51291. };
  51292. /**
  51293. * Returns the pixels data extracted from an RGBE texture.
  51294. * This pixels will be stored left to right up to down in the R G B order in one array.
  51295. *
  51296. * More information on this format are available here:
  51297. * https://en.wikipedia.org/wiki/RGBE_image_format
  51298. *
  51299. * @param uint8array The binary file stored in an array buffer.
  51300. * @param hdrInfo The header information of the file.
  51301. * @return The pixels data in RGB right to left up to down order.
  51302. */
  51303. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  51304. // Keep for multi format supports.
  51305. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  51306. };
  51307. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  51308. var num_scanlines = hdrInfo.height;
  51309. var scanline_width = hdrInfo.width;
  51310. var a, b, c, d, count;
  51311. var dataIndex = hdrInfo.dataPosition;
  51312. var index = 0, endIndex = 0, i = 0;
  51313. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  51314. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  51315. // 3 channels of 4 bytes per pixel in float.
  51316. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  51317. var resultArray = new Float32Array(resultBuffer);
  51318. // read in each successive scanline
  51319. while (num_scanlines > 0) {
  51320. a = uint8array[dataIndex++];
  51321. b = uint8array[dataIndex++];
  51322. c = uint8array[dataIndex++];
  51323. d = uint8array[dataIndex++];
  51324. if (a != 2 || b != 2 || (c & 0x80)) {
  51325. // this file is not run length encoded
  51326. throw "HDR Bad header format, not RLE";
  51327. }
  51328. if (((c << 8) | d) != scanline_width) {
  51329. throw "HDR Bad header format, wrong scan line width";
  51330. }
  51331. index = 0;
  51332. // read each of the four channels for the scanline into the buffer
  51333. for (i = 0; i < 4; i++) {
  51334. endIndex = (i + 1) * scanline_width;
  51335. while (index < endIndex) {
  51336. a = uint8array[dataIndex++];
  51337. b = uint8array[dataIndex++];
  51338. if (a > 128) {
  51339. // a run of the same value
  51340. count = a - 128;
  51341. if ((count == 0) || (count > endIndex - index)) {
  51342. throw "HDR Bad Format, bad scanline data (run)";
  51343. }
  51344. while (count-- > 0) {
  51345. scanLineArray[index++] = b;
  51346. }
  51347. }
  51348. else {
  51349. // a non-run
  51350. count = a;
  51351. if ((count == 0) || (count > endIndex - index)) {
  51352. throw "HDR Bad Format, bad scanline data (non-run)";
  51353. }
  51354. scanLineArray[index++] = b;
  51355. if (--count > 0) {
  51356. for (var j = 0; j < count; j++) {
  51357. scanLineArray[index++] = uint8array[dataIndex++];
  51358. }
  51359. }
  51360. }
  51361. }
  51362. }
  51363. // now convert data from buffer into floats
  51364. for (i = 0; i < scanline_width; i++) {
  51365. a = scanLineArray[i];
  51366. b = scanLineArray[i + scanline_width];
  51367. c = scanLineArray[i + 2 * scanline_width];
  51368. d = scanLineArray[i + 3 * scanline_width];
  51369. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  51370. }
  51371. num_scanlines--;
  51372. }
  51373. return resultArray;
  51374. };
  51375. return HDRTools;
  51376. }());
  51377. Internals.HDRTools = HDRTools;
  51378. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51379. })(BABYLON || (BABYLON = {}));
  51380. //# sourceMappingURL=babylon.tools.hdr.js.map
  51381. //_______________________________________________________________
  51382. // Extracted from CubeMapGen:
  51383. // https://code.google.com/archive/p/cubemapgen/
  51384. //
  51385. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51386. //_______________________________________________________________
  51387. var BABYLON;
  51388. (function (BABYLON) {
  51389. var Internals;
  51390. (function (Internals) {
  51391. /**
  51392. * The bounding box information used during the conversion process.
  51393. */
  51394. var CMGBoundinBox = (function () {
  51395. function CMGBoundinBox() {
  51396. this.min = new BABYLON.Vector3(0, 0, 0);
  51397. this.max = new BABYLON.Vector3(0, 0, 0);
  51398. this.clear();
  51399. }
  51400. CMGBoundinBox.prototype.clear = function () {
  51401. this.min.x = CMGBoundinBox.MAX;
  51402. this.min.y = CMGBoundinBox.MAX;
  51403. this.min.z = CMGBoundinBox.MAX;
  51404. this.max.x = CMGBoundinBox.MIN;
  51405. this.max.y = CMGBoundinBox.MIN;
  51406. this.max.z = CMGBoundinBox.MIN;
  51407. };
  51408. CMGBoundinBox.prototype.augment = function (x, y, z) {
  51409. this.min.x = Math.min(this.min.x, x);
  51410. this.min.y = Math.min(this.min.y, y);
  51411. this.min.z = Math.min(this.min.z, z);
  51412. this.max.x = Math.max(this.max.x, x);
  51413. this.max.y = Math.max(this.max.y, y);
  51414. this.max.z = Math.max(this.max.z, z);
  51415. };
  51416. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  51417. this.min.x = Math.max(this.min.x, x);
  51418. this.min.y = Math.max(this.min.y, y);
  51419. this.min.z = Math.max(this.min.z, z);
  51420. };
  51421. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  51422. this.max.x = Math.min(this.max.x, x);
  51423. this.max.y = Math.min(this.max.y, y);
  51424. this.max.z = Math.min(this.max.z, z);
  51425. };
  51426. CMGBoundinBox.prototype.empty = function () {
  51427. if ((this.min.x > this.max.y) ||
  51428. (this.min.y > this.max.y) ||
  51429. (this.min.z > this.max.y)) {
  51430. return true;
  51431. }
  51432. else {
  51433. return false;
  51434. }
  51435. };
  51436. return CMGBoundinBox;
  51437. }());
  51438. CMGBoundinBox.MAX = Number.MAX_VALUE;
  51439. CMGBoundinBox.MIN = Number.MIN_VALUE;
  51440. /**
  51441. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  51442. * required by the glossinees of a material.
  51443. *
  51444. * This only supports the cosine drop power as well as Warp fixup generation method.
  51445. *
  51446. * This is using the process from CubeMapGen described here:
  51447. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  51448. */
  51449. var PMREMGenerator = (function () {
  51450. /**
  51451. * Constructor of the generator.
  51452. *
  51453. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  51454. * @param inputSize The size of the cubemap faces
  51455. * @param outputSize The size of the output cubemap faces
  51456. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  51457. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  51458. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  51459. * @param specularPower The max specular level of the desired cubemap
  51460. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  51461. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  51462. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  51463. */
  51464. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  51465. this.input = input;
  51466. this.inputSize = inputSize;
  51467. this.outputSize = outputSize;
  51468. this.maxNumMipLevels = maxNumMipLevels;
  51469. this.numChannels = numChannels;
  51470. this.isFloat = isFloat;
  51471. this.specularPower = specularPower;
  51472. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  51473. this.excludeBase = excludeBase;
  51474. this.fixup = fixup;
  51475. this._outputSurface = [];
  51476. this._numMipLevels = 0;
  51477. }
  51478. /**
  51479. * Launches the filter process and return the result.
  51480. *
  51481. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  51482. */
  51483. PMREMGenerator.prototype.filterCubeMap = function () {
  51484. // Init cubemap processor
  51485. this.init();
  51486. // Filters the cubemap
  51487. this.filterCubeMapMipChain();
  51488. // Returns the filtered mips.
  51489. return this._outputSurface;
  51490. };
  51491. PMREMGenerator.prototype.init = function () {
  51492. var i;
  51493. var j;
  51494. var mipLevelSize;
  51495. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  51496. if (this.maxNumMipLevels == 0) {
  51497. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  51498. }
  51499. //first miplevel size
  51500. mipLevelSize = this.outputSize;
  51501. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  51502. for (j = 0; j < this.maxNumMipLevels; j++) {
  51503. this._outputSurface.length++;
  51504. this._outputSurface[j] = [];
  51505. //Iterate over faces for output images
  51506. for (i = 0; i < 6; i++) {
  51507. this._outputSurface[j].length++;
  51508. // Initializes a new array for the output.
  51509. if (this.isFloat) {
  51510. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51511. }
  51512. else {
  51513. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  51514. }
  51515. }
  51516. //next mip level is half size
  51517. mipLevelSize >>= 1;
  51518. this._numMipLevels++;
  51519. //terminate if mip chain becomes too small
  51520. if (mipLevelSize == 0) {
  51521. this.maxNumMipLevels = j;
  51522. return;
  51523. }
  51524. }
  51525. };
  51526. //--------------------------------------------------------------------------------------
  51527. //Cube map filtering and mip chain generation.
  51528. // the cube map filtereing is specified using a number of parameters:
  51529. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  51530. // indicates the region of the hemisphere to filter over for each tap.
  51531. //
  51532. // Note that the top mip level is also a filtered version of the original input images
  51533. // as well in order to create mip chains for diffuse environment illumination.
  51534. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  51535. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  51536. //
  51537. // Then the mip angle used to genreate the next level of the mip chain from the first level
  51538. // is a_InitialMipAngle
  51539. //
  51540. // The angle for the subsequent levels of the mip chain are specified by their parents
  51541. // filtering angle and a per-level scale and bias
  51542. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  51543. //
  51544. //--------------------------------------------------------------------------------------
  51545. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  51546. // First, take count of the lighting model to modify SpecularPower
  51547. // 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;
  51548. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  51549. //Cone angle start (for generating subsequent mip levels)
  51550. var currentSpecularPower = this.specularPower;
  51551. //Build filter lookup tables based on the source miplevel size
  51552. this.precomputeFilterLookupTables(this.inputSize);
  51553. // Note that we need to filter the first level before generating mipmap
  51554. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  51555. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  51556. // TODO : Write a function to copy and scale the base mipmap in output
  51557. // I am just lazy here and just put a high specular power value, and do some if.
  51558. if (this.excludeBase && (levelIndex == 0)) {
  51559. // 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).
  51560. currentSpecularPower = 100000.0;
  51561. }
  51562. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  51563. var srcCubeImage = this.input;
  51564. var dstCubeImage = this._outputSurface[levelIndex];
  51565. var dstSize = this.outputSize >> levelIndex;
  51566. // Compute required angle.
  51567. var angle = this.getBaseFilterAngle(currentSpecularPower);
  51568. // filter cube surfaces
  51569. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  51570. // fix seams
  51571. if (this.fixup) {
  51572. this.fixupCubeEdges(dstCubeImage, dstSize);
  51573. }
  51574. // Decrease the specular power to generate the mipmap chain
  51575. // TODO : Use another method for Exclude (see first comment at start of the function
  51576. if (this.excludeBase && (levelIndex == 0)) {
  51577. currentSpecularPower = this.specularPower;
  51578. }
  51579. currentSpecularPower *= this.cosinePowerDropPerMip;
  51580. }
  51581. };
  51582. //--------------------------------------------------------------------------------------
  51583. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  51584. // It allow to optimize the texel to access base on the specular power.
  51585. //--------------------------------------------------------------------------------------
  51586. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  51587. // We want to find the alpha such that:
  51588. // cos(alpha)^cosinePower = epsilon
  51589. // That's: acos(epsilon^(1/cosinePower))
  51590. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  51591. var angle = 180.0;
  51592. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  51593. angle *= 180.0 / Math.PI; // Convert to degree
  51594. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  51595. return angle;
  51596. };
  51597. //--------------------------------------------------------------------------------------
  51598. //Builds the following lookup tables prior to filtering:
  51599. // -normalizer cube map
  51600. // -tap weight lookup table
  51601. //
  51602. //--------------------------------------------------------------------------------------
  51603. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  51604. var srcTexelAngle;
  51605. var iCubeFace;
  51606. //clear pre-existing normalizer cube map
  51607. this._normCubeMap = [];
  51608. //Normalized vectors per cubeface and per-texel solid angle
  51609. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  51610. };
  51611. //--------------------------------------------------------------------------------------
  51612. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  51613. //
  51614. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  51615. //
  51616. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  51617. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  51618. // below
  51619. //--------------------------------------------------------------------------------------
  51620. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  51621. var iCubeFace;
  51622. var u;
  51623. var v;
  51624. //iterate over cube faces
  51625. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51626. //First three channels for norm cube, and last channel for solid angle
  51627. this._normCubeMap.push(new Float32Array(size * size * 4));
  51628. //fast texture walk, build normalizer cube map
  51629. var facesData = this.input[iCubeFace];
  51630. for (v = 0; v < size; v++) {
  51631. for (u = 0; u < size; u++) {
  51632. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  51633. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  51634. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  51635. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  51636. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  51637. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  51638. }
  51639. }
  51640. }
  51641. };
  51642. //--------------------------------------------------------------------------------------
  51643. // Convert cubemap face texel coordinates and face idx to 3D vector
  51644. // note the U and V coords are integer coords and range from 0 to size-1
  51645. // this routine can be used to generate a normalizer cube map
  51646. //--------------------------------------------------------------------------------------
  51647. // SL BEGIN
  51648. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  51649. var nvcU;
  51650. var nvcV;
  51651. var tempVec;
  51652. // Change from original AMD code
  51653. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51654. // + 0.5f is for texel center addressing
  51655. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  51656. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  51657. // warp fixup
  51658. if (fixup && size > 1) {
  51659. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  51660. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  51661. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  51662. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  51663. }
  51664. // Get current vector
  51665. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  51666. // U contribution
  51667. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51668. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  51669. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  51670. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  51671. // V contribution and Sum
  51672. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51673. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  51674. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  51675. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  51676. //add face axis
  51677. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  51678. PMREMGenerator._vectorTemp.x += faceAxis[0];
  51679. PMREMGenerator._vectorTemp.y += faceAxis[1];
  51680. PMREMGenerator._vectorTemp.z += faceAxis[2];
  51681. //normalize vector
  51682. PMREMGenerator._vectorTemp.normalize();
  51683. return PMREMGenerator._vectorTemp;
  51684. };
  51685. //--------------------------------------------------------------------------------------
  51686. // Convert 3D vector to cubemap face texel coordinates and face idx
  51687. // note the U and V coords are integer coords and range from 0 to size-1
  51688. // this routine can be used to generate a normalizer cube map
  51689. //
  51690. // returns face IDX and texel coords
  51691. //--------------------------------------------------------------------------------------
  51692. // SL BEGIN
  51693. /*
  51694. Mapping Texture Coordinates to Cube Map Faces
  51695. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  51696. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  51697. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  51698. map arrangement in Pixar's RenderMan package.
  51699. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  51700. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  51701. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  51702. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  51703. the major axis direction). The target column in the table below explains how the major axis direction
  51704. maps to the 2D image of a particular cube map target.
  51705. major axis
  51706. direction target sc tc ma
  51707. ---------- --------------------------------- --- --- ---
  51708. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  51709. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  51710. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  51711. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  51712. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  51713. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  51714. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  51715. an updated (s,t) is calculated as follows
  51716. s = ( sc/|ma| + 1 ) / 2
  51717. t = ( tc/|ma| + 1 ) / 2
  51718. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  51719. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  51720. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  51721. */
  51722. // Note this method return U and V in range from 0 to size-1
  51723. // SL END
  51724. // Store the information in vector3 for convenience (faceindex, u, v)
  51725. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  51726. var maxCoord;
  51727. var faceIdx;
  51728. //absolute value 3
  51729. var absX = Math.abs(x);
  51730. var absY = Math.abs(y);
  51731. var absZ = Math.abs(z);
  51732. if (absX >= absY && absX >= absZ) {
  51733. maxCoord = absX;
  51734. if (x >= 0) {
  51735. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  51736. }
  51737. else {
  51738. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51739. }
  51740. }
  51741. else if (absY >= absX && absY >= absZ) {
  51742. maxCoord = absY;
  51743. if (y >= 0) {
  51744. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51745. }
  51746. else {
  51747. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51748. }
  51749. }
  51750. else {
  51751. maxCoord = absZ;
  51752. if (z >= 0) {
  51753. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51754. }
  51755. else {
  51756. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51757. }
  51758. }
  51759. //divide through by max coord so face vector lies on cube face
  51760. var scale = 1 / maxCoord;
  51761. x *= scale;
  51762. y *= scale;
  51763. z *= scale;
  51764. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  51765. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  51766. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  51767. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  51768. // Modify original AMD code to return value from 0 to Size - 1
  51769. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  51770. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  51771. PMREMGenerator._vectorTemp.x = faceIdx;
  51772. PMREMGenerator._vectorTemp.y = u;
  51773. PMREMGenerator._vectorTemp.z = v;
  51774. return PMREMGenerator._vectorTemp;
  51775. };
  51776. //--------------------------------------------------------------------------------------
  51777. //Original code from Ignacio CastaÒo
  51778. // This formula is from Manne ÷hrstrˆm's thesis.
  51779. // Take two coordiantes in the range [-1, 1] that define a portion of a
  51780. // cube face and return the area of the projection of that portion on the
  51781. // surface of the sphere.
  51782. //--------------------------------------------------------------------------------------
  51783. PMREMGenerator.prototype.areaElement = function (x, y) {
  51784. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  51785. };
  51786. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  51787. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  51788. // (+ 0.5f is for texel center addressing)
  51789. u = (2.0 * (u + 0.5) / size) - 1.0;
  51790. v = (2.0 * (v + 0.5) / size) - 1.0;
  51791. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  51792. var invResolution = 1.0 / size;
  51793. // U and V are the -1..1 texture coordinate on the current face.
  51794. // Get projected area for this texel
  51795. var x0 = u - invResolution;
  51796. var y0 = v - invResolution;
  51797. var x1 = u + invResolution;
  51798. var y1 = v + invResolution;
  51799. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  51800. return solidAngle;
  51801. };
  51802. //--------------------------------------------------------------------------------------
  51803. //The key to the speed of these filtering routines is to quickly define a per-face
  51804. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  51805. // Later these pixels are selectively processed based on their dot products to see if
  51806. // they reside within the filtering cone.
  51807. //
  51808. //This is done by computing the smallest per-texel angle to get a conservative estimate
  51809. // of the number of texels needed to be covered in width and height order to filter the
  51810. // region. the bounding box for the center taps face is defined first, and if the
  51811. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  51812. // defined next
  51813. //--------------------------------------------------------------------------------------
  51814. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  51815. // note that pixels within these regions may be rejected
  51816. // based on the anlge
  51817. var iCubeFace;
  51818. var u;
  51819. var v;
  51820. // bounding box per face to specify region to process
  51821. var filterExtents = [];
  51822. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51823. filterExtents.push(new CMGBoundinBox());
  51824. }
  51825. // min angle a src texel can cover (in degrees)
  51826. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  51827. // angle about center tap to define filter cone
  51828. // filter angle is 1/2 the cone angle
  51829. var filterAngle = filterConeAngle / 2.0;
  51830. //ensure filter angle is larger than a texel
  51831. if (filterAngle < srcTexelAngle) {
  51832. filterAngle = srcTexelAngle;
  51833. }
  51834. //ensure filter cone is always smaller than the hemisphere
  51835. if (filterAngle > 90.0) {
  51836. filterAngle = 90.0;
  51837. }
  51838. // the maximum number of texels in 1D the filter cone angle will cover
  51839. // used to determine bounding box size for filter extents
  51840. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  51841. // ensure conservative region always covers at least one texel
  51842. if (filterSize < 1) {
  51843. filterSize = 1;
  51844. }
  51845. // dotProdThresh threshold based on cone angle to determine whether or not taps
  51846. // reside within the cone angle
  51847. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  51848. // process required faces
  51849. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51850. //iterate over dst cube map face texel
  51851. for (v = 0; v < dstSize; v++) {
  51852. for (u = 0; u < dstSize; u++) {
  51853. //get center tap direction
  51854. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  51855. //clear old per-face filter extents
  51856. this.clearFilterExtents(filterExtents);
  51857. //define per-face filter extents
  51858. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  51859. //perform filtering of src faces using filter extents
  51860. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  51861. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  51862. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  51863. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  51864. }
  51865. }
  51866. }
  51867. };
  51868. //--------------------------------------------------------------------------------------
  51869. //Clear filter extents for the 6 cube map faces
  51870. //--------------------------------------------------------------------------------------
  51871. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  51872. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  51873. filterExtents[iCubeFaces].clear();
  51874. }
  51875. };
  51876. //--------------------------------------------------------------------------------------
  51877. //Define per-face bounding box filter extents
  51878. //
  51879. // These define conservative texel regions in each of the faces the filter can possibly
  51880. // process. When the pixels in the regions are actually processed, the dot product
  51881. // between the tap vector and the center tap vector is used to determine the weight of
  51882. // the tap and whether or not the tap is within the cone.
  51883. //
  51884. //--------------------------------------------------------------------------------------
  51885. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  51886. //neighboring face and bleed over amount, and width of BBOX for
  51887. // left, right, top, and bottom edges of this face
  51888. var bleedOverAmount = [0, 0, 0, 0];
  51889. var bleedOverBBoxMin = [0, 0, 0, 0];
  51890. var bleedOverBBoxMax = [0, 0, 0, 0];
  51891. var neighborFace;
  51892. var neighborEdge;
  51893. var oppositeFaceIdx;
  51894. //get face idx, and u, v info from center tap dir
  51895. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  51896. var faceIdx = result.x;
  51897. var u = result.y;
  51898. var v = result.z;
  51899. //define bbox size within face
  51900. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  51901. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  51902. filterExtents[faceIdx].clampMin(0, 0, 0);
  51903. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  51904. //u and v extent in face corresponding to center tap
  51905. var minU = filterExtents[faceIdx].min.x;
  51906. var minV = filterExtents[faceIdx].min.y;
  51907. var maxU = filterExtents[faceIdx].max.x;
  51908. var maxV = filterExtents[faceIdx].max.y;
  51909. //bleed over amounts for face across u=0 edge (left)
  51910. bleedOverAmount[0] = (bboxSize - u);
  51911. bleedOverBBoxMin[0] = minV;
  51912. bleedOverBBoxMax[0] = maxV;
  51913. //bleed over amounts for face across u=1 edge (right)
  51914. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  51915. bleedOverBBoxMin[1] = minV;
  51916. bleedOverBBoxMax[1] = maxV;
  51917. //bleed over to face across v=0 edge (up)
  51918. bleedOverAmount[2] = (bboxSize - v);
  51919. bleedOverBBoxMin[2] = minU;
  51920. bleedOverBBoxMax[2] = maxU;
  51921. //bleed over to face across v=1 edge (down)
  51922. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  51923. bleedOverBBoxMin[3] = minU;
  51924. bleedOverBBoxMax[3] = maxU;
  51925. //compute bleed over regions in neighboring faces
  51926. for (var i = 0; i < 4; i++) {
  51927. if (bleedOverAmount[i] > 0) {
  51928. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  51929. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  51930. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  51931. // be flipped: the cases are
  51932. // if a left edge mates with a left or bottom edge on the neighbor
  51933. // if a top edge mates with a top or right edge on the neighbor
  51934. // if a right edge mates with a right or top edge on the neighbor
  51935. // if a bottom edge mates with a bottom or left edge on the neighbor
  51936. //Seeing as the edges are enumerated as follows
  51937. // left =0
  51938. // right =1
  51939. // top =2
  51940. // bottom =3
  51941. //
  51942. // so if the edge enums are the same, or the sum of the enums == 3,
  51943. // the bbox needs to be flipped
  51944. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51945. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51946. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51947. }
  51948. //The way the bounding box is extended onto the neighboring face
  51949. // depends on which edge of neighboring face abuts with this one
  51950. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51951. case PMREMGenerator.CP_EDGE_LEFT:
  51952. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51953. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51954. break;
  51955. case PMREMGenerator.CP_EDGE_RIGHT:
  51956. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51957. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51958. break;
  51959. case PMREMGenerator.CP_EDGE_TOP:
  51960. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51961. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51962. break;
  51963. case PMREMGenerator.CP_EDGE_BOTTOM:
  51964. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51965. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51966. break;
  51967. }
  51968. //clamp filter extents in non-center tap faces to remain within surface
  51969. filterExtents[neighborFace].clampMin(0, 0, 0);
  51970. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51971. }
  51972. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51973. // from the center tap face, then process the opposite face entirely for now.
  51974. //Note that the cases in which this happens, what usually happens is that
  51975. // more than one edge bleeds onto the opposite face, and the bounding box
  51976. // encompasses the entire cube map face.
  51977. if (bleedOverAmount[i] > srcSize) {
  51978. //determine opposite face
  51979. switch (faceIdx) {
  51980. case PMREMGenerator.CP_FACE_X_POS:
  51981. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51982. break;
  51983. case PMREMGenerator.CP_FACE_X_NEG:
  51984. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51985. break;
  51986. case PMREMGenerator.CP_FACE_Y_POS:
  51987. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51988. break;
  51989. case PMREMGenerator.CP_FACE_Y_NEG:
  51990. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51991. break;
  51992. case PMREMGenerator.CP_FACE_Z_POS:
  51993. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51994. break;
  51995. case PMREMGenerator.CP_FACE_Z_NEG:
  51996. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51997. break;
  51998. default:
  51999. break;
  52000. }
  52001. //just encompass entire face for now
  52002. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  52003. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  52004. }
  52005. }
  52006. };
  52007. //--------------------------------------------------------------------------------------
  52008. //ProcessFilterExtents
  52009. // Process bounding box in each cube face
  52010. //
  52011. //--------------------------------------------------------------------------------------
  52012. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  52013. //accumulators are 64-bit floats in order to have the precision needed
  52014. // over a summation of a large number of pixels
  52015. var dstAccum = [0, 0, 0, 0];
  52016. var weightAccum = 0;
  52017. var k = 0;
  52018. var nSrcChannels = this.numChannels;
  52019. // norm cube map and srcCubeMap have same face width
  52020. var faceWidth = srcSize;
  52021. //amount to add to pointer to move to next scanline in images
  52022. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  52023. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  52024. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  52025. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  52026. // iterate over cubefaces
  52027. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  52028. //if bbox is non empty
  52029. if (!filterExtents[iFaceIdx].empty()) {
  52030. var uStart = filterExtents[iFaceIdx].min.x;
  52031. var vStart = filterExtents[iFaceIdx].min.y;
  52032. var uEnd = filterExtents[iFaceIdx].max.x;
  52033. var vEnd = filterExtents[iFaceIdx].max.y;
  52034. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  52035. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  52036. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  52037. for (var v = vStart; v <= vEnd; v++) {
  52038. var normCubeRowWalk = 0;
  52039. var srcCubeRowWalk = 0;
  52040. for (var u = uStart; u <= uEnd; u++) {
  52041. //pointer to direction in cube map associated with texel
  52042. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  52043. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  52044. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  52045. //check dot product to see if texel is within cone
  52046. var tapDotProd = texelVectX * centerTapDir.x +
  52047. texelVectY * centerTapDir.y +
  52048. texelVectZ * centerTapDir.z;
  52049. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  52050. //solid angle stored in 4th channel of normalizer/solid angle cube map
  52051. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  52052. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  52053. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  52054. // so just adding one to specularpower do the trick.
  52055. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  52056. //iterate over channels
  52057. for (k = 0; k < nSrcChannels; k++) {
  52058. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  52059. srcCubeRowWalk++;
  52060. }
  52061. weightAccum += weight; //accumulate weight
  52062. }
  52063. else {
  52064. //step across source pixel
  52065. srcCubeRowWalk += nSrcChannels;
  52066. }
  52067. normCubeRowWalk += 4; // 4 channels per norm cube map.
  52068. }
  52069. startIndexNormCubeMap += normCubePitch;
  52070. startIndexSrcCubeMap += srcCubePitch;
  52071. }
  52072. }
  52073. }
  52074. //divide through by weights if weight is non zero
  52075. if (weightAccum != 0.0) {
  52076. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  52077. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  52078. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  52079. if (this.numChannels > 3) {
  52080. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  52081. }
  52082. }
  52083. else {
  52084. // otherwise sample nearest
  52085. // get face idx and u, v texel coordinate in face
  52086. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  52087. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  52088. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  52089. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  52090. if (this.numChannels > 3) {
  52091. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  52092. }
  52093. }
  52094. return PMREMGenerator._vectorTemp;
  52095. };
  52096. //--------------------------------------------------------------------------------------
  52097. // Fixup cube edges
  52098. //
  52099. // average texels on cube map faces across the edges
  52100. // WARP/BENT Method Only.
  52101. //--------------------------------------------------------------------------------------
  52102. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  52103. var k;
  52104. var j;
  52105. var i;
  52106. var iFace;
  52107. var iCorner = 0;
  52108. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  52109. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  52110. // note that if functionality to filter across the three texels for each corner, then
  52111. //indexed by corner and face idx. the array contains the face the start points belongs to.
  52112. var cornerPtr = [
  52113. [[], [], []],
  52114. [[], [], []],
  52115. [[], [], []],
  52116. [[], [], []],
  52117. [[], [], []],
  52118. [[], [], []],
  52119. [[], [], []],
  52120. [[], [], []]
  52121. ];
  52122. //if there is no fixup, or fixup width = 0, do nothing
  52123. if (cubeMapSize < 1) {
  52124. return;
  52125. }
  52126. //special case 1x1 cubemap, average face colors
  52127. if (cubeMapSize == 1) {
  52128. //iterate over channels
  52129. for (k = 0; k < this.numChannels; k++) {
  52130. var accum = 0.0;
  52131. //iterate over faces to accumulate face colors
  52132. for (iFace = 0; iFace < 6; iFace++) {
  52133. accum += cubeMap[iFace][k];
  52134. }
  52135. //compute average over 6 face colors
  52136. accum /= 6.0;
  52137. //iterate over faces to distribute face colors
  52138. for (iFace = 0; iFace < 6; iFace++) {
  52139. cubeMap[iFace][k] = accum;
  52140. }
  52141. }
  52142. return;
  52143. }
  52144. //iterate over faces to collect list of corner texel pointers
  52145. for (iFace = 0; iFace < 6; iFace++) {
  52146. //the 4 corner pointers for this face
  52147. faceCornerStartIndicies[0] = [iFace, 0];
  52148. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  52149. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  52150. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  52151. //iterate over face corners to collect cube corner pointers
  52152. for (iCorner = 0; iCorner < 4; iCorner++) {
  52153. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  52154. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  52155. cornerNumPtrs[corner]++;
  52156. }
  52157. }
  52158. //iterate over corners to average across corner tap values
  52159. for (iCorner = 0; iCorner < 8; iCorner++) {
  52160. for (k = 0; k < this.numChannels; k++) {
  52161. var cornerTapAccum = 0.0;
  52162. //iterate over corner texels and average results
  52163. for (i = 0; i < 3; i++) {
  52164. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  52165. }
  52166. //divide by 3 to compute average of corner tap values
  52167. cornerTapAccum *= (1.0 / 3.0);
  52168. //iterate over corner texels and average results
  52169. for (i = 0; i < 3; i++) {
  52170. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  52171. }
  52172. }
  52173. }
  52174. //iterate over the twelve edges of the cube to average across edges
  52175. for (i = 0; i < 12; i++) {
  52176. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  52177. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  52178. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  52179. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  52180. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  52181. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  52182. var edgeWalk = 0;
  52183. var neighborEdgeWalk = 0;
  52184. //Determine walking pointers based on edge type
  52185. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  52186. switch (edge) {
  52187. case PMREMGenerator.CP_EDGE_LEFT:
  52188. // no change to faceEdgeStartPtr
  52189. edgeWalk = this.numChannels * cubeMapSize;
  52190. break;
  52191. case PMREMGenerator.CP_EDGE_RIGHT:
  52192. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52193. edgeWalk = this.numChannels * cubeMapSize;
  52194. break;
  52195. case PMREMGenerator.CP_EDGE_TOP:
  52196. // no change to faceEdgeStartPtr
  52197. edgeWalk = this.numChannels;
  52198. break;
  52199. case PMREMGenerator.CP_EDGE_BOTTOM:
  52200. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  52201. edgeWalk = this.numChannels;
  52202. break;
  52203. }
  52204. //For certain types of edge abutments, the neighbor edge walk needs to
  52205. // be flipped: the cases are
  52206. // if a left edge mates with a left or bottom edge on the neighbor
  52207. // if a top edge mates with a top or right edge on the neighbor
  52208. // if a right edge mates with a right or top edge on the neighbor
  52209. // if a bottom edge mates with a bottom or left edge on the neighbor
  52210. //Seeing as the edges are enumerated as follows
  52211. // left =0
  52212. // right =1
  52213. // top =2
  52214. // bottom =3
  52215. //
  52216. //If the edge enums are the same, or the sum of the enums == 3,
  52217. // the neighbor edge walk needs to be flipped
  52218. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  52219. switch (neighborEdge) {
  52220. case PMREMGenerator.CP_EDGE_LEFT:
  52221. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  52222. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  52223. break;
  52224. case PMREMGenerator.CP_EDGE_RIGHT:
  52225. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  52226. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  52227. break;
  52228. case PMREMGenerator.CP_EDGE_TOP:
  52229. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52230. neighborEdgeWalk = -this.numChannels;
  52231. break;
  52232. case PMREMGenerator.CP_EDGE_BOTTOM:
  52233. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  52234. neighborEdgeWalk = -this.numChannels;
  52235. break;
  52236. }
  52237. }
  52238. else {
  52239. //swapped direction neighbor edge walk
  52240. switch (neighborEdge) {
  52241. case PMREMGenerator.CP_EDGE_LEFT:
  52242. //no change to neighborEdgeStartPtr for this case since it points
  52243. // to the upper left corner already
  52244. neighborEdgeWalk = this.numChannels * cubeMapSize;
  52245. break;
  52246. case PMREMGenerator.CP_EDGE_RIGHT:
  52247. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  52248. neighborEdgeWalk = this.numChannels * cubeMapSize;
  52249. break;
  52250. case PMREMGenerator.CP_EDGE_TOP:
  52251. //no change to neighborEdgeStartPtr for this case since it points
  52252. // to the upper left corner already
  52253. neighborEdgeWalk = this.numChannels;
  52254. break;
  52255. case PMREMGenerator.CP_EDGE_BOTTOM:
  52256. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  52257. neighborEdgeWalk = this.numChannels;
  52258. break;
  52259. }
  52260. }
  52261. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  52262. //nearby neighborhood
  52263. //step ahead one texel on edge
  52264. edgeStartIndex += edgeWalk;
  52265. neighborEdgeStartIndex += neighborEdgeWalk;
  52266. // note that this loop does not process the corner texels, since they have already been
  52267. // averaged across faces across earlier
  52268. for (j = 1; j < (cubeMapSize - 1); j++) {
  52269. //for each set of taps along edge, average them
  52270. // and rewrite the results into the edges
  52271. for (k = 0; k < this.numChannels; k++) {
  52272. var edgeTap = cubeMap[face][edgeStartIndex + k];
  52273. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  52274. //compute average of tap intensity values
  52275. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  52276. //propagate average of taps to edge taps
  52277. cubeMap[face][edgeStartIndex + k] = avgTap;
  52278. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  52279. }
  52280. edgeStartIndex += edgeWalk;
  52281. neighborEdgeStartIndex += neighborEdgeWalk;
  52282. }
  52283. }
  52284. };
  52285. return PMREMGenerator;
  52286. }());
  52287. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  52288. PMREMGenerator.CP_UDIR = 0;
  52289. PMREMGenerator.CP_VDIR = 1;
  52290. PMREMGenerator.CP_FACEAXIS = 2;
  52291. //used to index cube faces
  52292. PMREMGenerator.CP_FACE_X_POS = 0;
  52293. PMREMGenerator.CP_FACE_X_NEG = 1;
  52294. PMREMGenerator.CP_FACE_Y_POS = 2;
  52295. PMREMGenerator.CP_FACE_Y_NEG = 3;
  52296. PMREMGenerator.CP_FACE_Z_POS = 4;
  52297. PMREMGenerator.CP_FACE_Z_NEG = 5;
  52298. //used to index image edges
  52299. // NOTE.. the actual number corresponding to the edge is important
  52300. // do not change these, or the code will break
  52301. //
  52302. // CP_EDGE_LEFT is u = 0
  52303. // CP_EDGE_RIGHT is u = width-1
  52304. // CP_EDGE_TOP is v = 0
  52305. // CP_EDGE_BOTTOM is v = height-1
  52306. PMREMGenerator.CP_EDGE_LEFT = 0;
  52307. PMREMGenerator.CP_EDGE_RIGHT = 1;
  52308. PMREMGenerator.CP_EDGE_TOP = 2;
  52309. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  52310. //corners of CUBE map (P or N specifys if it corresponds to the
  52311. // positive or negative direction each of X, Y, and Z
  52312. PMREMGenerator.CP_CORNER_NNN = 0;
  52313. PMREMGenerator.CP_CORNER_NNP = 1;
  52314. PMREMGenerator.CP_CORNER_NPN = 2;
  52315. PMREMGenerator.CP_CORNER_NPP = 3;
  52316. PMREMGenerator.CP_CORNER_PNN = 4;
  52317. PMREMGenerator.CP_CORNER_PNP = 5;
  52318. PMREMGenerator.CP_CORNER_PPN = 6;
  52319. PMREMGenerator.CP_CORNER_PPP = 7;
  52320. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  52321. //3x2 matrices that map cube map indexing vectors in 3d
  52322. // (after face selection and divide through by the
  52323. // _ABSOLUTE VALUE_ of the max coord)
  52324. // into NVC space
  52325. //Note this currently assumes the D3D cube face ordering and orientation
  52326. PMREMGenerator._sgFace2DMapping = [
  52327. //XPOS face
  52328. [[0, 0, -1],
  52329. [0, -1, 0],
  52330. [1, 0, 0]],
  52331. //XNEG face
  52332. [[0, 0, 1],
  52333. [0, -1, 0],
  52334. [-1, 0, 0]],
  52335. //YPOS face
  52336. [[1, 0, 0],
  52337. [0, 0, 1],
  52338. [0, 1, 0]],
  52339. //YNEG face
  52340. [[1, 0, 0],
  52341. [0, 0, -1],
  52342. [0, -1, 0]],
  52343. //ZPOS face
  52344. [[1, 0, 0],
  52345. [0, -1, 0],
  52346. [0, 0, 1]],
  52347. //ZNEG face
  52348. [[-1, 0, 0],
  52349. [0, -1, 0],
  52350. [0, 0, -1]],
  52351. ];
  52352. //------------------------------------------------------------------------------
  52353. // D3D cube map face specification
  52354. // mapping from 3D x,y,z cube map lookup coordinates
  52355. // to 2D within face u,v coordinates
  52356. //
  52357. // --------------------> U direction
  52358. // | (within-face texture space)
  52359. // | _____
  52360. // | | |
  52361. // | | +Y |
  52362. // | _____|_____|_____ _____
  52363. // | | | | | |
  52364. // | | -X | +Z | +X | -Z |
  52365. // | |_____|_____|_____|_____|
  52366. // | | |
  52367. // | | -Y |
  52368. // | |_____|
  52369. // |
  52370. // v V direction
  52371. // (within-face texture space)
  52372. //------------------------------------------------------------------------------
  52373. //Information about neighbors and how texture coorrdinates change across faces
  52374. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  52375. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  52376. //Note this currently assumes the D3D cube face ordering and orientation
  52377. PMREMGenerator._sgCubeNgh = [
  52378. //XPOS face
  52379. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52380. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52381. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52382. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  52383. //XNEG face
  52384. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52385. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  52386. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  52387. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  52388. //YPOS face
  52389. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52390. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52391. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52392. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  52393. //YNEG face
  52394. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52395. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52396. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52397. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  52398. //ZPOS face
  52399. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52400. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52401. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52402. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  52403. //ZNEG face
  52404. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52405. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52406. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  52407. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  52408. ];
  52409. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  52410. // this table is used to average over the edges.
  52411. PMREMGenerator._sgCubeEdgeList = [
  52412. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  52413. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  52414. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  52415. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52416. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  52417. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  52418. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  52419. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  52420. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  52421. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  52422. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  52423. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  52424. ];
  52425. //Information about which of the 8 cube corners are correspond to the
  52426. // the 4 corners in each cube face
  52427. // the order is upper left, upper right, lower left, lower right
  52428. PMREMGenerator._sgCubeCornerList = [
  52429. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  52430. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  52431. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  52432. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  52433. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  52434. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  52435. ];
  52436. Internals.PMREMGenerator = PMREMGenerator;
  52437. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  52438. })(BABYLON || (BABYLON = {}));
  52439. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  52440. var BABYLON;
  52441. (function (BABYLON) {
  52442. /**
  52443. * This represents a texture coming from an HDR input.
  52444. *
  52445. * The only supported format is currently panorama picture stored in RGBE format.
  52446. * Example of such files can be found on HDRLib: http://hdrlib.com/
  52447. */
  52448. var HDRCubeTexture = (function (_super) {
  52449. __extends(HDRCubeTexture, _super);
  52450. /**
  52451. * Instantiates an HDRTexture from the following parameters.
  52452. *
  52453. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  52454. * @param scene The scene the texture will be used in
  52455. * @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.
  52456. * @param noMipmap Forces to not generate the mipmap if true
  52457. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  52458. * @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)
  52459. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  52460. */
  52461. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  52462. if (noMipmap === void 0) { noMipmap = false; }
  52463. if (generateHarmonics === void 0) { generateHarmonics = true; }
  52464. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  52465. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  52466. if (onLoad === void 0) { onLoad = null; }
  52467. if (onError === void 0) { onError = null; }
  52468. var _this = _super.call(this, scene) || this;
  52469. _this._useInGammaSpace = false;
  52470. _this._generateHarmonics = true;
  52471. _this._isBABYLONPreprocessed = false;
  52472. _this._onLoad = null;
  52473. _this._onError = null;
  52474. /**
  52475. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  52476. */
  52477. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  52478. /**
  52479. * The spherical polynomial data extracted from the texture.
  52480. */
  52481. _this.sphericalPolynomial = null;
  52482. /**
  52483. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  52484. * This is usefull at run time to apply the good shader.
  52485. */
  52486. _this.isPMREM = false;
  52487. if (!url) {
  52488. return _this;
  52489. }
  52490. _this.name = url;
  52491. _this.url = url;
  52492. _this.hasAlpha = false;
  52493. _this.isCube = true;
  52494. _this._textureMatrix = BABYLON.Matrix.Identity();
  52495. _this._onLoad = onLoad;
  52496. _this._onError = onError;
  52497. if (size) {
  52498. _this._isBABYLONPreprocessed = false;
  52499. _this._noMipmap = noMipmap;
  52500. _this._size = size;
  52501. _this._useInGammaSpace = useInGammaSpace;
  52502. _this._usePMREMGenerator = usePMREMGenerator &&
  52503. scene.getEngine().getCaps().textureLOD &&
  52504. _this.getScene().getEngine().getCaps().textureFloat &&
  52505. !_this._useInGammaSpace;
  52506. }
  52507. else {
  52508. _this._isBABYLONPreprocessed = true;
  52509. _this._noMipmap = false;
  52510. _this._useInGammaSpace = false;
  52511. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  52512. _this.getScene().getEngine().getCaps().textureFloat &&
  52513. !_this._useInGammaSpace;
  52514. }
  52515. _this.isPMREM = _this._usePMREMGenerator;
  52516. _this._texture = _this._getFromCache(url, _this._noMipmap);
  52517. if (!_this._texture) {
  52518. if (!scene.useDelayedTextureLoading) {
  52519. _this.loadTexture();
  52520. }
  52521. else {
  52522. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52523. }
  52524. }
  52525. return _this;
  52526. }
  52527. /**
  52528. * Occurs when the file is a preprocessed .babylon.hdr file.
  52529. */
  52530. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  52531. var _this = this;
  52532. var mipLevels = 0;
  52533. var floatArrayView = null;
  52534. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  52535. var mips = [];
  52536. var startIndex = 30;
  52537. for (var level = 0; level < mipLevels; level++) {
  52538. mips.push([]);
  52539. // Fill each pixel of the mip level.
  52540. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  52541. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52542. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  52543. mips[level].push(faceData);
  52544. startIndex += faceSize;
  52545. }
  52546. }
  52547. return mips;
  52548. } : null;
  52549. var callback = function (buffer) {
  52550. // Create Native Array Views
  52551. var intArrayView = new Int32Array(buffer);
  52552. floatArrayView = new Float32Array(buffer);
  52553. // Fill header.
  52554. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  52555. _this._size = intArrayView[1]; // CubeMap max mip face size.
  52556. // Update Texture Information.
  52557. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  52558. // Fill polynomial information.
  52559. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  52560. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  52561. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  52562. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  52563. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  52564. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  52565. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  52566. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  52567. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  52568. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  52569. // Fill pixel data.
  52570. mipLevels = intArrayView[29]; // Number of mip levels.
  52571. var startIndex = 30;
  52572. var data = [];
  52573. var faceSize = Math.pow(_this._size, 2) * 3;
  52574. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52575. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  52576. startIndex += faceSize;
  52577. }
  52578. var results = [];
  52579. var byteArray = null;
  52580. // Push each faces.
  52581. for (var k = 0; k < 6; k++) {
  52582. var dataFace = null;
  52583. // If special cases.
  52584. if (!mipmapGenerator) {
  52585. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  52586. dataFace = data[j];
  52587. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52588. // 3 channels of 1 bytes per pixel in bytes.
  52589. var byteBuffer = new ArrayBuffer(faceSize);
  52590. byteArray = new Uint8Array(byteBuffer);
  52591. }
  52592. for (var i = 0; i < _this._size * _this._size; i++) {
  52593. // Put in gamma space if requested.
  52594. if (_this._useInGammaSpace) {
  52595. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52596. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52597. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52598. }
  52599. // Convert to int texture for fallback.
  52600. if (byteArray) {
  52601. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52602. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52603. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52604. // May use luminance instead if the result is not accurate.
  52605. var max = Math.max(Math.max(r, g), b);
  52606. if (max > 255) {
  52607. var scale = 255 / max;
  52608. r *= scale;
  52609. g *= scale;
  52610. b *= scale;
  52611. }
  52612. byteArray[(i * 3) + 0] = r;
  52613. byteArray[(i * 3) + 1] = g;
  52614. byteArray[(i * 3) + 2] = b;
  52615. }
  52616. }
  52617. }
  52618. else {
  52619. dataFace = data[k];
  52620. }
  52621. // Fill the array accordingly.
  52622. if (byteArray) {
  52623. results.push(byteArray);
  52624. }
  52625. else {
  52626. results.push(dataFace);
  52627. }
  52628. }
  52629. return results;
  52630. };
  52631. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  52632. };
  52633. /**
  52634. * Occurs when the file is raw .hdr file.
  52635. */
  52636. HDRCubeTexture.prototype.loadHDRTexture = function () {
  52637. var _this = this;
  52638. var callback = function (buffer) {
  52639. // Extract the raw linear data.
  52640. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  52641. // Generate harmonics if needed.
  52642. if (_this._generateHarmonics) {
  52643. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  52644. }
  52645. var results = [];
  52646. var byteArray = null;
  52647. // Push each faces.
  52648. for (var j = 0; j < 6; j++) {
  52649. // Create uintarray fallback.
  52650. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  52651. // 3 channels of 1 bytes per pixel in bytes.
  52652. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  52653. byteArray = new Uint8Array(byteBuffer);
  52654. }
  52655. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  52656. // If special cases.
  52657. if (_this._useInGammaSpace || byteArray) {
  52658. for (var i = 0; i < _this._size * _this._size; i++) {
  52659. // Put in gamma space if requested.
  52660. if (_this._useInGammaSpace) {
  52661. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  52662. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  52663. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  52664. }
  52665. // Convert to int texture for fallback.
  52666. if (byteArray) {
  52667. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  52668. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  52669. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  52670. // May use luminance instead if the result is not accurate.
  52671. var max = Math.max(Math.max(r, g), b);
  52672. if (max > 255) {
  52673. var scale = 255 / max;
  52674. r *= scale;
  52675. g *= scale;
  52676. b *= scale;
  52677. }
  52678. byteArray[(i * 3) + 0] = r;
  52679. byteArray[(i * 3) + 1] = g;
  52680. byteArray[(i * 3) + 2] = b;
  52681. }
  52682. }
  52683. }
  52684. if (byteArray) {
  52685. results.push(byteArray);
  52686. }
  52687. else {
  52688. results.push(dataFace);
  52689. }
  52690. }
  52691. return results;
  52692. };
  52693. var mipmapGenerator = null;
  52694. if (!this._noMipmap &&
  52695. this._usePMREMGenerator) {
  52696. mipmapGenerator = function (data) {
  52697. // Custom setup of the generator matching with the PBR shader values.
  52698. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  52699. return generator.filterCubeMap();
  52700. };
  52701. }
  52702. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator, this._onLoad, this._onError);
  52703. };
  52704. /**
  52705. * Starts the loading process of the texture.
  52706. */
  52707. HDRCubeTexture.prototype.loadTexture = function () {
  52708. if (this._isBABYLONPreprocessed) {
  52709. this.loadBabylonTexture();
  52710. }
  52711. else {
  52712. this.loadHDRTexture();
  52713. }
  52714. };
  52715. HDRCubeTexture.prototype.clone = function () {
  52716. var size = this._isBABYLONPreprocessed ? null : this._size;
  52717. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  52718. // Base texture
  52719. newTexture.level = this.level;
  52720. newTexture.wrapU = this.wrapU;
  52721. newTexture.wrapV = this.wrapV;
  52722. newTexture.coordinatesIndex = this.coordinatesIndex;
  52723. newTexture.coordinatesMode = this.coordinatesMode;
  52724. return newTexture;
  52725. };
  52726. // Methods
  52727. HDRCubeTexture.prototype.delayLoad = function () {
  52728. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52729. return;
  52730. }
  52731. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52732. this._texture = this._getFromCache(this.url, this._noMipmap);
  52733. if (!this._texture) {
  52734. this.loadTexture();
  52735. }
  52736. };
  52737. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  52738. return this._textureMatrix;
  52739. };
  52740. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52741. var texture = null;
  52742. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52743. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  52744. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  52745. texture.name = parsedTexture.name;
  52746. texture.hasAlpha = parsedTexture.hasAlpha;
  52747. texture.level = parsedTexture.level;
  52748. texture.coordinatesMode = parsedTexture.coordinatesMode;
  52749. }
  52750. return texture;
  52751. };
  52752. HDRCubeTexture.prototype.serialize = function () {
  52753. if (!this.name) {
  52754. return null;
  52755. }
  52756. var serializationObject = {};
  52757. serializationObject.name = this.name;
  52758. serializationObject.hasAlpha = this.hasAlpha;
  52759. serializationObject.isCube = true;
  52760. serializationObject.level = this.level;
  52761. serializationObject.size = this._size;
  52762. serializationObject.coordinatesMode = this.coordinatesMode;
  52763. serializationObject.useInGammaSpace = this._useInGammaSpace;
  52764. serializationObject.generateHarmonics = this._generateHarmonics;
  52765. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  52766. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  52767. serializationObject.customType = "BABYLON.HDRCubeTexture";
  52768. serializationObject.noMipmap = this._noMipmap;
  52769. return serializationObject;
  52770. };
  52771. /**
  52772. * Saves as a file the data contained in the texture in a binary format.
  52773. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52774. * as the spherical used in the lighting.
  52775. * @param url The HDR file url.
  52776. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52777. * @param onError Method called if any error happens during download.
  52778. * @return The packed binary data.
  52779. */
  52780. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  52781. if (onError === void 0) { onError = null; }
  52782. var callback = function (buffer) {
  52783. var data = new Blob([buffer], { type: 'application/octet-stream' });
  52784. // Returns a URL you can use as a href.
  52785. var objUrl = window.URL.createObjectURL(data);
  52786. // Simulates a link to it and click to dowload.
  52787. var a = document.createElement("a");
  52788. document.body.appendChild(a);
  52789. a.style.display = "none";
  52790. a.href = objUrl;
  52791. a.download = "envmap.babylon.hdr";
  52792. a.click();
  52793. };
  52794. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  52795. };
  52796. /**
  52797. * Serializes the data contained in the texture in a binary format.
  52798. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  52799. * as the spherical used in the lighting.
  52800. * @param url The HDR file url.
  52801. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  52802. * @param onError Method called if any error happens during download.
  52803. * @return The packed binary data.
  52804. */
  52805. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  52806. if (onError === void 0) { onError = null; }
  52807. // Needs the url tho create the texture.
  52808. if (!url) {
  52809. return null;
  52810. }
  52811. // Check Power of two size.
  52812. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  52813. return null;
  52814. }
  52815. var getDataCallback = function (dataBuffer) {
  52816. // Extract the raw linear data.
  52817. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  52818. // Generate harmonics if needed.
  52819. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  52820. // Generate seamless faces
  52821. var mipGeneratorArray = [];
  52822. // Data are known to be in +X +Y +Z -X -Y -Z
  52823. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  52824. mipGeneratorArray.push(cubeData.right); // +X
  52825. mipGeneratorArray.push(cubeData.left); // -X
  52826. mipGeneratorArray.push(cubeData.up); // +Y
  52827. mipGeneratorArray.push(cubeData.down); // -Y
  52828. mipGeneratorArray.push(cubeData.front); // +Z
  52829. mipGeneratorArray.push(cubeData.back); // -Z
  52830. // Custom setup of the generator matching with the PBR shader values.
  52831. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  52832. var mippedData = generator.filterCubeMap();
  52833. // Compute required byte length.
  52834. var byteLength = 1 * 4; // Raw Data Version int32.
  52835. byteLength += 4; // CubeMap max mip face size int32.
  52836. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  52837. // Add data size.
  52838. byteLength += 4; // Number of mip levels int32.
  52839. for (var level = 0; level < mippedData.length; level++) {
  52840. var mipSize = size >> level;
  52841. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  52842. }
  52843. // Prepare binary structure.
  52844. var buffer = new ArrayBuffer(byteLength);
  52845. var intArrayView = new Int32Array(buffer);
  52846. var floatArrayView = new Float32Array(buffer);
  52847. // Fill header.
  52848. intArrayView[0] = 1; // Version 1.
  52849. intArrayView[1] = size; // CubeMap max mip face size.
  52850. // Fill polynomial information.
  52851. sphericalPolynomial.x.toArray(floatArrayView, 2);
  52852. sphericalPolynomial.y.toArray(floatArrayView, 5);
  52853. sphericalPolynomial.z.toArray(floatArrayView, 8);
  52854. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  52855. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  52856. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  52857. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  52858. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  52859. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  52860. // Fill pixel data.
  52861. intArrayView[29] = mippedData.length; // Number of mip levels.
  52862. var startIndex = 30;
  52863. for (var level = 0; level < mippedData.length; level++) {
  52864. // Fill each pixel of the mip level.
  52865. var faceSize = Math.pow(size >> level, 2) * 3;
  52866. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52867. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  52868. startIndex += faceSize;
  52869. }
  52870. }
  52871. // Callback.
  52872. callback(buffer);
  52873. };
  52874. // Download and process.
  52875. BABYLON.Tools.LoadFile(url, function (data) {
  52876. getDataCallback(data);
  52877. }, null, null, true, onError);
  52878. };
  52879. return HDRCubeTexture;
  52880. }(BABYLON.BaseTexture));
  52881. HDRCubeTexture._facesMapping = [
  52882. "right",
  52883. "up",
  52884. "front",
  52885. "left",
  52886. "down",
  52887. "back"
  52888. ];
  52889. BABYLON.HDRCubeTexture = HDRCubeTexture;
  52890. })(BABYLON || (BABYLON = {}));
  52891. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  52892. var BABYLON;
  52893. (function (BABYLON) {
  52894. var Debug;
  52895. (function (Debug) {
  52896. /**
  52897. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  52898. */
  52899. var SkeletonViewer = (function () {
  52900. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  52901. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  52902. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  52903. this.skeleton = skeleton;
  52904. this.mesh = mesh;
  52905. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  52906. this.renderingGroupId = renderingGroupId;
  52907. this.color = BABYLON.Color3.White();
  52908. this._debugLines = [];
  52909. this._isEnabled = false;
  52910. this._scene = scene;
  52911. this.update();
  52912. this._renderFunction = this.update.bind(this);
  52913. }
  52914. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  52915. get: function () {
  52916. return this._isEnabled;
  52917. },
  52918. set: function (value) {
  52919. if (this._isEnabled === value) {
  52920. return;
  52921. }
  52922. this._isEnabled = value;
  52923. if (value) {
  52924. this._scene.registerBeforeRender(this._renderFunction);
  52925. }
  52926. else {
  52927. this._scene.unregisterBeforeRender(this._renderFunction);
  52928. }
  52929. },
  52930. enumerable: true,
  52931. configurable: true
  52932. });
  52933. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  52934. if (x === void 0) { x = 0; }
  52935. if (y === void 0) { y = 0; }
  52936. if (z === void 0) { z = 0; }
  52937. var tmat = BABYLON.Tmp.Matrix[0];
  52938. var parentBone = bone.getParent();
  52939. tmat.copyFrom(bone.getLocalMatrix());
  52940. if (x !== 0 || y !== 0 || z !== 0) {
  52941. var tmat2 = BABYLON.Tmp.Matrix[1];
  52942. BABYLON.Matrix.IdentityToRef(tmat2);
  52943. tmat2.m[12] = x;
  52944. tmat2.m[13] = y;
  52945. tmat2.m[14] = z;
  52946. tmat2.multiplyToRef(tmat, tmat);
  52947. }
  52948. if (parentBone) {
  52949. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  52950. }
  52951. tmat.multiplyToRef(meshMat, tmat);
  52952. position.x = tmat.m[12];
  52953. position.y = tmat.m[13];
  52954. position.z = tmat.m[14];
  52955. };
  52956. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  52957. var len = bones.length;
  52958. for (var i = 0; i < len; i++) {
  52959. var bone = bones[i];
  52960. var points = this._debugLines[i];
  52961. if (!points) {
  52962. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52963. this._debugLines[i] = points;
  52964. }
  52965. this._getBonePosition(points[0], bone, meshMat);
  52966. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  52967. }
  52968. };
  52969. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  52970. var len = bones.length;
  52971. var boneNum = 0;
  52972. for (var i = len - 1; i >= 0; i--) {
  52973. var childBone = bones[i];
  52974. var parentBone = childBone.getParent();
  52975. if (!parentBone) {
  52976. continue;
  52977. }
  52978. var points = this._debugLines[boneNum];
  52979. if (!points) {
  52980. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52981. this._debugLines[boneNum] = points;
  52982. }
  52983. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  52984. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  52985. boneNum++;
  52986. }
  52987. };
  52988. SkeletonViewer.prototype.update = function () {
  52989. if (this.autoUpdateBonesMatrices) {
  52990. this.skeleton.computeAbsoluteTransforms();
  52991. }
  52992. if (this.skeleton.bones[0].length === undefined) {
  52993. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52994. }
  52995. else {
  52996. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52997. }
  52998. if (!this._debugMesh) {
  52999. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  53000. this._debugMesh.renderingGroupId = this.renderingGroupId;
  53001. }
  53002. else {
  53003. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  53004. }
  53005. this._debugMesh.color = this.color;
  53006. };
  53007. SkeletonViewer.prototype.dispose = function () {
  53008. if (this._debugMesh) {
  53009. this.isEnabled = false;
  53010. this._debugMesh.dispose();
  53011. this._debugMesh = null;
  53012. }
  53013. };
  53014. return SkeletonViewer;
  53015. }());
  53016. Debug.SkeletonViewer = SkeletonViewer;
  53017. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  53018. })(BABYLON || (BABYLON = {}));
  53019. //# sourceMappingURL=babylon.skeletonViewer.js.map
  53020. var BABYLON;
  53021. (function (BABYLON) {
  53022. var Debug;
  53023. (function (Debug) {
  53024. var AxesViewer = (function () {
  53025. function AxesViewer(scene, scaleLines) {
  53026. if (scaleLines === void 0) { scaleLines = 1; }
  53027. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  53028. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  53029. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  53030. this.scaleLines = 1;
  53031. this.scaleLines = scaleLines;
  53032. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  53033. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  53034. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  53035. this._xmesh.renderingGroupId = 2;
  53036. this._ymesh.renderingGroupId = 2;
  53037. this._zmesh.renderingGroupId = 2;
  53038. this._xmesh.material.checkReadyOnlyOnce = true;
  53039. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  53040. this._ymesh.material.checkReadyOnlyOnce = true;
  53041. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  53042. this._zmesh.material.checkReadyOnlyOnce = true;
  53043. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  53044. this.scene = scene;
  53045. }
  53046. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  53047. var scaleLines = this.scaleLines;
  53048. var point1 = this._xline[0];
  53049. var point2 = this._xline[1];
  53050. point1.x = position.x;
  53051. point1.y = position.y;
  53052. point1.z = position.z;
  53053. point2.x = point1.x + xaxis.x * scaleLines;
  53054. point2.y = point1.y + xaxis.y * scaleLines;
  53055. point2.z = point1.z + xaxis.z * scaleLines;
  53056. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  53057. point1 = this._yline[0];
  53058. point2 = this._yline[1];
  53059. point1.x = position.x;
  53060. point1.y = position.y;
  53061. point1.z = position.z;
  53062. point2.x = point1.x + yaxis.x * scaleLines;
  53063. point2.y = point1.y + yaxis.y * scaleLines;
  53064. point2.z = point1.z + yaxis.z * scaleLines;
  53065. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  53066. point1 = this._zline[0];
  53067. point2 = this._zline[1];
  53068. point1.x = position.x;
  53069. point1.y = position.y;
  53070. point1.z = position.z;
  53071. point2.x = point1.x + zaxis.x * scaleLines;
  53072. point2.y = point1.y + zaxis.y * scaleLines;
  53073. point2.z = point1.z + zaxis.z * scaleLines;
  53074. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  53075. };
  53076. AxesViewer.prototype.dispose = function () {
  53077. if (this._xmesh) {
  53078. this._xmesh.dispose();
  53079. this._ymesh.dispose();
  53080. this._zmesh.dispose();
  53081. this._xmesh = null;
  53082. this._ymesh = null;
  53083. this._zmesh = null;
  53084. this._xline = null;
  53085. this._yline = null;
  53086. this._zline = null;
  53087. this.scene = null;
  53088. }
  53089. };
  53090. return AxesViewer;
  53091. }());
  53092. Debug.AxesViewer = AxesViewer;
  53093. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  53094. })(BABYLON || (BABYLON = {}));
  53095. //# sourceMappingURL=babylon.axesViewer.js.map
  53096. var BABYLON;
  53097. (function (BABYLON) {
  53098. var Debug;
  53099. (function (Debug) {
  53100. var BoneAxesViewer = (function (_super) {
  53101. __extends(BoneAxesViewer, _super);
  53102. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  53103. if (scaleLines === void 0) { scaleLines = 1; }
  53104. var _this = _super.call(this, scene, scaleLines) || this;
  53105. _this.pos = BABYLON.Vector3.Zero();
  53106. _this.xaxis = BABYLON.Vector3.Zero();
  53107. _this.yaxis = BABYLON.Vector3.Zero();
  53108. _this.zaxis = BABYLON.Vector3.Zero();
  53109. _this.mesh = mesh;
  53110. _this.bone = bone;
  53111. return _this;
  53112. }
  53113. BoneAxesViewer.prototype.update = function () {
  53114. var bone = this.bone;
  53115. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  53116. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  53117. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  53118. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  53119. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  53120. };
  53121. BoneAxesViewer.prototype.dispose = function () {
  53122. if (this.pos) {
  53123. this.pos = null;
  53124. this.xaxis = null;
  53125. this.yaxis = null;
  53126. this.zaxis = null;
  53127. this.mesh = null;
  53128. this.bone = null;
  53129. _super.prototype.dispose.call(this);
  53130. }
  53131. };
  53132. return BoneAxesViewer;
  53133. }(Debug.AxesViewer));
  53134. Debug.BoneAxesViewer = BoneAxesViewer;
  53135. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  53136. })(BABYLON || (BABYLON = {}));
  53137. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  53138. var BABYLON;
  53139. (function (BABYLON) {
  53140. /**
  53141. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  53142. * It can help converting any input color in a desired output one. This can then be used to create effects
  53143. * from sepia, black and white to sixties or futuristic rendering...
  53144. *
  53145. * The only supported format is currently 3dl.
  53146. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  53147. */
  53148. var ColorGradingTexture = (function (_super) {
  53149. __extends(ColorGradingTexture, _super);
  53150. /**
  53151. * Instantiates a ColorGradingTexture from the following parameters.
  53152. *
  53153. * @param url The location of the color gradind data (currently only supporting 3dl)
  53154. * @param scene The scene the texture will be used in
  53155. */
  53156. function ColorGradingTexture(url, scene) {
  53157. var _this = _super.call(this, scene) || this;
  53158. if (!url) {
  53159. return _this;
  53160. }
  53161. _this._textureMatrix = BABYLON.Matrix.Identity();
  53162. _this.name = url;
  53163. _this.url = url;
  53164. _this.hasAlpha = false;
  53165. _this.isCube = false;
  53166. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53167. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53168. _this.anisotropicFilteringLevel = 1;
  53169. _this._texture = _this._getFromCache(url, true);
  53170. if (!_this._texture) {
  53171. if (!scene.useDelayedTextureLoading) {
  53172. _this.loadTexture();
  53173. }
  53174. else {
  53175. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  53176. }
  53177. }
  53178. return _this;
  53179. }
  53180. /**
  53181. * Returns the texture matrix used in most of the material.
  53182. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  53183. */
  53184. ColorGradingTexture.prototype.getTextureMatrix = function () {
  53185. return this._textureMatrix;
  53186. };
  53187. /**
  53188. * Occurs when the file being loaded is a .3dl LUT file.
  53189. */
  53190. ColorGradingTexture.prototype.load3dlTexture = function () {
  53191. var _this = this;
  53192. var mipLevels = 0;
  53193. var floatArrayView = null;
  53194. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  53195. this._texture = texture;
  53196. var callback = function (text) {
  53197. var data;
  53198. var tempData;
  53199. var line;
  53200. var lines = text.split('\n');
  53201. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  53202. var maxColor = 0;
  53203. for (var i = 0; i < lines.length; i++) {
  53204. line = lines[i];
  53205. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  53206. continue;
  53207. if (line.indexOf('#') === 0)
  53208. continue;
  53209. var words = line.split(" ");
  53210. if (size === 0) {
  53211. // Number of space + one
  53212. size = words.length;
  53213. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  53214. tempData = new Float32Array(size * size * size * 4);
  53215. continue;
  53216. }
  53217. if (size != 0) {
  53218. var r = Math.max(parseInt(words[0]), 0);
  53219. var g = Math.max(parseInt(words[1]), 0);
  53220. var b = Math.max(parseInt(words[2]), 0);
  53221. maxColor = Math.max(r, maxColor);
  53222. maxColor = Math.max(g, maxColor);
  53223. maxColor = Math.max(b, maxColor);
  53224. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  53225. tempData[pixelStorageIndex + 0] = r;
  53226. tempData[pixelStorageIndex + 1] = g;
  53227. tempData[pixelStorageIndex + 2] = b;
  53228. tempData[pixelStorageIndex + 3] = 0;
  53229. pixelIndexSlice++;
  53230. if (pixelIndexSlice % size == 0) {
  53231. pixelIndexH++;
  53232. pixelIndexSlice = 0;
  53233. if (pixelIndexH % size == 0) {
  53234. pixelIndexW++;
  53235. pixelIndexH = 0;
  53236. }
  53237. }
  53238. }
  53239. }
  53240. for (var i = 0; i < tempData.length; i++) {
  53241. var value = tempData[i];
  53242. data[i] = (value / maxColor * 255);
  53243. }
  53244. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  53245. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  53246. };
  53247. BABYLON.Tools.LoadFile(this.url, callback);
  53248. return this._texture;
  53249. };
  53250. /**
  53251. * Starts the loading process of the texture.
  53252. */
  53253. ColorGradingTexture.prototype.loadTexture = function () {
  53254. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  53255. this.load3dlTexture();
  53256. }
  53257. };
  53258. /**
  53259. * Clones the color gradind texture.
  53260. */
  53261. ColorGradingTexture.prototype.clone = function () {
  53262. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  53263. // Base texture
  53264. newTexture.level = this.level;
  53265. return newTexture;
  53266. };
  53267. /**
  53268. * Called during delayed load for textures.
  53269. */
  53270. ColorGradingTexture.prototype.delayLoad = function () {
  53271. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  53272. return;
  53273. }
  53274. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  53275. this._texture = this._getFromCache(this.url, true);
  53276. if (!this._texture) {
  53277. this.loadTexture();
  53278. }
  53279. };
  53280. /**
  53281. * Binds the color grading to the shader.
  53282. * @param colorGrading The texture to bind
  53283. * @param effect The effect to bind to
  53284. */
  53285. ColorGradingTexture.Bind = function (colorGrading, effect) {
  53286. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  53287. var x = colorGrading.level; // Texture Level
  53288. var y = colorGrading.getSize().height; // Texture Size example with 8
  53289. var z = y - 1.0; // SizeMinusOne 8 - 1
  53290. var w = 1 / y; // Space of 1 slice 1 / 8
  53291. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  53292. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  53293. 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
  53294. 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
  53295. 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
  53296. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  53297. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  53298. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  53299. };
  53300. /**
  53301. * Prepare the list of uniforms associated with the ColorGrading effects.
  53302. * @param uniformsList The list of uniforms used in the effect
  53303. * @param samplersList The list of samplers used in the effect
  53304. */
  53305. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  53306. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  53307. samplersList.push("cameraColorGrading2DSampler");
  53308. };
  53309. /**
  53310. * Parses a color grading texture serialized by Babylon.
  53311. * @param parsedTexture The texture information being parsedTexture
  53312. * @param scene The scene to load the texture in
  53313. * @param rootUrl The root url of the data assets to load
  53314. * @return A color gradind texture
  53315. */
  53316. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  53317. var texture = null;
  53318. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  53319. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  53320. texture.name = parsedTexture.name;
  53321. texture.level = parsedTexture.level;
  53322. }
  53323. return texture;
  53324. };
  53325. /**
  53326. * Serializes the LUT texture to json format.
  53327. */
  53328. ColorGradingTexture.prototype.serialize = function () {
  53329. if (!this.name) {
  53330. return null;
  53331. }
  53332. var serializationObject = {};
  53333. serializationObject.name = this.name;
  53334. serializationObject.level = this.level;
  53335. serializationObject.customType = "BABYLON.ColorGradingTexture";
  53336. return serializationObject;
  53337. };
  53338. return ColorGradingTexture;
  53339. }(BABYLON.BaseTexture));
  53340. /**
  53341. * Empty line regex stored for GC.
  53342. */
  53343. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  53344. BABYLON.ColorGradingTexture = ColorGradingTexture;
  53345. })(BABYLON || (BABYLON = {}));
  53346. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  53347. var BABYLON;
  53348. (function (BABYLON) {
  53349. /**
  53350. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  53351. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  53352. * 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;
  53353. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  53354. */
  53355. var ColorCurves = (function () {
  53356. function ColorCurves() {
  53357. this._dirty = true;
  53358. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  53359. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  53360. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  53361. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  53362. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  53363. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  53364. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  53365. this._globalHue = 30;
  53366. this._globalDensity = 0;
  53367. this._globalSaturation = 0;
  53368. this._globalExposure = 0;
  53369. this._highlightsHue = 30;
  53370. this._highlightsDensity = 0;
  53371. this._highlightsSaturation = 0;
  53372. this._highlightsExposure = 0;
  53373. this._midtonesHue = 30;
  53374. this._midtonesDensity = 0;
  53375. this._midtonesSaturation = 0;
  53376. this._midtonesExposure = 0;
  53377. this._shadowsHue = 30;
  53378. this._shadowsDensity = 0;
  53379. this._shadowsSaturation = 0;
  53380. this._shadowsExposure = 0;
  53381. }
  53382. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  53383. /**
  53384. * Gets the global Hue value.
  53385. * 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).
  53386. */
  53387. get: function () {
  53388. return this._globalHue;
  53389. },
  53390. /**
  53391. * Sets the global Hue value.
  53392. * 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).
  53393. */
  53394. set: function (value) {
  53395. this._globalHue = value;
  53396. this._dirty = true;
  53397. },
  53398. enumerable: true,
  53399. configurable: true
  53400. });
  53401. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  53402. /**
  53403. * Gets the global Density value.
  53404. * 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.
  53405. * Values less than zero provide a filter of opposite hue.
  53406. */
  53407. get: function () {
  53408. return this._globalDensity;
  53409. },
  53410. /**
  53411. * Sets the global Density value.
  53412. * 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.
  53413. * Values less than zero provide a filter of opposite hue.
  53414. */
  53415. set: function (value) {
  53416. this._globalDensity = value;
  53417. this._dirty = true;
  53418. },
  53419. enumerable: true,
  53420. configurable: true
  53421. });
  53422. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  53423. /**
  53424. * Gets the global Saturation value.
  53425. * 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.
  53426. */
  53427. get: function () {
  53428. return this._globalSaturation;
  53429. },
  53430. /**
  53431. * Sets the global Saturation value.
  53432. * 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.
  53433. */
  53434. set: function (value) {
  53435. this._globalSaturation = value;
  53436. this._dirty = true;
  53437. },
  53438. enumerable: true,
  53439. configurable: true
  53440. });
  53441. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  53442. /**
  53443. * Gets the highlights Hue value.
  53444. * 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).
  53445. */
  53446. get: function () {
  53447. return this._highlightsHue;
  53448. },
  53449. /**
  53450. * Sets the highlights Hue value.
  53451. * 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).
  53452. */
  53453. set: function (value) {
  53454. this._highlightsHue = value;
  53455. this._dirty = true;
  53456. },
  53457. enumerable: true,
  53458. configurable: true
  53459. });
  53460. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  53461. /**
  53462. * Gets the highlights Density value.
  53463. * 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.
  53464. * Values less than zero provide a filter of opposite hue.
  53465. */
  53466. get: function () {
  53467. return this._highlightsDensity;
  53468. },
  53469. /**
  53470. * Sets the highlights Density value.
  53471. * 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.
  53472. * Values less than zero provide a filter of opposite hue.
  53473. */
  53474. set: function (value) {
  53475. this._highlightsDensity = value;
  53476. this._dirty = true;
  53477. },
  53478. enumerable: true,
  53479. configurable: true
  53480. });
  53481. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  53482. /**
  53483. * Gets the highlights Saturation value.
  53484. * 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.
  53485. */
  53486. get: function () {
  53487. return this._highlightsSaturation;
  53488. },
  53489. /**
  53490. * Sets the highlights Saturation value.
  53491. * 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.
  53492. */
  53493. set: function (value) {
  53494. this._highlightsSaturation = value;
  53495. this._dirty = true;
  53496. },
  53497. enumerable: true,
  53498. configurable: true
  53499. });
  53500. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  53501. /**
  53502. * Gets the highlights Exposure value.
  53503. * 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.
  53504. */
  53505. get: function () {
  53506. return this._highlightsExposure;
  53507. },
  53508. /**
  53509. * Sets the highlights Exposure value.
  53510. * 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.
  53511. */
  53512. set: function (value) {
  53513. this._highlightsExposure = value;
  53514. this._dirty = true;
  53515. },
  53516. enumerable: true,
  53517. configurable: true
  53518. });
  53519. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  53520. /**
  53521. * Gets the midtones Hue value.
  53522. * 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).
  53523. */
  53524. get: function () {
  53525. return this._midtonesHue;
  53526. },
  53527. /**
  53528. * Sets the midtones Hue value.
  53529. * 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).
  53530. */
  53531. set: function (value) {
  53532. this._midtonesHue = value;
  53533. this._dirty = true;
  53534. },
  53535. enumerable: true,
  53536. configurable: true
  53537. });
  53538. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  53539. /**
  53540. * Gets the midtones Density value.
  53541. * 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.
  53542. * Values less than zero provide a filter of opposite hue.
  53543. */
  53544. get: function () {
  53545. return this._midtonesDensity;
  53546. },
  53547. /**
  53548. * Sets the midtones Density value.
  53549. * 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.
  53550. * Values less than zero provide a filter of opposite hue.
  53551. */
  53552. set: function (value) {
  53553. this._midtonesDensity = value;
  53554. this._dirty = true;
  53555. },
  53556. enumerable: true,
  53557. configurable: true
  53558. });
  53559. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  53560. /**
  53561. * Gets the midtones Saturation value.
  53562. * 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.
  53563. */
  53564. get: function () {
  53565. return this._midtonesSaturation;
  53566. },
  53567. /**
  53568. * Sets the midtones Saturation value.
  53569. * 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.
  53570. */
  53571. set: function (value) {
  53572. this._midtonesSaturation = value;
  53573. this._dirty = true;
  53574. },
  53575. enumerable: true,
  53576. configurable: true
  53577. });
  53578. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  53579. /**
  53580. * Gets the midtones Exposure value.
  53581. * 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.
  53582. */
  53583. get: function () {
  53584. return this._midtonesExposure;
  53585. },
  53586. /**
  53587. * Sets the midtones Exposure value.
  53588. * 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.
  53589. */
  53590. set: function (value) {
  53591. this._midtonesExposure = value;
  53592. this._dirty = true;
  53593. },
  53594. enumerable: true,
  53595. configurable: true
  53596. });
  53597. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  53598. /**
  53599. * Gets the shadows Hue value.
  53600. * 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).
  53601. */
  53602. get: function () {
  53603. return this._shadowsHue;
  53604. },
  53605. /**
  53606. * Sets the shadows Hue value.
  53607. * 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).
  53608. */
  53609. set: function (value) {
  53610. this._shadowsHue = value;
  53611. this._dirty = true;
  53612. },
  53613. enumerable: true,
  53614. configurable: true
  53615. });
  53616. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  53617. /**
  53618. * Gets the shadows Density value.
  53619. * 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.
  53620. * Values less than zero provide a filter of opposite hue.
  53621. */
  53622. get: function () {
  53623. return this._shadowsDensity;
  53624. },
  53625. /**
  53626. * Sets the shadows Density value.
  53627. * 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.
  53628. * Values less than zero provide a filter of opposite hue.
  53629. */
  53630. set: function (value) {
  53631. this._shadowsDensity = value;
  53632. this._dirty = true;
  53633. },
  53634. enumerable: true,
  53635. configurable: true
  53636. });
  53637. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  53638. /**
  53639. * Gets the shadows Saturation value.
  53640. * 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.
  53641. */
  53642. get: function () {
  53643. return this._shadowsSaturation;
  53644. },
  53645. /**
  53646. * Sets the shadows Saturation value.
  53647. * 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.
  53648. */
  53649. set: function (value) {
  53650. this._shadowsSaturation = value;
  53651. this._dirty = true;
  53652. },
  53653. enumerable: true,
  53654. configurable: true
  53655. });
  53656. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  53657. /**
  53658. * Gets the shadows Exposure value.
  53659. * 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.
  53660. */
  53661. get: function () {
  53662. return this._shadowsExposure;
  53663. },
  53664. /**
  53665. * Sets the shadows Exposure value.
  53666. * 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.
  53667. */
  53668. set: function (value) {
  53669. this._shadowsExposure = value;
  53670. this._dirty = true;
  53671. },
  53672. enumerable: true,
  53673. configurable: true
  53674. });
  53675. /**
  53676. * Binds the color curves to the shader.
  53677. * @param colorCurves The color curve to bind
  53678. * @param effect The effect to bind to
  53679. */
  53680. ColorCurves.Bind = function (colorCurves, effect) {
  53681. if (colorCurves._dirty) {
  53682. colorCurves._dirty = false;
  53683. // Fill in global info.
  53684. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  53685. // Compute highlights info.
  53686. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  53687. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  53688. // Compute midtones info.
  53689. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  53690. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  53691. // Compute shadows info.
  53692. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  53693. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  53694. // Compute deltas (neutral is midtones).
  53695. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  53696. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  53697. }
  53698. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  53699. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  53700. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  53701. };
  53702. /**
  53703. * Prepare the list of uniforms associated with the ColorCurves effects.
  53704. * @param uniformsList The list of uniforms used in the effect
  53705. */
  53706. ColorCurves.PrepareUniforms = function (uniformsList) {
  53707. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  53708. };
  53709. /**
  53710. * Returns color grading data based on a hue, density, saturation and exposure value.
  53711. * @param filterHue The hue of the color filter.
  53712. * @param filterDensity The density of the color filter.
  53713. * @param saturation The saturation.
  53714. * @param exposure The exposure.
  53715. * @param result The result data container.
  53716. */
  53717. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  53718. if (hue == null) {
  53719. return;
  53720. }
  53721. hue = ColorCurves.clamp(hue, 0, 360);
  53722. density = ColorCurves.clamp(density, -100, 100);
  53723. saturation = ColorCurves.clamp(saturation, -100, 100);
  53724. exposure = ColorCurves.clamp(exposure, -100, 100);
  53725. // Remap the slider/config filter density with non-linear mapping and also scale by half
  53726. // so that the maximum filter density is only 50% control. This provides fine control
  53727. // for small values and reasonable range.
  53728. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  53729. density *= 0.5;
  53730. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  53731. if (density < 0) {
  53732. density *= -1;
  53733. hue = (hue + 180) % 360;
  53734. }
  53735. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  53736. result.scaleToRef(2, result);
  53737. result.a = 1 + 0.01 * saturation;
  53738. };
  53739. /**
  53740. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  53741. * @param value The input slider value in range [-100,100].
  53742. * @returns Adjusted value.
  53743. */
  53744. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  53745. value /= 100;
  53746. var x = Math.abs(value);
  53747. x = Math.pow(x, 2);
  53748. if (value < 0) {
  53749. x *= -1;
  53750. }
  53751. x *= 100;
  53752. return x;
  53753. };
  53754. /**
  53755. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  53756. * @param hue The hue (H) input.
  53757. * @param saturation The saturation (S) input.
  53758. * @param brightness The brightness (B) input.
  53759. * @result An RGBA color represented as Vector4.
  53760. */
  53761. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  53762. var h = ColorCurves.clamp(hue, 0, 360);
  53763. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  53764. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  53765. if (s === 0) {
  53766. result.r = v;
  53767. result.g = v;
  53768. result.b = v;
  53769. }
  53770. else {
  53771. // sector 0 to 5
  53772. h /= 60;
  53773. var i = Math.floor(h);
  53774. // fractional part of h
  53775. var f = h - i;
  53776. var p = v * (1 - s);
  53777. var q = v * (1 - s * f);
  53778. var t = v * (1 - s * (1 - f));
  53779. switch (i) {
  53780. case 0:
  53781. result.r = v;
  53782. result.g = t;
  53783. result.b = p;
  53784. break;
  53785. case 1:
  53786. result.r = q;
  53787. result.g = v;
  53788. result.b = p;
  53789. break;
  53790. case 2:
  53791. result.r = p;
  53792. result.g = v;
  53793. result.b = t;
  53794. break;
  53795. case 3:
  53796. result.r = p;
  53797. result.g = q;
  53798. result.b = v;
  53799. break;
  53800. case 4:
  53801. result.r = t;
  53802. result.g = p;
  53803. result.b = v;
  53804. break;
  53805. default:
  53806. result.r = v;
  53807. result.g = p;
  53808. result.b = q;
  53809. break;
  53810. }
  53811. }
  53812. result.a = 1;
  53813. };
  53814. /**
  53815. * Returns a value clamped between min and max
  53816. * @param value The value to clamp
  53817. * @param min The minimum of value
  53818. * @param max The maximum of value
  53819. * @returns The clamped value.
  53820. */
  53821. ColorCurves.clamp = function (value, min, max) {
  53822. return Math.min(Math.max(value, min), max);
  53823. };
  53824. /**
  53825. * Clones the current color curve instance.
  53826. * @return The cloned curves
  53827. */
  53828. ColorCurves.prototype.clone = function () {
  53829. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  53830. };
  53831. /**
  53832. * Serializes the current color curve instance to a json representation.
  53833. * @return a JSON representation
  53834. */
  53835. ColorCurves.prototype.serialize = function () {
  53836. return BABYLON.SerializationHelper.Serialize(this);
  53837. };
  53838. /**
  53839. * Parses the color curve from a json representation.
  53840. * @param source the JSON source to parse
  53841. * @return The parsed curves
  53842. */
  53843. ColorCurves.Parse = function (source) {
  53844. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  53845. };
  53846. return ColorCurves;
  53847. }());
  53848. __decorate([
  53849. BABYLON.serialize()
  53850. ], ColorCurves.prototype, "_globalHue", void 0);
  53851. __decorate([
  53852. BABYLON.serialize()
  53853. ], ColorCurves.prototype, "_globalDensity", void 0);
  53854. __decorate([
  53855. BABYLON.serialize()
  53856. ], ColorCurves.prototype, "_globalSaturation", void 0);
  53857. __decorate([
  53858. BABYLON.serialize()
  53859. ], ColorCurves.prototype, "_globalExposure", void 0);
  53860. __decorate([
  53861. BABYLON.serialize()
  53862. ], ColorCurves.prototype, "_highlightsHue", void 0);
  53863. __decorate([
  53864. BABYLON.serialize()
  53865. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  53866. __decorate([
  53867. BABYLON.serialize()
  53868. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  53869. __decorate([
  53870. BABYLON.serialize()
  53871. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  53872. __decorate([
  53873. BABYLON.serialize()
  53874. ], ColorCurves.prototype, "_midtonesHue", void 0);
  53875. __decorate([
  53876. BABYLON.serialize()
  53877. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  53878. __decorate([
  53879. BABYLON.serialize()
  53880. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  53881. __decorate([
  53882. BABYLON.serialize()
  53883. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  53884. BABYLON.ColorCurves = ColorCurves;
  53885. })(BABYLON || (BABYLON = {}));
  53886. //# sourceMappingURL=babylon.colorCurves.js.map
  53887. var BABYLON;
  53888. (function (BABYLON) {
  53889. var PBRMaterialDefines = (function (_super) {
  53890. __extends(PBRMaterialDefines, _super);
  53891. function PBRMaterialDefines() {
  53892. var _this = _super.call(this) || this;
  53893. _this.ALBEDO = false;
  53894. _this.AMBIENT = false;
  53895. _this.OPACITY = false;
  53896. _this.OPACITYRGB = false;
  53897. _this.REFLECTION = false;
  53898. _this.EMISSIVE = false;
  53899. _this.REFLECTIVITY = false;
  53900. _this.BUMP = false;
  53901. _this.PARALLAX = false;
  53902. _this.PARALLAXOCCLUSION = false;
  53903. _this.SPECULAROVERALPHA = false;
  53904. _this.CLIPPLANE = false;
  53905. _this.ALPHATEST = false;
  53906. _this.ALPHAFROMALBEDO = false;
  53907. _this.POINTSIZE = false;
  53908. _this.FOG = false;
  53909. _this.SPECULARTERM = false;
  53910. _this.OPACITYFRESNEL = false;
  53911. _this.EMISSIVEFRESNEL = false;
  53912. _this.FRESNEL = false;
  53913. _this.NORMAL = false;
  53914. _this.UV1 = false;
  53915. _this.UV2 = false;
  53916. _this.VERTEXCOLOR = false;
  53917. _this.VERTEXALPHA = false;
  53918. _this.NUM_BONE_INFLUENCERS = 0;
  53919. _this.BonesPerMesh = 0;
  53920. _this.INSTANCES = false;
  53921. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  53922. _this.MICROSURFACEAUTOMATIC = false;
  53923. _this.EMISSIVEASILLUMINATION = false;
  53924. _this.LINKEMISSIVEWITHALBEDO = false;
  53925. _this.LIGHTMAP = false;
  53926. _this.USELIGHTMAPASSHADOWMAP = false;
  53927. _this.REFLECTIONMAP_3D = false;
  53928. _this.REFLECTIONMAP_SPHERICAL = false;
  53929. _this.REFLECTIONMAP_PLANAR = false;
  53930. _this.REFLECTIONMAP_CUBIC = false;
  53931. _this.REFLECTIONMAP_PROJECTION = false;
  53932. _this.REFLECTIONMAP_SKYBOX = false;
  53933. _this.REFLECTIONMAP_EXPLICIT = false;
  53934. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  53935. _this.INVERTCUBICMAP = false;
  53936. _this.LOGARITHMICDEPTH = false;
  53937. _this.CAMERATONEMAP = false;
  53938. _this.CAMERACONTRAST = false;
  53939. _this.CAMERACOLORGRADING = false;
  53940. _this.CAMERACOLORCURVES = false;
  53941. _this.OVERLOADEDVALUES = false;
  53942. _this.OVERLOADEDSHADOWVALUES = false;
  53943. _this.USESPHERICALFROMREFLECTIONMAP = false;
  53944. _this.REFRACTION = false;
  53945. _this.REFRACTIONMAP_3D = false;
  53946. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  53947. _this.REFRACTIONMAPINLINEARSPACE = false;
  53948. _this.LODBASEDMICROSFURACE = false;
  53949. _this.USEPHYSICALLIGHTFALLOFF = false;
  53950. _this.RADIANCEOVERALPHA = false;
  53951. _this.USEPMREMREFLECTION = false;
  53952. _this.USEPMREMREFRACTION = false;
  53953. _this.OPENGLNORMALMAP = false;
  53954. _this.INVERTNORMALMAPX = false;
  53955. _this.INVERTNORMALMAPY = false;
  53956. _this.SHADOWFULLFLOAT = false;
  53957. _this.METALLICWORKFLOW = false;
  53958. _this.METALLICROUGHNESSMAP = false;
  53959. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  53960. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  53961. _this.rebuild();
  53962. return _this;
  53963. }
  53964. return PBRMaterialDefines;
  53965. }(BABYLON.MaterialDefines));
  53966. /**
  53967. * The Physically based material of BJS.
  53968. *
  53969. * This offers the main features of a standard PBR material.
  53970. * For more information, please refer to the documentation :
  53971. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  53972. */
  53973. var PBRMaterial = (function (_super) {
  53974. __extends(PBRMaterial, _super);
  53975. /**
  53976. * Instantiates a new PBRMaterial instance.
  53977. *
  53978. * @param name The material name
  53979. * @param scene The scene the material will be use in.
  53980. */
  53981. function PBRMaterial(name, scene) {
  53982. var _this = _super.call(this, name, scene) || this;
  53983. /**
  53984. * Intensity of the direct lights e.g. the four lights available in your scene.
  53985. * This impacts both the direct diffuse and specular highlights.
  53986. */
  53987. _this.directIntensity = 1.0;
  53988. /**
  53989. * Intensity of the emissive part of the material.
  53990. * This helps controlling the emissive effect without modifying the emissive color.
  53991. */
  53992. _this.emissiveIntensity = 1.0;
  53993. /**
  53994. * Intensity of the environment e.g. how much the environment will light the object
  53995. * either through harmonics for rough material or through the refelction for shiny ones.
  53996. */
  53997. _this.environmentIntensity = 1.0;
  53998. /**
  53999. * This is a special control allowing the reduction of the specular highlights coming from the
  54000. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  54001. */
  54002. _this.specularIntensity = 1.0;
  54003. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  54004. /**
  54005. * Debug Control allowing disabling the bump map on this material.
  54006. */
  54007. _this.disableBumpMap = false;
  54008. /**
  54009. * Debug Control helping enforcing or dropping the darkness of shadows.
  54010. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  54011. */
  54012. _this.overloadedShadowIntensity = 1.0;
  54013. /**
  54014. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  54015. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  54016. */
  54017. _this.overloadedShadeIntensity = 1.0;
  54018. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  54019. /**
  54020. * The camera exposure used on this material.
  54021. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  54022. * This corresponds to a photographic exposure.
  54023. */
  54024. _this.cameraExposure = 1.0;
  54025. /**
  54026. * The camera contrast used on this material.
  54027. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  54028. */
  54029. _this.cameraContrast = 1.0;
  54030. /**
  54031. * Color Grading 2D Lookup Texture.
  54032. * This allows special effects like sepia, black and white to sixties rendering style.
  54033. */
  54034. _this.cameraColorGradingTexture = null;
  54035. /**
  54036. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  54037. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  54038. * 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;
  54039. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  54040. */
  54041. _this.cameraColorCurves = null;
  54042. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  54043. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  54044. /**
  54045. * Debug Control allowing to overload the ambient color.
  54046. * This as to be use with the overloadedAmbientIntensity parameter.
  54047. */
  54048. _this.overloadedAmbient = BABYLON.Color3.White();
  54049. /**
  54050. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  54051. */
  54052. _this.overloadedAmbientIntensity = 0.0;
  54053. /**
  54054. * Debug Control allowing to overload the albedo color.
  54055. * This as to be use with the overloadedAlbedoIntensity parameter.
  54056. */
  54057. _this.overloadedAlbedo = BABYLON.Color3.White();
  54058. /**
  54059. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  54060. */
  54061. _this.overloadedAlbedoIntensity = 0.0;
  54062. /**
  54063. * Debug Control allowing to overload the reflectivity color.
  54064. * This as to be use with the overloadedReflectivityIntensity parameter.
  54065. */
  54066. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  54067. /**
  54068. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  54069. */
  54070. _this.overloadedReflectivityIntensity = 0.0;
  54071. /**
  54072. * Debug Control allowing to overload the emissive color.
  54073. * This as to be use with the overloadedEmissiveIntensity parameter.
  54074. */
  54075. _this.overloadedEmissive = BABYLON.Color3.White();
  54076. /**
  54077. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  54078. */
  54079. _this.overloadedEmissiveIntensity = 0.0;
  54080. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  54081. /**
  54082. * Debug Control allowing to overload the reflection color.
  54083. * This as to be use with the overloadedReflectionIntensity parameter.
  54084. */
  54085. _this.overloadedReflection = BABYLON.Color3.White();
  54086. /**
  54087. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  54088. */
  54089. _this.overloadedReflectionIntensity = 0.0;
  54090. /**
  54091. * Debug Control allowing to overload the microsurface.
  54092. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  54093. */
  54094. _this.overloadedMicroSurface = 0.0;
  54095. /**
  54096. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  54097. */
  54098. _this.overloadedMicroSurfaceIntensity = 0.0;
  54099. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  54100. /**
  54101. * AKA Occlusion Texture Intensity in other nomenclature.
  54102. */
  54103. _this.ambientTextureStrength = 1.0;
  54104. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  54105. /**
  54106. * AKA Diffuse Color in other nomenclature.
  54107. */
  54108. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  54109. /**
  54110. * AKA Specular Color in other nomenclature.
  54111. */
  54112. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  54113. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  54114. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  54115. /**
  54116. * AKA Glossiness in other nomenclature.
  54117. */
  54118. _this.microSurface = 0.9;
  54119. /**
  54120. * source material index of refraction (IOR)' / 'destination material IOR.
  54121. */
  54122. _this.indexOfRefraction = 0.66;
  54123. /**
  54124. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  54125. */
  54126. _this.invertRefractionY = false;
  54127. /**
  54128. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  54129. * Materials half opaque for instance using refraction could benefit from this control.
  54130. */
  54131. _this.linkRefractionWithTransparency = false;
  54132. /**
  54133. * The emissive and albedo are linked to never be more than one (Energy conservation).
  54134. */
  54135. _this.linkEmissiveWithAlbedo = false;
  54136. _this.useLightmapAsShadowmap = false;
  54137. /**
  54138. * In this mode, the emissive informtaion will always be added to the lighting once.
  54139. * A light for instance can be thought as emissive.
  54140. */
  54141. _this.useEmissiveAsIllumination = false;
  54142. /**
  54143. * Secifies that the alpha is coming form the albedo channel alpha channel.
  54144. */
  54145. _this.useAlphaFromAlbedoTexture = false;
  54146. /**
  54147. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  54148. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  54149. */
  54150. _this.useSpecularOverAlpha = true;
  54151. /**
  54152. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  54153. */
  54154. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  54155. /**
  54156. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  54157. */
  54158. _this.useRoughnessFromMetallicTextureAlpha = true;
  54159. /**
  54160. * Specifies if the metallic texture contains the roughness information in its green channel.
  54161. */
  54162. _this.useRoughnessFromMetallicTextureGreen = false;
  54163. /**
  54164. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  54165. * The material will try to infer what glossiness each pixel should be.
  54166. */
  54167. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  54168. /**
  54169. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  54170. * the creation of the material.
  54171. */
  54172. _this.useScalarInLinearSpace = false;
  54173. /**
  54174. * BJS is using an harcoded light falloff based on a manually sets up range.
  54175. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  54176. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  54177. */
  54178. _this.usePhysicalLightFalloff = true;
  54179. /**
  54180. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  54181. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  54182. */
  54183. _this.useRadianceOverAlpha = true;
  54184. /**
  54185. * Allows using the bump map in parallax mode.
  54186. */
  54187. _this.useParallax = false;
  54188. /**
  54189. * Allows using the bump map in parallax occlusion mode.
  54190. */
  54191. _this.useParallaxOcclusion = false;
  54192. /**
  54193. * Controls the scale bias of the parallax mode.
  54194. */
  54195. _this.parallaxScaleBias = 0.05;
  54196. /**
  54197. * If sets to true, disables all the lights affecting the material.
  54198. */
  54199. _this.disableLighting = false;
  54200. /**
  54201. * Number of Simultaneous lights allowed on the material.
  54202. */
  54203. _this.maxSimultaneousLights = 4;
  54204. /**
  54205. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  54206. */
  54207. _this.invertNormalMapX = false;
  54208. /**
  54209. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  54210. */
  54211. _this.invertNormalMapY = false;
  54212. _this._renderTargets = new BABYLON.SmartArray(16);
  54213. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  54214. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  54215. _this._tempColor = new BABYLON.Color3();
  54216. _this._defines = new PBRMaterialDefines();
  54217. _this._cachedDefines = new PBRMaterialDefines();
  54218. _this._myScene = null;
  54219. _this._myShadowGenerator = null;
  54220. _this._cachedDefines.BonesPerMesh = -1;
  54221. _this.getRenderTargetTextures = function () {
  54222. _this._renderTargets.reset();
  54223. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  54224. _this._renderTargets.push(_this.reflectionTexture);
  54225. }
  54226. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  54227. _this._renderTargets.push(_this.refractionTexture);
  54228. }
  54229. return _this._renderTargets;
  54230. };
  54231. return _this;
  54232. }
  54233. PBRMaterial.prototype.getClassName = function () {
  54234. return "PBRMaterial";
  54235. };
  54236. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  54237. get: function () {
  54238. return this._useLogarithmicDepth;
  54239. },
  54240. set: function (value) {
  54241. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  54242. },
  54243. enumerable: true,
  54244. configurable: true
  54245. });
  54246. PBRMaterial.prototype.needAlphaBlending = function () {
  54247. if (this.linkRefractionWithTransparency) {
  54248. return false;
  54249. }
  54250. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  54251. };
  54252. PBRMaterial.prototype.needAlphaTesting = function () {
  54253. if (this.linkRefractionWithTransparency) {
  54254. return false;
  54255. }
  54256. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  54257. };
  54258. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  54259. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  54260. };
  54261. PBRMaterial.prototype.getAlphaTestTexture = function () {
  54262. return this.albedoTexture;
  54263. };
  54264. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  54265. if (!mesh) {
  54266. return true;
  54267. }
  54268. if (this._defines.INSTANCES !== useInstances) {
  54269. return false;
  54270. }
  54271. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  54272. return true;
  54273. }
  54274. return false;
  54275. };
  54276. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  54277. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  54278. };
  54279. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  54280. if (!useScalarInLinear) {
  54281. color.toLinearSpaceToRef(ref);
  54282. }
  54283. else {
  54284. ref.r = color.r;
  54285. ref.g = color.g;
  54286. ref.b = color.b;
  54287. }
  54288. };
  54289. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  54290. var lightIndex = 0;
  54291. var depthValuesAlreadySet = false;
  54292. for (var index = 0; index < scene.lights.length; index++) {
  54293. var light = scene.lights[index];
  54294. if (!light.isEnabled()) {
  54295. continue;
  54296. }
  54297. if (!light.canAffectMesh(mesh)) {
  54298. continue;
  54299. }
  54300. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  54301. // GAMMA CORRECTION.
  54302. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  54303. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  54304. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  54305. if (defines["SPECULARTERM"]) {
  54306. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  54307. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  54308. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  54309. }
  54310. // Shadows
  54311. if (scene.shadowsEnabled) {
  54312. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  54313. }
  54314. lightIndex++;
  54315. if (lightIndex === maxSimultaneousLights)
  54316. break;
  54317. }
  54318. };
  54319. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  54320. if (this.isFrozen) {
  54321. if (this._wasPreviouslyReady) {
  54322. return true;
  54323. }
  54324. }
  54325. var scene = this.getScene();
  54326. var engine = scene.getEngine();
  54327. var needNormals = false;
  54328. var needUVs = false;
  54329. this._defines.reset();
  54330. if (scene.lightsEnabled && !this.disableLighting) {
  54331. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  54332. }
  54333. if (!this.checkReadyOnEveryCall) {
  54334. if (this._renderId === scene.getRenderId()) {
  54335. if (this._checkCache(scene, mesh, useInstances)) {
  54336. return true;
  54337. }
  54338. }
  54339. }
  54340. if (scene.texturesEnabled) {
  54341. if (scene.getEngine().getCaps().textureLOD) {
  54342. this._defines.LODBASEDMICROSFURACE = true;
  54343. }
  54344. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54345. if (!this.albedoTexture.isReady()) {
  54346. return false;
  54347. }
  54348. else {
  54349. needUVs = true;
  54350. this._defines.ALBEDO = true;
  54351. }
  54352. }
  54353. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  54354. if (!this.ambientTexture.isReady()) {
  54355. return false;
  54356. }
  54357. else {
  54358. needUVs = true;
  54359. this._defines.AMBIENT = true;
  54360. }
  54361. }
  54362. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  54363. if (!this.opacityTexture.isReady()) {
  54364. return false;
  54365. }
  54366. else {
  54367. needUVs = true;
  54368. this._defines.OPACITY = true;
  54369. if (this.opacityTexture.getAlphaFromRGB) {
  54370. this._defines.OPACITYRGB = true;
  54371. }
  54372. }
  54373. }
  54374. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  54375. if (!this.reflectionTexture.isReady()) {
  54376. return false;
  54377. }
  54378. else {
  54379. needNormals = true;
  54380. this._defines.REFLECTION = true;
  54381. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  54382. this._defines.INVERTCUBICMAP = true;
  54383. }
  54384. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  54385. switch (this.reflectionTexture.coordinatesMode) {
  54386. case BABYLON.Texture.CUBIC_MODE:
  54387. case BABYLON.Texture.INVCUBIC_MODE:
  54388. this._defines.REFLECTIONMAP_CUBIC = true;
  54389. break;
  54390. case BABYLON.Texture.EXPLICIT_MODE:
  54391. this._defines.REFLECTIONMAP_EXPLICIT = true;
  54392. break;
  54393. case BABYLON.Texture.PLANAR_MODE:
  54394. this._defines.REFLECTIONMAP_PLANAR = true;
  54395. break;
  54396. case BABYLON.Texture.PROJECTION_MODE:
  54397. this._defines.REFLECTIONMAP_PROJECTION = true;
  54398. break;
  54399. case BABYLON.Texture.SKYBOX_MODE:
  54400. this._defines.REFLECTIONMAP_SKYBOX = true;
  54401. break;
  54402. case BABYLON.Texture.SPHERICAL_MODE:
  54403. this._defines.REFLECTIONMAP_SPHERICAL = true;
  54404. break;
  54405. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  54406. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  54407. break;
  54408. }
  54409. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  54410. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  54411. needNormals = true;
  54412. if (this.reflectionTexture.isPMREM) {
  54413. this._defines.USEPMREMREFLECTION = true;
  54414. }
  54415. }
  54416. }
  54417. }
  54418. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  54419. if (!this.lightmapTexture.isReady()) {
  54420. return false;
  54421. }
  54422. else {
  54423. needUVs = true;
  54424. this._defines.LIGHTMAP = true;
  54425. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  54426. }
  54427. }
  54428. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  54429. if (!this.emissiveTexture.isReady()) {
  54430. return false;
  54431. }
  54432. else {
  54433. needUVs = true;
  54434. this._defines.EMISSIVE = true;
  54435. }
  54436. }
  54437. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  54438. if (this.metallicTexture) {
  54439. if (!this.metallicTexture.isReady()) {
  54440. return false;
  54441. }
  54442. else {
  54443. needUVs = true;
  54444. this._defines.METALLICWORKFLOW = true;
  54445. this._defines.METALLICROUGHNESSMAP = true;
  54446. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  54447. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  54448. }
  54449. }
  54450. else if (this.reflectivityTexture) {
  54451. if (!this.reflectivityTexture.isReady()) {
  54452. return false;
  54453. }
  54454. else {
  54455. needUVs = true;
  54456. this._defines.REFLECTIVITY = true;
  54457. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  54458. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  54459. }
  54460. }
  54461. }
  54462. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  54463. if (!this.bumpTexture.isReady()) {
  54464. return false;
  54465. }
  54466. else {
  54467. needUVs = true;
  54468. this._defines.BUMP = true;
  54469. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54470. this._defines.PARALLAX = true;
  54471. if (this.useParallaxOcclusion) {
  54472. this._defines.PARALLAXOCCLUSION = true;
  54473. }
  54474. }
  54475. if (this.invertNormalMapX) {
  54476. this._defines.INVERTNORMALMAPX = true;
  54477. }
  54478. if (this.invertNormalMapY) {
  54479. this._defines.INVERTNORMALMAPY = true;
  54480. }
  54481. if (scene._mirroredCameraPosition) {
  54482. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  54483. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  54484. }
  54485. }
  54486. }
  54487. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  54488. if (!this.refractionTexture.isReady()) {
  54489. return false;
  54490. }
  54491. else {
  54492. needUVs = true;
  54493. this._defines.REFRACTION = true;
  54494. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  54495. if (this.linkRefractionWithTransparency) {
  54496. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  54497. }
  54498. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  54499. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  54500. if (this.refractionTexture.isPMREM) {
  54501. this._defines.USEPMREMREFRACTION = true;
  54502. }
  54503. }
  54504. }
  54505. }
  54506. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  54507. if (!this.cameraColorGradingTexture.isReady()) {
  54508. return false;
  54509. }
  54510. else {
  54511. this._defines.CAMERACOLORGRADING = true;
  54512. }
  54513. }
  54514. }
  54515. // Effect
  54516. if (scene.clipPlane) {
  54517. this._defines.CLIPPLANE = true;
  54518. }
  54519. if (engine.getAlphaTesting()) {
  54520. this._defines.ALPHATEST = true;
  54521. }
  54522. if (this._shouldUseAlphaFromAlbedoTexture()) {
  54523. this._defines.ALPHAFROMALBEDO = true;
  54524. }
  54525. if (this.useEmissiveAsIllumination) {
  54526. this._defines.EMISSIVEASILLUMINATION = true;
  54527. }
  54528. if (this.linkEmissiveWithAlbedo) {
  54529. this._defines.LINKEMISSIVEWITHALBEDO = true;
  54530. }
  54531. if (this.useLogarithmicDepth) {
  54532. this._defines.LOGARITHMICDEPTH = true;
  54533. }
  54534. if (this.cameraContrast != 1) {
  54535. this._defines.CAMERACONTRAST = true;
  54536. }
  54537. if (this.cameraExposure != 1) {
  54538. this._defines.CAMERATONEMAP = true;
  54539. }
  54540. if (this.cameraColorCurves) {
  54541. this._defines.CAMERACOLORCURVES = true;
  54542. }
  54543. if (this.overloadedShadeIntensity != 1 ||
  54544. this.overloadedShadowIntensity != 1) {
  54545. this._defines.OVERLOADEDSHADOWVALUES = true;
  54546. }
  54547. if (this.overloadedMicroSurfaceIntensity > 0 ||
  54548. this.overloadedEmissiveIntensity > 0 ||
  54549. this.overloadedReflectivityIntensity > 0 ||
  54550. this.overloadedAlbedoIntensity > 0 ||
  54551. this.overloadedAmbientIntensity > 0 ||
  54552. this.overloadedReflectionIntensity > 0) {
  54553. this._defines.OVERLOADEDVALUES = true;
  54554. }
  54555. // Point size
  54556. if (this.pointsCloud || scene.forcePointsCloud) {
  54557. this._defines.POINTSIZE = true;
  54558. }
  54559. // Fog
  54560. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54561. this._defines.FOG = true;
  54562. }
  54563. if (BABYLON.StandardMaterial.FresnelEnabled) {
  54564. // Fresnel
  54565. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  54566. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54567. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  54568. this._defines.OPACITYFRESNEL = true;
  54569. }
  54570. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54571. this._defines.EMISSIVEFRESNEL = true;
  54572. }
  54573. needNormals = true;
  54574. this._defines.FRESNEL = true;
  54575. }
  54576. }
  54577. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  54578. this._defines.SPECULAROVERALPHA = true;
  54579. }
  54580. if (this.usePhysicalLightFalloff) {
  54581. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  54582. }
  54583. if (this.useRadianceOverAlpha) {
  54584. this._defines.RADIANCEOVERALPHA = true;
  54585. }
  54586. if ((this.metallic !== undefined && this.metallic !== null) || (this.roughness !== undefined && this.roughness !== null)) {
  54587. this._defines.METALLICWORKFLOW = true;
  54588. }
  54589. // Attribs
  54590. if (mesh) {
  54591. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54592. this._defines.NORMAL = true;
  54593. }
  54594. if (needUVs) {
  54595. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54596. this._defines.UV1 = true;
  54597. }
  54598. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54599. this._defines.UV2 = true;
  54600. }
  54601. }
  54602. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  54603. this._defines.VERTEXCOLOR = true;
  54604. if (mesh.hasVertexAlpha) {
  54605. this._defines.VERTEXALPHA = true;
  54606. }
  54607. }
  54608. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54609. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  54610. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  54611. }
  54612. // Instances
  54613. if (useInstances) {
  54614. this._defines.INSTANCES = true;
  54615. }
  54616. }
  54617. // Get correct effect
  54618. if (!this._defines.isEqual(this._cachedDefines)) {
  54619. this._defines.cloneTo(this._cachedDefines);
  54620. scene.resetCachedMaterial();
  54621. // Fallbacks
  54622. var fallbacks = new BABYLON.EffectFallbacks();
  54623. if (this._defines.REFLECTION) {
  54624. fallbacks.addFallback(0, "REFLECTION");
  54625. }
  54626. if (this._defines.REFRACTION) {
  54627. fallbacks.addFallback(0, "REFRACTION");
  54628. }
  54629. if (this._defines.REFLECTIVITY) {
  54630. fallbacks.addFallback(0, "REFLECTIVITY");
  54631. }
  54632. if (this._defines.BUMP) {
  54633. fallbacks.addFallback(0, "BUMP");
  54634. }
  54635. if (this._defines.PARALLAX) {
  54636. fallbacks.addFallback(1, "PARALLAX");
  54637. }
  54638. if (this._defines.PARALLAXOCCLUSION) {
  54639. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  54640. }
  54641. if (this._defines.SPECULAROVERALPHA) {
  54642. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  54643. }
  54644. if (this._defines.FOG) {
  54645. fallbacks.addFallback(1, "FOG");
  54646. }
  54647. if (this._defines.POINTSIZE) {
  54648. fallbacks.addFallback(0, "POINTSIZE");
  54649. }
  54650. if (this._defines.LOGARITHMICDEPTH) {
  54651. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  54652. }
  54653. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  54654. if (this._defines.SPECULARTERM) {
  54655. fallbacks.addFallback(0, "SPECULARTERM");
  54656. }
  54657. if (this._defines.OPACITYFRESNEL) {
  54658. fallbacks.addFallback(1, "OPACITYFRESNEL");
  54659. }
  54660. if (this._defines.EMISSIVEFRESNEL) {
  54661. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  54662. }
  54663. if (this._defines.FRESNEL) {
  54664. fallbacks.addFallback(3, "FRESNEL");
  54665. }
  54666. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  54667. fallbacks.addCPUSkinningFallback(0, mesh);
  54668. }
  54669. //Attributes
  54670. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54671. if (this._defines.NORMAL) {
  54672. attribs.push(BABYLON.VertexBuffer.NormalKind);
  54673. }
  54674. if (this._defines.UV1) {
  54675. attribs.push(BABYLON.VertexBuffer.UVKind);
  54676. }
  54677. if (this._defines.UV2) {
  54678. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54679. }
  54680. if (this._defines.VERTEXCOLOR) {
  54681. attribs.push(BABYLON.VertexBuffer.ColorKind);
  54682. }
  54683. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  54684. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  54685. // Legacy browser patch
  54686. var join = this._defines.toString();
  54687. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  54688. "vFogInfos", "vFogColor", "pointSize",
  54689. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  54690. "mBones",
  54691. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  54692. "depthValues",
  54693. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  54694. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  54695. "logarithmicDepthConstant",
  54696. "vSphericalX", "vSphericalY", "vSphericalZ",
  54697. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  54698. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  54699. "vMicrosurfaceTextureLods",
  54700. "vCameraInfos"
  54701. ];
  54702. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  54703. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  54704. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  54705. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  54706. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  54707. }
  54708. if (!this._effect.isReady()) {
  54709. return false;
  54710. }
  54711. this._renderId = scene.getRenderId();
  54712. this._wasPreviouslyReady = true;
  54713. if (mesh) {
  54714. if (!mesh._materialDefines) {
  54715. mesh._materialDefines = new PBRMaterialDefines();
  54716. }
  54717. this._defines.cloneTo(mesh._materialDefines);
  54718. }
  54719. return true;
  54720. };
  54721. PBRMaterial.prototype.unbind = function () {
  54722. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  54723. this._effect.setTexture("reflection2DSampler", null);
  54724. }
  54725. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  54726. this._effect.setTexture("refraction2DSampler", null);
  54727. }
  54728. _super.prototype.unbind.call(this);
  54729. };
  54730. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  54731. this._effect.setMatrix("world", world);
  54732. };
  54733. PBRMaterial.prototype.bind = function (world, mesh) {
  54734. this._myScene = this.getScene();
  54735. // Matrices
  54736. this.bindOnlyWorldMatrix(world);
  54737. // Bones
  54738. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  54739. if (this._myScene.getCachedMaterial() !== this) {
  54740. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  54741. if (BABYLON.StandardMaterial.FresnelEnabled) {
  54742. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  54743. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  54744. }
  54745. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  54746. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  54747. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  54748. }
  54749. }
  54750. // Textures
  54751. if (this._myScene.texturesEnabled) {
  54752. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  54753. this._effect.setTexture("albedoSampler", this.albedoTexture);
  54754. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  54755. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  54756. }
  54757. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  54758. this._effect.setTexture("ambientSampler", this.ambientTexture);
  54759. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  54760. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  54761. }
  54762. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  54763. this._effect.setTexture("opacitySampler", this.opacityTexture);
  54764. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  54765. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  54766. }
  54767. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  54768. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  54769. if (this.reflectionTexture.isCube) {
  54770. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  54771. }
  54772. else {
  54773. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  54774. }
  54775. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  54776. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  54777. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  54778. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  54779. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  54780. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  54781. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  54782. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  54783. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  54784. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  54785. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  54786. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  54787. }
  54788. }
  54789. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  54790. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  54791. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  54792. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  54793. }
  54794. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  54795. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  54796. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  54797. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  54798. }
  54799. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  54800. if (this.metallicTexture) {
  54801. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  54802. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  54803. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  54804. }
  54805. else if (this.reflectivityTexture) {
  54806. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  54807. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  54808. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  54809. }
  54810. }
  54811. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  54812. this._effect.setTexture("bumpSampler", this.bumpTexture);
  54813. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  54814. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  54815. }
  54816. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  54817. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  54818. var depth = 1.0;
  54819. if (this.refractionTexture.isCube) {
  54820. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  54821. }
  54822. else {
  54823. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  54824. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  54825. if (this.refractionTexture.depth) {
  54826. depth = this.refractionTexture.depth;
  54827. }
  54828. }
  54829. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  54830. }
  54831. if ((this.reflectionTexture || this.refractionTexture)) {
  54832. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  54833. }
  54834. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  54835. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  54836. }
  54837. }
  54838. // Clip plane
  54839. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  54840. // Point size
  54841. if (this.pointsCloud) {
  54842. this._effect.setFloat("pointSize", this.pointSize);
  54843. }
  54844. // Colors
  54845. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  54846. if (this._defines.METALLICWORKFLOW) {
  54847. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  54848. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  54849. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  54850. }
  54851. else {
  54852. // GAMMA CORRECTION.
  54853. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  54854. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  54855. }
  54856. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  54857. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  54858. // GAMMA CORRECTION.
  54859. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  54860. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  54861. // GAMMA CORRECTION.
  54862. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  54863. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  54864. }
  54865. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  54866. // GAMMA CORRECTION.
  54867. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  54868. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  54869. // Lights
  54870. if (this._myScene.lightsEnabled && !this.disableLighting) {
  54871. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  54872. }
  54873. // View
  54874. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  54875. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  54876. }
  54877. // Fog
  54878. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  54879. this._lightingInfos.x = this.directIntensity;
  54880. this._lightingInfos.y = this.emissiveIntensity;
  54881. this._lightingInfos.z = this.environmentIntensity;
  54882. this._lightingInfos.w = this.specularIntensity;
  54883. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  54884. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  54885. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  54886. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  54887. this._cameraInfos.x = this.cameraExposure;
  54888. this._cameraInfos.y = this.cameraContrast;
  54889. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  54890. if (this.cameraColorCurves) {
  54891. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  54892. }
  54893. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  54894. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  54895. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  54896. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  54897. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  54898. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  54899. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  54900. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  54901. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  54902. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  54903. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  54904. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  54905. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  54906. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  54907. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  54908. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  54909. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  54910. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  54911. // Log. depth
  54912. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  54913. }
  54914. _super.prototype.bind.call(this, world, mesh);
  54915. this._myScene = null;
  54916. };
  54917. PBRMaterial.prototype.getAnimatables = function () {
  54918. var results = [];
  54919. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  54920. results.push(this.albedoTexture);
  54921. }
  54922. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  54923. results.push(this.ambientTexture);
  54924. }
  54925. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  54926. results.push(this.opacityTexture);
  54927. }
  54928. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  54929. results.push(this.reflectionTexture);
  54930. }
  54931. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  54932. results.push(this.emissiveTexture);
  54933. }
  54934. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  54935. results.push(this.metallicTexture);
  54936. }
  54937. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  54938. results.push(this.reflectivityTexture);
  54939. }
  54940. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  54941. results.push(this.bumpTexture);
  54942. }
  54943. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  54944. results.push(this.lightmapTexture);
  54945. }
  54946. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  54947. results.push(this.refractionTexture);
  54948. }
  54949. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  54950. results.push(this.cameraColorGradingTexture);
  54951. }
  54952. return results;
  54953. };
  54954. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54955. if (forceDisposeTextures) {
  54956. if (this.albedoTexture) {
  54957. this.albedoTexture.dispose();
  54958. }
  54959. if (this.ambientTexture) {
  54960. this.ambientTexture.dispose();
  54961. }
  54962. if (this.opacityTexture) {
  54963. this.opacityTexture.dispose();
  54964. }
  54965. if (this.reflectionTexture) {
  54966. this.reflectionTexture.dispose();
  54967. }
  54968. if (this.emissiveTexture) {
  54969. this.emissiveTexture.dispose();
  54970. }
  54971. if (this.metallicTexture) {
  54972. this.metallicTexture.dispose();
  54973. }
  54974. if (this.reflectivityTexture) {
  54975. this.reflectivityTexture.dispose();
  54976. }
  54977. if (this.bumpTexture) {
  54978. this.bumpTexture.dispose();
  54979. }
  54980. if (this.lightmapTexture) {
  54981. this.lightmapTexture.dispose();
  54982. }
  54983. if (this.refractionTexture) {
  54984. this.refractionTexture.dispose();
  54985. }
  54986. if (this.cameraColorGradingTexture) {
  54987. this.cameraColorGradingTexture.dispose();
  54988. }
  54989. }
  54990. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54991. };
  54992. PBRMaterial.prototype.clone = function (name) {
  54993. var _this = this;
  54994. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  54995. };
  54996. PBRMaterial.prototype.serialize = function () {
  54997. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54998. serializationObject.customType = "BABYLON.PBRMaterial";
  54999. return serializationObject;
  55000. };
  55001. // Statics
  55002. PBRMaterial.Parse = function (source, scene, rootUrl) {
  55003. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  55004. };
  55005. return PBRMaterial;
  55006. }(BABYLON.Material));
  55007. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  55008. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  55009. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  55010. PBRMaterial._scaledReflection = new BABYLON.Color3();
  55011. __decorate([
  55012. BABYLON.serialize()
  55013. ], PBRMaterial.prototype, "directIntensity", void 0);
  55014. __decorate([
  55015. BABYLON.serialize()
  55016. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  55017. __decorate([
  55018. BABYLON.serialize()
  55019. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  55020. __decorate([
  55021. BABYLON.serialize()
  55022. ], PBRMaterial.prototype, "specularIntensity", void 0);
  55023. __decorate([
  55024. BABYLON.serialize()
  55025. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  55026. __decorate([
  55027. BABYLON.serialize()
  55028. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  55029. __decorate([
  55030. BABYLON.serialize()
  55031. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  55032. __decorate([
  55033. BABYLON.serialize()
  55034. ], PBRMaterial.prototype, "cameraExposure", void 0);
  55035. __decorate([
  55036. BABYLON.serialize()
  55037. ], PBRMaterial.prototype, "cameraContrast", void 0);
  55038. __decorate([
  55039. BABYLON.serializeAsTexture()
  55040. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  55041. __decorate([
  55042. BABYLON.serializeAsColorCurves()
  55043. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  55044. __decorate([
  55045. BABYLON.serializeAsColor3()
  55046. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  55047. __decorate([
  55048. BABYLON.serialize()
  55049. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  55050. __decorate([
  55051. BABYLON.serializeAsColor3()
  55052. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  55053. __decorate([
  55054. BABYLON.serialize()
  55055. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  55056. __decorate([
  55057. BABYLON.serializeAsColor3()
  55058. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  55059. __decorate([
  55060. BABYLON.serialize()
  55061. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  55062. __decorate([
  55063. BABYLON.serializeAsColor3()
  55064. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  55065. __decorate([
  55066. BABYLON.serialize()
  55067. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  55068. __decorate([
  55069. BABYLON.serializeAsColor3()
  55070. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  55071. __decorate([
  55072. BABYLON.serialize()
  55073. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  55074. __decorate([
  55075. BABYLON.serialize()
  55076. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  55077. __decorate([
  55078. BABYLON.serialize()
  55079. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  55080. __decorate([
  55081. BABYLON.serializeAsTexture()
  55082. ], PBRMaterial.prototype, "albedoTexture", void 0);
  55083. __decorate([
  55084. BABYLON.serializeAsTexture()
  55085. ], PBRMaterial.prototype, "ambientTexture", void 0);
  55086. __decorate([
  55087. BABYLON.serialize()
  55088. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  55089. __decorate([
  55090. BABYLON.serializeAsTexture()
  55091. ], PBRMaterial.prototype, "opacityTexture", void 0);
  55092. __decorate([
  55093. BABYLON.serializeAsTexture()
  55094. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  55095. __decorate([
  55096. BABYLON.serializeAsTexture()
  55097. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  55098. __decorate([
  55099. BABYLON.serializeAsTexture()
  55100. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  55101. __decorate([
  55102. BABYLON.serializeAsTexture()
  55103. ], PBRMaterial.prototype, "metallicTexture", void 0);
  55104. __decorate([
  55105. BABYLON.serialize()
  55106. ], PBRMaterial.prototype, "metallic", void 0);
  55107. __decorate([
  55108. BABYLON.serialize()
  55109. ], PBRMaterial.prototype, "roughness", void 0);
  55110. __decorate([
  55111. BABYLON.serializeAsTexture()
  55112. ], PBRMaterial.prototype, "bumpTexture", void 0);
  55113. __decorate([
  55114. BABYLON.serializeAsTexture()
  55115. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  55116. __decorate([
  55117. BABYLON.serializeAsTexture()
  55118. ], PBRMaterial.prototype, "refractionTexture", void 0);
  55119. __decorate([
  55120. BABYLON.serializeAsColor3("ambient")
  55121. ], PBRMaterial.prototype, "ambientColor", void 0);
  55122. __decorate([
  55123. BABYLON.serializeAsColor3("albedo")
  55124. ], PBRMaterial.prototype, "albedoColor", void 0);
  55125. __decorate([
  55126. BABYLON.serializeAsColor3("reflectivity")
  55127. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  55128. __decorate([
  55129. BABYLON.serializeAsColor3("reflection")
  55130. ], PBRMaterial.prototype, "reflectionColor", void 0);
  55131. __decorate([
  55132. BABYLON.serializeAsColor3("emissive")
  55133. ], PBRMaterial.prototype, "emissiveColor", void 0);
  55134. __decorate([
  55135. BABYLON.serialize()
  55136. ], PBRMaterial.prototype, "microSurface", void 0);
  55137. __decorate([
  55138. BABYLON.serialize()
  55139. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  55140. __decorate([
  55141. BABYLON.serialize()
  55142. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  55143. __decorate([
  55144. BABYLON.serializeAsFresnelParameters()
  55145. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  55146. __decorate([
  55147. BABYLON.serializeAsFresnelParameters()
  55148. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  55149. __decorate([
  55150. BABYLON.serialize()
  55151. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  55152. __decorate([
  55153. BABYLON.serialize()
  55154. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  55155. __decorate([
  55156. BABYLON.serialize()
  55157. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  55158. __decorate([
  55159. BABYLON.serialize()
  55160. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  55161. __decorate([
  55162. BABYLON.serialize()
  55163. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  55164. __decorate([
  55165. BABYLON.serialize()
  55166. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  55167. __decorate([
  55168. BABYLON.serialize()
  55169. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  55170. __decorate([
  55171. BABYLON.serialize()
  55172. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  55173. __decorate([
  55174. BABYLON.serialize()
  55175. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  55176. __decorate([
  55177. BABYLON.serialize()
  55178. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  55179. __decorate([
  55180. BABYLON.serialize()
  55181. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  55182. __decorate([
  55183. BABYLON.serialize()
  55184. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  55185. __decorate([
  55186. BABYLON.serialize()
  55187. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  55188. __decorate([
  55189. BABYLON.serialize()
  55190. ], PBRMaterial.prototype, "useParallax", void 0);
  55191. __decorate([
  55192. BABYLON.serialize()
  55193. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  55194. __decorate([
  55195. BABYLON.serialize()
  55196. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  55197. __decorate([
  55198. BABYLON.serialize()
  55199. ], PBRMaterial.prototype, "disableLighting", void 0);
  55200. __decorate([
  55201. BABYLON.serialize()
  55202. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  55203. __decorate([
  55204. BABYLON.serialize()
  55205. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  55206. __decorate([
  55207. BABYLON.serialize()
  55208. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  55209. __decorate([
  55210. BABYLON.serialize()
  55211. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  55212. BABYLON.PBRMaterial = PBRMaterial;
  55213. })(BABYLON || (BABYLON = {}));
  55214. //# sourceMappingURL=babylon.pbrMaterial.js.map
  55215. var BABYLON;
  55216. (function (BABYLON) {
  55217. var DebugLayer = (function () {
  55218. function DebugLayer(scene) {
  55219. this._scene = scene;
  55220. }
  55221. /** Creates the inspector window. */
  55222. DebugLayer.prototype._createInspector = function (popup) {
  55223. if (!this._inspector) {
  55224. this._inspector = new INSPECTOR.Inspector(this._scene, popup);
  55225. } // else nothing to do,; instance is already existing
  55226. };
  55227. DebugLayer.prototype.isVisible = function () {
  55228. return false;
  55229. };
  55230. DebugLayer.prototype.hide = function () {
  55231. if (this._inspector) {
  55232. this._inspector.dispose();
  55233. this._inspector = null;
  55234. }
  55235. };
  55236. DebugLayer.prototype.show = function (popup) {
  55237. if (typeof INSPECTOR == 'undefined') {
  55238. // Load inspector and add it to the DOM
  55239. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup));
  55240. }
  55241. else {
  55242. // Otherwise creates the inspector
  55243. this._createInspector(popup);
  55244. }
  55245. };
  55246. return DebugLayer;
  55247. }());
  55248. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  55249. BABYLON.DebugLayer = DebugLayer;
  55250. })(BABYLON || (BABYLON = {}));
  55251. //# sourceMappingURL=babylon.debugLayer.js.map
  55252. var BABYLON;
  55253. (function (BABYLON) {
  55254. var StandardRenderingPipeline = (function (_super) {
  55255. __extends(StandardRenderingPipeline, _super);
  55256. /**
  55257. * @constructor
  55258. * @param {string} name - The rendering pipeline name
  55259. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  55260. * @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)
  55261. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  55262. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  55263. */
  55264. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  55265. if (originalPostProcess === void 0) { originalPostProcess = null; }
  55266. var _this = _super.call(this, scene.getEngine(), name) || this;
  55267. _this.downSampleX4PostProcess = null;
  55268. _this.brightPassPostProcess = null;
  55269. _this.gaussianBlurHPostProcesses = [];
  55270. _this.gaussianBlurVPostProcesses = [];
  55271. _this.textureAdderPostProcess = null;
  55272. _this.textureAdderFinalPostProcess = null;
  55273. _this.lensFlarePostProcess = null;
  55274. _this.lensFlareComposePostProcess = null;
  55275. _this.depthOfFieldPostProcess = null;
  55276. // Values
  55277. _this.brightThreshold = 1.0;
  55278. _this.blurWidth = 2.0;
  55279. _this.gaussianCoefficient = 0.25;
  55280. _this.gaussianMean = 1.0;
  55281. _this.gaussianStandardDeviation = 1.0;
  55282. _this.exposure = 1.0;
  55283. _this.lensTexture = null;
  55284. _this.lensColorTexture = null;
  55285. _this.lensFlareStrength = 20.0;
  55286. _this.lensFlareGhostDispersal = 1.4;
  55287. _this.lensFlareHaloWidth = 0.7;
  55288. _this.lensFlareDistortionStrength = 16.0;
  55289. _this.lensStarTexture = null;
  55290. _this.lensFlareDirtTexture = null;
  55291. _this.depthOfFieldDistance = 10.0;
  55292. // IAnimatable
  55293. _this.animations = [];
  55294. _this._depthRenderer = null;
  55295. // Getters and setters
  55296. _this._depthOfFieldEnabled = true;
  55297. _this._lensFlareEnabled = true;
  55298. // Initialize
  55299. _this._scene = scene;
  55300. // Create pass post-processe
  55301. if (!originalPostProcess) {
  55302. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  55303. }
  55304. else {
  55305. _this.originalPostProcess = originalPostProcess;
  55306. }
  55307. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  55308. // Create down sample X4 post-process
  55309. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  55310. // Create bright pass post-process
  55311. _this._createBrightPassPostProcess(scene, ratio / 2);
  55312. // Create gaussian blur post-processes (down sampling blurs)
  55313. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  55314. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  55315. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  55316. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  55317. // Create texture adder post-process
  55318. _this._createTextureAdderPostProcess(scene, ratio);
  55319. // Create depth-of-field source post-process
  55320. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55321. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  55322. // Create lens flare post-process
  55323. _this._createLensFlarePostProcess(scene, ratio);
  55324. // Create gaussian blur used by depth-of-field
  55325. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  55326. // Create depth-of-field post-process
  55327. _this._createDepthOfFieldPostProcess(scene, ratio);
  55328. // Finish
  55329. scene.postProcessRenderPipelineManager.addPipeline(_this);
  55330. if (cameras !== null) {
  55331. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  55332. }
  55333. // Deactivate
  55334. _this.LensFlareEnabled = false;
  55335. _this.DepthOfFieldEnabled = false;
  55336. return _this;
  55337. }
  55338. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  55339. get: function () {
  55340. return this._depthOfFieldEnabled;
  55341. },
  55342. set: function (enabled) {
  55343. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  55344. if (enabled && !this._depthOfFieldEnabled) {
  55345. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55346. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55347. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  55348. this._depthRenderer = this._scene.enableDepthRenderer();
  55349. }
  55350. else if (!enabled && this._depthOfFieldEnabled) {
  55351. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55352. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55353. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  55354. }
  55355. this._depthOfFieldEnabled = enabled;
  55356. },
  55357. enumerable: true,
  55358. configurable: true
  55359. });
  55360. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  55361. get: function () {
  55362. return this._lensFlareEnabled;
  55363. },
  55364. set: function (enabled) {
  55365. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  55366. if (enabled && !this._lensFlareEnabled) {
  55367. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  55368. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  55369. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55370. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55371. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  55372. }
  55373. else if (!enabled && this._lensFlareEnabled) {
  55374. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  55375. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  55376. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  55377. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  55378. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  55379. }
  55380. this._lensFlareEnabled = enabled;
  55381. },
  55382. enumerable: true,
  55383. configurable: true
  55384. });
  55385. // Down Sample X4 Post-Processs
  55386. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  55387. var _this = this;
  55388. var downSampleX4Offsets = new Array(32);
  55389. 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);
  55390. this.downSampleX4PostProcess.onApply = function (effect) {
  55391. var id = 0;
  55392. for (var i = -2; i < 2; i++) {
  55393. for (var j = -2; j < 2; j++) {
  55394. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  55395. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  55396. id += 2;
  55397. }
  55398. }
  55399. effect.setArray2("dsOffsets", downSampleX4Offsets);
  55400. };
  55401. // Add to pipeline
  55402. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  55403. };
  55404. // Brightpass Post-Process
  55405. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  55406. var _this = this;
  55407. var brightOffsets = new Array(8);
  55408. 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);
  55409. this.brightPassPostProcess.onApply = function (effect) {
  55410. var sU = (1.0 / _this.brightPassPostProcess.width);
  55411. var sV = (1.0 / _this.brightPassPostProcess.height);
  55412. brightOffsets[0] = -0.5 * sU;
  55413. brightOffsets[1] = 0.5 * sV;
  55414. brightOffsets[2] = 0.5 * sU;
  55415. brightOffsets[3] = 0.5 * sV;
  55416. brightOffsets[4] = -0.5 * sU;
  55417. brightOffsets[5] = -0.5 * sV;
  55418. brightOffsets[6] = 0.5 * sU;
  55419. brightOffsets[7] = -0.5 * sV;
  55420. effect.setArray2("dsOffsets", brightOffsets);
  55421. effect.setFloat("brightThreshold", _this.brightThreshold);
  55422. };
  55423. // Add to pipeline
  55424. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  55425. };
  55426. // Create gaussian blur H&V post-processes
  55427. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  55428. var _this = this;
  55429. var blurOffsets = new Array(9);
  55430. var blurWeights = new Array(9);
  55431. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  55432. var callback = function (height) {
  55433. return function (effect) {
  55434. // Weights
  55435. var x = 0.0;
  55436. for (var i = 0; i < 9; i++) {
  55437. x = (i - 4.0) / 4.0;
  55438. blurWeights[i] =
  55439. _this.gaussianCoefficient
  55440. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  55441. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  55442. }
  55443. var lastOutputDimensions = {
  55444. width: scene.getEngine().getRenderWidth(),
  55445. height: scene.getEngine().getRenderHeight()
  55446. };
  55447. for (var i = 0; i < 9; i++) {
  55448. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  55449. blurOffsets[i] = value;
  55450. }
  55451. effect.setArray("blurOffsets", blurOffsets);
  55452. effect.setArray("blurWeights", blurWeights);
  55453. effect.setFloat("blurWidth", _this.blurWidth);
  55454. };
  55455. };
  55456. // Create horizontal gaussian blur post-processes
  55457. 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);
  55458. gaussianBlurHPostProcess.onApply = callback(false);
  55459. // Create vertical gaussian blur post-process
  55460. 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);
  55461. gaussianBlurVPostProcess.onApply = callback(true);
  55462. // Add to pipeline
  55463. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  55464. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  55465. // Finish
  55466. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  55467. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  55468. };
  55469. // Create texture adder post-process
  55470. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  55471. var _this = this;
  55472. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  55473. 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);
  55474. this.textureAdderPostProcess.onApply = function (effect) {
  55475. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  55476. effect.setTexture("lensSampler", _this.lensTexture);
  55477. effect.setFloat("exposure", _this.exposure);
  55478. };
  55479. // Add to pipeline
  55480. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  55481. };
  55482. // Create lens flare post-process
  55483. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  55484. var _this = this;
  55485. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55486. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  55487. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  55488. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  55489. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  55490. var resolution = new BABYLON.Vector2(0, 0);
  55491. // Lens flare
  55492. this.lensFlarePostProcess.onApply = function (effect) {
  55493. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  55494. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  55495. effect.setFloat("strength", _this.lensFlareStrength);
  55496. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  55497. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  55498. // Shift
  55499. resolution.x = _this.lensFlarePostProcess.width;
  55500. resolution.y = _this.lensFlarePostProcess.height;
  55501. effect.setVector2("resolution", resolution);
  55502. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  55503. };
  55504. // Compose
  55505. var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  55506. var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  55507. this.lensFlareComposePostProcess.onApply = function (effect) {
  55508. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  55509. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  55510. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  55511. // Lens start rotation matrix
  55512. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  55513. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  55514. var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
  55515. camRot *= 4.0;
  55516. var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  55517. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  55518. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  55519. };
  55520. };
  55521. // Create depth-of-field post-process
  55522. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  55523. var _this = this;
  55524. 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);
  55525. this.depthOfFieldPostProcess.onApply = function (effect) {
  55526. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  55527. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  55528. effect.setFloat("distance", _this.depthOfFieldDistance);
  55529. };
  55530. // Add to pipeline
  55531. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  55532. };
  55533. // Dispose
  55534. StandardRenderingPipeline.prototype.dispose = function () {
  55535. for (var i = 0; i < this._scene.cameras.length; i++) {
  55536. var camera = this._scene.cameras[i];
  55537. this.originalPostProcess.dispose(camera);
  55538. this.downSampleX4PostProcess.dispose(camera);
  55539. this.brightPassPostProcess.dispose(camera);
  55540. this.textureAdderPostProcess.dispose(camera);
  55541. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  55542. this.gaussianBlurHPostProcesses[j].dispose(camera);
  55543. }
  55544. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  55545. this.gaussianBlurVPostProcesses[j].dispose(camera);
  55546. }
  55547. this.textureAdderFinalPostProcess.dispose(camera);
  55548. this.lensFlarePostProcess.dispose(camera);
  55549. this.lensFlareComposePostProcess.dispose(camera);
  55550. this.depthOfFieldPostProcess.dispose(camera);
  55551. }
  55552. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  55553. _super.prototype.dispose.call(this);
  55554. };
  55555. return StandardRenderingPipeline;
  55556. }(BABYLON.PostProcessRenderPipeline));
  55557. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  55558. })(BABYLON || (BABYLON = {}));
  55559. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  55560. BABYLON.Effect.ShadersStore={"anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\nfloat luminance=dot(texture2D(textureSampler,vUV).rgb,vec3(0.3,0.59,0.11));\ngl_FragColor=vec4(luminance,luminance,luminance,1.0);\n}","blurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\nbaseColor+=texture2D(textureSampler,start+texelOffset)*weights[i];\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\nif (chromatic_aberration>0.0) {\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*radius*17.0/screen_width;\nfloat ref_shiftY=chromatic_aberration*radius*17.0/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\n}\ngl_FragColor=original;\n}","colorPixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","colorVertexShader":"\nattribute vec3 position;\n\nuniform mat4 worldViewProjection;\nvoid main(void) {\ngl_Position=worldViewProjection*vec4(position,1.0);\n}","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D texture,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(texture,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(texture,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","defaultPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<helperFunctions>\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform sampler2D diffuseSampler;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\n#endif\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb*vRefractionInfos.x;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb*vRefractionInfos.x;\n#endif\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb*vReflectionInfos.x;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb*vReflectionInfos.x;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb*vReflectionInfos.x;\n#endif\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\ngl_FragColor=color;\n}","defaultVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef DIFFUSE\nvarying vec2 vDiffuseUV;\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nvarying vec2 vSpecularUV;\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#include<pointCloudVertexDeclaration>\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef DIFFUSE\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform float far;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=(gl_FragCoord.z/gl_FragCoord.w)/far;\ngl_FragColor=vec4(depth,depth*depth,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","fxaaPixelShader":"#define FXAA_REDUCE_MIN (1.0/128.0)\n#define FXAA_REDUCE_MUL (1.0/8.0)\n#define FXAA_SPAN_MAX 8.0\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvoid main(){\nvec2 localTexelSize=texelSize;\nvec4 rgbNW=texture2D(textureSampler,(vUV+vec2(-1.0,-1.0)*localTexelSize));\nvec4 rgbNE=texture2D(textureSampler,(vUV+vec2(1.0,-1.0)*localTexelSize));\nvec4 rgbSW=texture2D(textureSampler,(vUV+vec2(-1.0,1.0)*localTexelSize));\nvec4 rgbSE=texture2D(textureSampler,(vUV+vec2(1.0,1.0)*localTexelSize));\nvec4 rgbM=texture2D(textureSampler,vUV);\nvec4 luma=vec4(0.299,0.587,0.114,1.0);\nfloat lumaNW=dot(rgbNW,luma);\nfloat lumaNE=dot(rgbNE,luma);\nfloat lumaSW=dot(rgbSW,luma);\nfloat lumaSE=dot(rgbSE,luma);\nfloat lumaM=dot(rgbM,luma);\nfloat lumaMin=min(lumaM,min(min(lumaNW,lumaNE),min(lumaSW,lumaSE)));\nfloat lumaMax=max(lumaM,max(max(lumaNW,lumaNE),max(lumaSW,lumaSE)));\nvec2 dir=vec2(-((lumaNW+lumaNE)-(lumaSW+lumaSE)),((lumaNW+lumaSW)-(lumaNE+lumaSE)));\nfloat dirReduce=max(\n(lumaNW+lumaNE+lumaSW+lumaSE)*(0.25*FXAA_REDUCE_MUL),\nFXAA_REDUCE_MIN);\nfloat rcpDirMin=1.0/(min(abs(dir.x),abs(dir.y))+dirReduce);\ndir=min(vec2(FXAA_SPAN_MAX,FXAA_SPAN_MAX),\nmax(vec2(-FXAA_SPAN_MAX,-FXAA_SPAN_MAX),\ndir*rcpDirMin))*localTexelSize;\nvec4 rgbA=0.5*(\ntexture2D(textureSampler,vUV+dir*(1.0/3.0-0.5)) +\ntexture2D(textureSampler,vUV+dir*(2.0/3.0-0.5)));\nvec4 rgbB=rgbA*0.5+0.25*(\ntexture2D(textureSampler,vUV+dir*-0.5) +\ntexture2D(textureSampler,vUV+dir*0.5));\nfloat lumaB=dot(rgbB,luma);\nif ((lumaB<lumaMin) || (lumaB>lumaMax)) {\ngl_FragColor=rgbA;\n}\nelse {\ngl_FragColor=rgbB;\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","hdrPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float multiplier;\nvoid main(void) {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*multiplier,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*multiplier))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nvoid main() {\nvec4 sum=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nsum.a=clamp(sum.a,0.0,1.0);\ngl_FragColor=sum;\n}\n#endif\n#if defined(LUMINANCE_GENERATOR)\nuniform vec2 lumOffsets[4];\nvoid main() {\nfloat average=0.0;\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat maximum=-1e20;\nfor (int i=0; i<4; i++) {\ncolor=texture2D(textureSampler,vUV+lumOffsets[i]);\nfloat GreyValue=length(color.rgb);\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLE\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main() {\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++) {\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifndef FINAL_DOWN_SAMPLE\ngl_FragColor=vec4(average,average,0.0,1.0);\n#else\ngl_FragColor=pack(average);\n#endif\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main() {\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(HDR)\nuniform sampler2D otherSampler;\nuniform float exposure;\nuniform float avgLuminance;\nvoid main() {\nvec4 color=texture2D(textureSampler,vUV)+texture2D(otherSampler,vUV);\nvec4 adjustedColor=color/avgLuminance*exposure;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","outlinePixelShader":"uniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}\n","particlesPixelShader":"\nvarying vec2 vUV;\nvarying vec4 vColor;\nuniform vec4 textureMask;\nuniform sampler2D diffuseSampler;\n#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif\nvoid main(void) {\n#ifdef CLIPPLANE\nif (fClipDistance>0.0)\ndiscard;\n#endif\nvec4 baseColor=texture2D(diffuseSampler,vUV);\ngl_FragColor=(baseColor*textureMask+(vec4(1.,1.,1.,1.)-textureMask))*vColor;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute vec4 options;\n\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\nvoid main(void) { \nvec3 viewPos=(view*vec4(position,1.0)).xyz; \nvec3 cornerPos;\nfloat size=options.y;\nfloat angle=options.x;\nvec2 offset=options.zw;\ncornerPos=vec3(offset.x-0.5,offset.y-0.5,0.)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \nvColor=color;\nvUV=offset;\n\n#ifdef CLIPPLANE\nvec4 worldPos=invView*vec4(viewPos,1.0);\nfClipDistance=dot(worldPos,vClipPlane);\n#endif\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY \nvarying vec2 vOpacityUV;\nuniform sampler2D opacitySampler;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform sampler2D lightmapSampler;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICROUGHNESSMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallicRoughness.r);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\nmicroSurface=1.0-metallicRoughness.g;\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nvarying vec2 vOpacityUV;\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vEmissiveUV;\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nvarying vec2 vLightmapUV;\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<shadowsVertexDeclaration>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normal,0.0)));\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR_FIXED\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef AMBIENT\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef OPACITY\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef EMISSIVE\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef LIGHTMAP\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#ifdef BUMP\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","shadowMapPixelShader":"#ifndef FULLFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n\nvec2 packHalf(float depth) \n{ \nconst vec2 bitOffset=vec2(1.0/255.,0.);\nvec2 color=vec2(depth,fract(depth*255.));\nreturn color-(color.yy*bitOffset);\n}\n#endif\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef CUBEMAP\nuniform vec3 lightPosition;\nuniform vec2 depthValues;\n#endif\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#ifdef CUBEMAP\nvec3 directionToLight=vPosition.xyz-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth-depthValues.x)/(depthValues.y-depthValues.x);\ndepth=clamp(depth,0.,1.0);\n#else\nfloat depth=vPosition.z/vPosition.w;\ndepth=depth*0.5+0.5;\n#endif\n#ifdef VSM\nfloat moment1=depth;\nfloat moment2=moment1*moment1;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\n#endif\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(position,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\nvec4 color=vec4(0.0,0.0,0.0,0.0);\nfor (int i=0; i<9; i++) {\n#ifdef GAUSSIAN_BLUR_H\ncolor+=(texture2D(textureSampler,vUV+vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","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}"};
  55561. 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 vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\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"};
  55562. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),i=function(){function i(){this.radius=new t.Vector3(1,1,1),this.retry=0,this.basePointWorld=t.Vector3.Zero(),this.velocityWorld=t.Vector3.Zero(),this.normalizedVelocity=t.Vector3.Zero(),this._collisionPoint=t.Vector3.Zero(),this._planeIntersectionPoint=t.Vector3.Zero(),this._tempVector=t.Vector3.Zero(),this._tempVector2=t.Vector3.Zero(),this._tempVector3=t.Vector3.Zero(),this._tempVector4=t.Vector3.Zero(),this._edge=t.Vector3.Zero(),this._baseToVertex=t.Vector3.Zero(),this._destinationPoint=t.Vector3.Zero(),this._slidePlaneNormal=t.Vector3.Zero(),this._displacementVector=t.Vector3.Zero()}return i.prototype._initialize=function(e,o,i){this.velocity=o,t.Vector3.NormalizeToRef(o,this.normalizedVelocity),this.basePoint=e,e.multiplyToRef(this.radius,this.basePointWorld),o.multiplyToRef(this.radius,this.velocityWorld),this.velocityWorldLength=this.velocityWorld.length(),this.epsilon=i,this.collisionFound=!1},i.prototype._checkPointInTriangle=function(e,o,i,s,r){o.subtractToRef(e,this._tempVector),i.subtractToRef(e,this._tempVector2),t.Vector3.CrossToRef(this._tempVector,this._tempVector2,this._tempVector4);var n=t.Vector3.Dot(this._tempVector4,r);return!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(t.Vector3.CrossToRef(this._tempVector3,this._tempVector,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),n>=0))},i.prototype._canDoCollision=function(o,i,s,r){var n=t.Vector3.Distance(this.basePointWorld,o),c=Math.max(this.radius.x,this.radius.y,this.radius.z);return!(n>this.velocityWorldLength+c+i)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},i.prototype._testTriangle=function(e,i,s,r,n,c){var h,a=!1;i||(i=[]),i[e]||(i[e]=new t.Plane(0,0,0,0),i[e].copyFromPoints(s,r,n));var l=i[e];if(c||l.isFrontFacingTo(this.normalizedVelocity,0)){var _=l.signedDistanceTo(this.basePoint),d=t.Vector3.Dot(l.normal,this.velocity);if(0==d){if(Math.abs(_)>=1)return;a=!0,h=0}else{h=(-1-_)/d;var V=(1-_)/d;if(h>V){var u=V;V=h,h=u}if(h>1||V<0)return;h<0&&(h=0),h>1&&(h=1)}this._collisionPoint.copyFromFloats(0,0,0);var P=!1,p=1;if(a||(this.basePoint.subtractToRef(l.normal,this._planeIntersectionPoint),this.velocity.scaleToRef(h,this._tempVector),this._planeIntersectionPoint.addInPlace(this._tempVector),this._checkPointInTriangle(this._planeIntersectionPoint,s,r,n,l.normal)&&(P=!0,p=h,this._collisionPoint.copyFrom(this._planeIntersectionPoint))),!P){var f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p);y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(s)),this.basePoint.subtractToRef(r,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(r)),this.basePoint.subtractToRef(n,this._tempVector),T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,T,b,p),y.found&&(p=y.root,P=!0,this._collisionPoint.copyFrom(n)),r.subtractToRef(s,this._edge),s.subtractToRef(this.basePoint,this._baseToVertex);var g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex);if(m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),s.addToRef(this._edge,this._collisionPoint))}n.subtractToRef(r,this._edge),r.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),r.addToRef(this._edge,this._collisionPoint))),s.subtractToRef(n,this._edge),n.subtractToRef(this.basePoint,this._baseToVertex),g=this._edge.lengthSquared(),v=t.Vector3.Dot(this._edge,this.velocity),R=t.Vector3.Dot(this._edge,this._baseToVertex),m=g*-f+v*v,T=g*(2*t.Vector3.Dot(this.velocity,this._baseToVertex))-2*v*R,b=g*(1-this._baseToVertex.lengthSquared())+R*R,y=o(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(p=y.root,P=!0,this._edge.scaleInPlace(D),n.addToRef(this._edge,this._collisionPoint)))}if(P){var x=p*this.velocity.length();(!this.collisionFound||x<this.nearestDistance)&&(this.intersectionPoint?this.intersectionPoint.copyFrom(this._collisionPoint):this.intersectionPoint=this._collisionPoint.clone(),this.nearestDistance=x,this.collisionFound=!0)}}},i.prototype._collide=function(t,e,o,i,s,r,n){for(var c=i;c<s;c+=3){var h=e[o[c]-r],a=e[o[c+1]-r],l=e[o[c+2]-r];this._testTriangle(c,t,l,a,h,n)}},i.prototype._getResponse=function(e,o){e.addToRef(o,this._destinationPoint),o.scaleInPlace(this.nearestDistance/o.length()),this.basePoint.addToRef(o,e),e.subtractToRef(this.intersectionPoint,this._slidePlaneNormal),this._slidePlaneNormal.normalize(),this._slidePlaneNormal.scaleToRef(this.epsilon,this._displacementVector),e.addInPlace(this._displacementVector),this.intersectionPoint.addInPlace(this._displacementVector),this._slidePlaneNormal.scaleInPlace(t.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint,this._slidePlaneNormal,this._destinationPoint)),this._destinationPoint.subtractInPlace(this._slidePlaneNormal),this._destinationPoint.subtractToRef(this.intersectionPoint,o)},i}();t.Collider=i}(BABYLON||(BABYLON={}));var BABYLON;!function(o){o.WorkerIncluded=!0;var e=function(){function o(){this._meshes={},this._geometries={}}return o.prototype.getMeshes=function(){return this._meshes},o.prototype.getGeometries=function(){return this._geometries},o.prototype.getMesh=function(o){return this._meshes[o]},o.prototype.addMesh=function(o){this._meshes[o.uniqueId]=o},o.prototype.removeMesh=function(o){delete this._meshes[o]},o.prototype.getGeometry=function(o){return this._geometries[o]},o.prototype.addGeometry=function(o){this._geometries[o.id]=o},o.prototype.removeGeometry=function(o){delete this._geometries[o]},o}();o.CollisionCache=e;var i=function(){function e(e,i,r){this.collider=e,this._collisionCache=i,this.finalPosition=r,this.collisionsScalingMatrix=o.Matrix.Zero(),this.collisionTranformationMatrix=o.Matrix.Zero()}return e.prototype.collideWithWorld=function(o,e,i,r){var t=.01;if(this.collider.retry>=i)return void this.finalPosition.copyFrom(o);this.collider._initialize(o,e,t);for(var s,l=this._collisionCache.getMeshes(),n=Object.keys(l),a=n.length,c=0;c<a;++c)if(s=n[c],parseInt(s)!=r){var d=l[s];d.checkCollisions&&this.checkCollision(d)}return this.collider.collisionFound?(0===e.x&&0===e.y&&0===e.z||this.collider._getResponse(o,e),e.length()<=t?void this.finalPosition.copyFrom(o):(this.collider.retry++,void this.collideWithWorld(o,e,i,r))):void o.addToRef(e,this.finalPosition)},e.prototype.checkCollision=function(e){if(this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))){o.Matrix.ScalingToRef(1/this.collider.radius.x,1/this.collider.radius.y,1/this.collider.radius.z,this.collisionsScalingMatrix);var i=o.Matrix.FromArray(e.worldMatrixFromCache);i.multiplyToRef(this.collisionsScalingMatrix,this.collisionTranformationMatrix),this.processCollisionsForSubMeshes(this.collisionTranformationMatrix,e)}},e.prototype.processCollisionsForSubMeshes=function(o,e){var i=e.subMeshes,r=i.length;if(!e.geometryId)return void console.log(\"no mesh geometry id\");var t=this._collisionCache.getGeometry(e.geometryId);if(!t)return void console.log(\"couldn't find geometry\",e.geometryId);for(var s=0;s<r;s++){var l=i[s];r>1&&!this.checkSubmeshCollision(l)||(this.collideForSubMesh(l,o,t),this.collider.collisionFound&&(this.collider.collidedMesh=e.uniqueId))}},e.prototype.collideForSubMesh=function(e,i,r){if(!r.positionsArray){r.positionsArray=[];for(var t=0,s=r.positions.length;t<s;t+=3){var l=o.Vector3.FromArray([r.positions[t],r.positions[t+1],r.positions[t+2]]);r.positionsArray.push(l)}}if(!e._lastColliderWorldVertices||!e._lastColliderTransformMatrix.equals(i)){e._lastColliderTransformMatrix=i.clone(),e._lastColliderWorldVertices=[],e._trianglePlanes=[];for(var n=e.verticesStart,a=e.verticesStart+e.verticesCount,t=n;t<a;t++)e._lastColliderWorldVertices.push(o.Vector3.TransformCoordinates(r.positionsArray[t],i))}this.collider._collide(e._trianglePlanes,e._lastColliderWorldVertices,r.indices,e.indexStart,e.indexStart+e.indexCount,e.verticesStart,e.hasMaterial)},e.prototype.checkSubmeshCollision=function(e){return this.collider._canDoCollision(o.Vector3.FromArray(e.sphereCenter),e.sphereRadius,o.Vector3.FromArray(e.boxMinimum),o.Vector3.FromArray(e.boxMaximum))},e}();o.CollideWorker=i;var r=function(){function r(){}return r.prototype.onInit=function(i){this._collisionCache=new e;var r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.INIT};postMessage(r,void 0)},r.prototype.onUpdate=function(e){var i=this,r={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.UPDATE};try{for(var t in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(t)&&this._collisionCache.addGeometry(e.updatedGeometries[t]);for(var s in e.updatedMeshes)e.updatedMeshes.hasOwnProperty(s)&&this._collisionCache.addMesh(e.updatedMeshes[s]);e.removedGeometries.forEach(function(o){i._collisionCache.removeGeometry(o)}),e.removedMeshes.forEach(function(o){i._collisionCache.removeMesh(o)})}catch(l){r.error=o.WorkerReplyType.UNKNOWN_ERROR}postMessage(r,void 0)},r.prototype.onCollision=function(e){var r=o.Vector3.Zero(),t=new o.Collider;t.radius=o.Vector3.FromArray(e.collider.radius);var s=new i(t,this._collisionCache,r);s.collideWithWorld(o.Vector3.FromArray(e.collider.position),o.Vector3.FromArray(e.collider.velocity),e.maximumRetry,e.excludedMeshUniqueId);var l={collidedMeshUniqueId:t.collidedMesh,collisionId:e.collisionId,newPosition:r.asArray()},n={error:o.WorkerReplyType.SUCCESS,taskType:o.WorkerTaskType.COLLIDE,payload:l};postMessage(n,void 0)},r}();o.CollisionDetectorTransferable=r;try{if(self&&self instanceof WorkerGlobalScope){window={},o.Collider||(importScripts(\"./babylon.collisionCoordinator.js\"),importScripts(\"./babylon.collider.js\"),importScripts(\"../Math/babylon.math.js\"));var t=new r,s=function(e){var i=e.data;switch(i.taskType){case o.WorkerTaskType.INIT:t.onInit(i.payload);break;case o.WorkerTaskType.COLLIDE:t.onCollision(i.payload);break;case o.WorkerTaskType.UPDATE:t.onUpdate(i.payload)}};self.onmessage=s}}catch(l){console.log(\"single worker init\")}}(BABYLON||(BABYLON={}));var BABYLON;!function(e){e.CollisionWorker=\"\";var o;!function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(o=e.WorkerTaskType||(e.WorkerTaskType={}));var i;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(i=e.WorkerReplyType||(e.WorkerReplyType={}));var t=function(){function t(){var r=this;this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this.onMeshUpdated=function(e){r._addUpdateMeshesList[e.uniqueId]=t.SerializeMesh(e)},this.onGeometryUpdated=function(e){r._addUpdateGeometriesList[e.id]=t.SerializeGeometry(e)},this._afterRender=function(){if(r._init&&!(0==r._toRemoveGeometryArray.length&&0==r._toRemoveMeshesArray.length&&0==Object.keys(r._addUpdateGeometriesList).length&&0==Object.keys(r._addUpdateMeshesList).length||r._runningUpdated>4)){++r._runningUpdated;var e={updatedMeshes:r._addUpdateMeshesList,updatedGeometries:r._addUpdateGeometriesList,removedGeometries:r._toRemoveGeometryArray,removedMeshes:r._toRemoveMeshesArray},i={payload:e,taskType:o.UPDATE},t=[];for(var s in e.updatedGeometries)e.updatedGeometries.hasOwnProperty(s)&&(t.push(i.payload.updatedGeometries[s].indices.buffer),t.push(i.payload.updatedGeometries[s].normals.buffer),t.push(i.payload.updatedGeometries[s].positions.buffer));r._worker.postMessage(i,t),r._addUpdateMeshesList={},r._addUpdateGeometriesList={},r._toRemoveGeometryArray=[],r._toRemoveMeshesArray=[]}},this._onMessageFromWorker=function(t){var s=t.data;if(s.error!=i.SUCCESS)return void e.Tools.Warn(\"error returned from worker!\");switch(s.taskType){case o.INIT:r._init=!0,r._scene.meshes.forEach(function(e){r.onMeshAdded(e)}),r._scene.getGeometries().forEach(function(e){r.onGeometryAdded(e)});break;case o.UPDATE:r._runningUpdated--;break;case o.COLLIDE:r._runningCollisionTask=!1;var n=s.payload;if(!r._collisionsCallbackArray[n.collisionId])return;r._collisionsCallbackArray[n.collisionId](n.collisionId,e.Vector3.FromArray(n.newPosition),r._scene.getMeshByUniqueID(n.collidedMeshUniqueId)),r._collisionsCallbackArray[n.collisionId]=void 0}},this._collisionsCallbackArray=[],this._init=!1,this._runningUpdated=0,this._runningCollisionTask=!1,this._addUpdateMeshesList={},this._addUpdateGeometriesList={},this._toRemoveGeometryArray=[],this._toRemoveMeshesArray=[]}return t.prototype.getNewPosition=function(e,i,t,r,s,n,a){if(this._init&&!this._collisionsCallbackArray[a]&&!this._collisionsCallbackArray[a+1e5]){e.divideToRef(t.radius,this._scaledPosition),i.divideToRef(t.radius,this._scaledVelocity),this._collisionsCallbackArray[a]=n;var d={collider:{position:this._scaledPosition.asArray(),velocity:this._scaledVelocity.asArray(),radius:t.radius.asArray()},collisionId:a,excludedMeshUniqueId:s?s.uniqueId:null,maximumRetry:r},l={payload:d,taskType:o.COLLIDE};this._worker.postMessage(l)}},t.prototype.init=function(i){this._scene=i,this._scene.registerAfterRender(this._afterRender);var t=e.WorkerIncluded?e.Engine.CodeRepository+\"Collisions/babylon.collisionWorker.js\":URL.createObjectURL(new Blob([e.CollisionWorker],{type:\"application/javascript\"}));this._worker=new Worker(t),this._worker.onmessage=this._onMessageFromWorker;var r={payload:{},taskType:o.INIT};this._worker.postMessage(r)},t.prototype.destroy=function(){this._scene.unregisterAfterRender(this._afterRender),this._worker.terminate()},t.prototype.onMeshAdded=function(e){e.registerAfterWorldMatrixUpdate(this.onMeshUpdated),this.onMeshUpdated(e)},t.prototype.onMeshRemoved=function(e){this._toRemoveMeshesArray.push(e.uniqueId)},t.prototype.onGeometryAdded=function(e){e.onGeometryUpdated=this.onGeometryUpdated,this.onGeometryUpdated(e)},t.prototype.onGeometryDeleted=function(e){this._toRemoveGeometryArray.push(e.id)},t}();t.SerializeMesh=function(o){var i=[];o.subMeshes&&(i=o.subMeshes.map(function(e,o){return{position:o,verticesStart:e.verticesStart,verticesCount:e.verticesCount,indexStart:e.indexStart,indexCount:e.indexCount,hasMaterial:!!e.getMaterial(),sphereCenter:e.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:e.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:e.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:e.getBoundingInfo().boundingBox.maximumWorld.asArray()}}));var t=null;return o instanceof e.Mesh?t=o.geometry?o.geometry.id:null:o instanceof e.InstancedMesh&&(t=o.sourceMesh&&o.sourceMesh.geometry?o.sourceMesh.geometry.id:null),{uniqueId:o.uniqueId,id:o.id,name:o.name,geometryId:t,sphereCenter:o.getBoundingInfo().boundingSphere.centerWorld.asArray(),sphereRadius:o.getBoundingInfo().boundingSphere.radiusWorld,boxMinimum:o.getBoundingInfo().boundingBox.minimumWorld.asArray(),boxMaximum:o.getBoundingInfo().boundingBox.maximumWorld.asArray(),worldMatrixFromCache:o.worldMatrixFromCache.asArray(),subMeshes:i,checkCollisions:o.checkCollisions}},t.SerializeGeometry=function(o){return{id:o.id,positions:new Float32Array(o.getVerticesData(e.VertexBuffer.PositionKind)||[]),normals:new Float32Array(o.getVerticesData(e.VertexBuffer.NormalKind)||[]),indices:new Uint32Array(o.getIndices()||[])}},e.CollisionCoordinatorWorker=t;var r=function(){function o(){this._scaledPosition=e.Vector3.Zero(),this._scaledVelocity=e.Vector3.Zero(),this._finalPosition=e.Vector3.Zero()}return o.prototype.getNewPosition=function(e,o,i,t,r,s,n){e.divideToRef(i.radius,this._scaledPosition),o.divideToRef(i.radius,this._scaledVelocity),i.collidedMesh=null,i.retry=0,i.initialVelocity=this._scaledVelocity,i.initialPosition=this._scaledPosition,this._collideWithWorld(this._scaledPosition,this._scaledVelocity,i,t,this._finalPosition,r),this._finalPosition.multiplyInPlace(i.radius),s(n,this._finalPosition,i.collidedMesh)},o.prototype.init=function(e){this._scene=e},o.prototype.destroy=function(){},o.prototype.onMeshAdded=function(e){},o.prototype.onMeshUpdated=function(e){},o.prototype.onMeshRemoved=function(e){},o.prototype.onGeometryAdded=function(e){},o.prototype.onGeometryUpdated=function(e){},o.prototype.onGeometryDeleted=function(e){},o.prototype._collideWithWorld=function(o,i,t,r,s,n){void 0===n&&(n=null);var a=10*e.Engine.CollisionsEpsilon;if(t.retry>=r)return void s.copyFrom(o);t._initialize(o,i,a);for(var d=0;d<this._scene.meshes.length;d++){var l=this._scene.meshes[d];l.isEnabled()&&l.checkCollisions&&l.subMeshes&&l!==n&&l._checkCollision(t)}return t.collisionFound?(0===i.x&&0===i.y&&0===i.z||t._getResponse(o,i),i.length()<=a?void s.copyFrom(o):(t.retry++,void this._collideWithWorld(o,i,t,r,s,n))):void o.addToRef(i,s)},o}();e.CollisionCoordinatorLegacy=r}(BABYLON||(BABYLON={}));var BABYLON;!function(t){t.ToGammaSpace=1/2.2,t.ToLinearSpace=2.2,t.Epsilon=.001;var i=function(){function t(){}return t.WithinEpsilon=function(t,i,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"0\"+i).toUpperCase():i.toUpperCase()},t.Sign=function(t){return t=+t,0===t||isNaN(t)?t:t>0?1:-1},t.Clamp=function(t,i,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.prototype.toLinearSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToLinearSpace),i.g=Math.pow(this.g,t.ToLinearSpace),i.b=Math.pow(this.b,t.ToLinearSpace),this},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.prototype.toGammaSpaceToRef=function(i){return i.r=Math.pow(this.r,t.ToGammaSpace),i.g=Math.pow(this.g,t.ToGammaSpace),i.b=Math.pow(this.b,t.ToGammaSpace),this},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r.Random=function(){return new r(Math.random(),Math.random(),Math.random())},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}return t.prototype.addInPlace=function(t){return this.r+=t.r,this.g+=t.g,this.b+=t.b,this.a+=t.a,this},t.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},t.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,t[i+3]=this.a,this},t.prototype.add=function(i){return new t(this.r+i.r,this.g+i.g,this.b+i.b,this.a+i.a)},t.prototype.subtract=function(i){return new t(this.r-i.r,this.g-i.g,this.b-i.b,this.a-i.a)},t.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,i.a=this.a-t.a,this},t.prototype.scale=function(i){return new t(this.r*i,this.g*i,this.b*i,this.a*i)},t.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,i.a=this.a*t,this},t.prototype.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,i.a=this.a*t.a,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},t.prototype.clone=function(){return new t(this.r,this.g,this.b,this.a)},t.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this.a=t.a,this},t.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r((-this.x),(-this.y))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,this},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,this},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,this},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.prototype.normalize=function(){var t=this.length();if(0===t||1===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r((-1),0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9]+i.m[13],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){A.Vector3[0].x=t.y*i.z-t.z*i.y,A.Vector3[0].y=t.z*i.x-t.x*i.z,A.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(A.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,.5,0,h+e/2,s/2+a,.5,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,(-(t.y/o*2-1)),2*t.z-1),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(n,o,e,s){var h=n.normalize(),a=e.normalize(),u=f.X,m=f.Y,y=0,c=0,p=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=A.Vector3[0],R=0,T=A.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),r.CrossToRef(h,T,g),g.normalize(),r.Dot(a,g)<0&&(v=1),R=r.Dot(h,T),R=Math.min(1,Math.max(-1,R)),p=Math.acos(R)*v,r.Dot(T,u)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),d++);var _=A.Vector3[2],M=A.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),r.CrossToRef(_,T,M),M.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(T,g)<0&&(v=1),R=r.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,r.Dot(M,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,T,g),g.normalize(),r.Dot(g,m)<0&&(v=1),R=r.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,t[i+2]=this.z,t[i+3]=this.w,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,i.z=this.z+t.z,i.w=this.w+t.w,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,i.z=this.z-t.z,i.w=this.w-t.w,this},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z),(-this.w))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t,i.w=this.w*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,i.z=this.z*t.z,i.w=this.w*t.w,this},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,i.z=this.z/t.z,i.w=this.w/t.w,this},r.prototype.MinimizeInPlace=function(t){return t.x<this.x&&(this.x=t.x),t.y<this.y&&(this.y=t.y),t.z<this.z&&(this.z=t.z),t.w<this.w&&(this.w=t.w),this},r.prototype.MaximizeInPlace=function(t){return t.x>this.x&&(this.x=t.x),t.y>this.y&&(this.y=t.y),t.z>this.z&&(this.z=t.z),t.w>this.w&&(this.w=t.w),this},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this.z*=i,this.w*=i,this},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.subtract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},t.prototype.asArray=function(){return[this.x,this.y,this.z,this.w]},t.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},t.prototype.clone=function(){return new t(this.x,this.y,this.z,this.w)},t.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},t.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},t.prototype.add=function(i){return new t(this.x+i.x,this.y+i.y,this.z+i.z,this.w+i.w)},t.prototype.subtract=function(i){return new t(this.x-i.x,this.y-i.y,this.z-i.z,this.w-i.w)},t.prototype.scale=function(i){return new t(this.x*i,this.y*i,this.z*i,this.w*i)},t.prototype.multiply=function(i){var r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-this.x*t.z+this.y*t.w+this.z*t.x+this.w*t.y,o=this.x*t.y-this.y*t.x+this.z*t.w+this.w*t.z,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),this},t.prototype.multiplyInPlace=function(t){return this.multiplyToRef(t,this),this},t.prototype.conjugateToRef=function(t){return t.copyFromFloats(-this.x,-this.y,-this.z,this.w),this},t.prototype.conjugateInPlace=function(){return this.x*=-1,this.y*=-1,this.z*=-1,this},t.prototype.conjugate=function(){var i=new t((-this.x),(-this.y),(-this.z),this.w);return i},t.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},t.prototype.normalize=function(){var t=1/this.length();return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},t.prototype.toEulerAngles=function(t){void 0===t&&(t=\"YZX\");var i=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r=this.z,n=this.x,o=this.y,e=this.w,s=e*e,h=r*r,a=n*n,u=o*o,m=o*r-n*e,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(n*o+r*e),-h-a+u+s),t.x=Math.asin(-2*(r*o-n*e)),t.y=Math.atan2(2*(r*n+o*e),h-a-u+s)),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=this.z*this.x,h=this.y*this.w,a=this.y*this.z,u=this.x*this.w;return t.m[0]=1-2*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+i),t.m[11]=0,t.m[12]=0,t.m[13]=0,t.m[14]=0,t.m[15]=1,this},t.prototype.fromRotationMatrix=function(i){return t.FromRotationMatrixToRef(i,this),this},t.FromRotationMatrix=function(i){var r=new t;return t.FromRotationMatrixToRef(i,r),r},t.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},t.Inverse=function(i){return new t((-i.x),(-i.y),(-i.z),i.w)},t.Identity=function(){return new t(0,0,0,1)},t.RotationAxis=function(i,r){return t.RotationAxisToRef(i,r,new t)},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,r,n){var o=t.Identity();return t.SlerpToRef(i,r,n,o),o},t.SlerpToRef=function(t,i,r,n){var o,e,s=r,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}n.x=e*t.x+o*i.x,n.y=e*t.y+o*i.y,n.z=e*t.z+o*i.z,n.w=e*t.w+o*i.w},t}();t.Quaternion=a;var u=function(){function r(){this.m=new Float32Array(16)}return r.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(0===this.m[1]&&0===this.m[2]&&0===this.m[3]&&0===this.m[4]&&0===this.m[6]&&0===this.m[7]&&0===this.m[8]&&0===this.m[9]&&0===this.m[11]&&0===this.m[12]&&0===this.m[13]&&0===this.m[14])},r.prototype.determinant=function(){var t=this.m[10]*this.m[15]-this.m[11]*this.m[14],i=this.m[9]*this.m[15]-this.m[11]*this.m[13],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=this.m[8]*this.m[15]-this.m[11]*this.m[12],o=this.m[8]*this.m[14]-this.m[10]*this.m[12],e=this.m[8]*this.m[13]-this.m[9]*this.m[12];return this.m[0]*(this.m[5]*t-this.m[6]*i+this.m[7]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},r.prototype.toArray=function(){return this.m},r.prototype.asArray=function(){return this.toArray()},r.prototype.invert=function(){return this.invertToRef(this),this},r.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},r.prototype.add=function(t){var i=new r;return this.addToRef(t,i),i},r.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];return this},r.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},r.prototype.invertToRef=function(t){var i=this.m[0],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=this.m[5],h=this.m[6],a=this.m[7],u=this.m[8],m=this.m[9],y=this.m[10],c=this.m[11],p=this.m[12],f=this.m[13],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),F=1/(i*T+r*_+n*M+o*A),b=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,V=s*y-h*m,q=e*c-a*u,D=e*y-h*u,N=e*m-s*u;return t.m[0]=T*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=A*F,t.m[1]=-(r*z-n*w+o*v)*F,t.m[5]=(i*z-n*d+o*g)*F,t.m[9]=-(i*w-r*d+o*R)*F,t.m[13]=(i*v-r*g+n*R)*F,t.m[2]=(r*b-n*L+o*C)*F,t.m[6]=-(i*b-n*P+o*Z)*F,t.m[10]=(i*L-r*P+o*S)*F,t.m[14]=-(i*C-r*Z+n*S)*F,t.m[3]=-(r*I-n*H+o*V)*F,t.m[7]=(i*I-n*q+o*D)*F,t.m[11]=-(i*H-r*q+o*N)*F,t.m[15]=(i*V-r*D+n*N)*F,this},r.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},r.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},r.prototype.multiply=function(t){\nvar i=new r;return this.multiplyToRef(t,i),i},r.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},r.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;r<16;r++)t[i+r]=this.m[r];return this},r.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},r.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=this.m[3],h=this.m[4],a=this.m[5],u=this.m[6],m=this.m[7],y=this.m[8],c=this.m[9],p=this.m[10],f=this.m[11],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],F=t.m[8],b=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*F+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*F+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*F+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*F+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+z*C+w*I,this},r.prototype.equals=function(t){return t&&this.m[0]===t.m[0]&&this.m[1]===t.m[1]&&this.m[2]===t.m[2]&&this.m[3]===t.m[3]&&this.m[4]===t.m[4]&&this.m[5]===t.m[5]&&this.m[6]===t.m[6]&&this.m[7]===t.m[7]&&this.m[8]===t.m[8]&&this.m[9]===t.m[9]&&this.m[10]===t.m[10]&&this.m[11]===t.m[11]&&this.m[12]===t.m[12]&&this.m[13]===t.m[13]&&this.m[14]===t.m[14]&&this.m[15]===t.m[15]},r.prototype.clone=function(){return r.FromValues(this.m[0],this.m[1],this.m[2],this.m[3],this.m[4],this.m[5],this.m[6],this.m[7],this.m[8],this.m[9],this.m[10],this.m[11],this.m[12],this.m[13],this.m[14],this.m[15])},r.prototype.getClassName=function(){return\"Matrix\"},r.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},r.prototype.decompose=function(t,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return t.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===t.x||0===t.y||0===t.z?(n.x=0,n.y=0,n.z=0,n.w=1,!1):(r.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,A.Matrix[0]),a.FromRotationMatrixToRef(A.Matrix[0],n),!0)},r.prototype.getRotationMatrix=function(){var t=r.Identity();return this.getRotationMatrixToRef(t),t},r.prototype.getRotationMatrixToRef=function(t){var i=this.m,n=i[0]*i[1]*i[2]*i[3]<0?-1:1,o=i[4]*i[5]*i[6]*i[7]<0?-1:1,e=i[8]*i[9]*i[10]*i[11]<0?-1:1,s=n*Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),h=o*Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),a=e*Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);r.FromValuesToRef(i[0]/s,i[1]/s,i[2]/s,0,i[4]/h,i[5]/h,i[6]/h,0,i[8]/a,i[9]/a,i[10]/a,0,0,0,0,1,t)},r.FromArray=function(t,i){var n=new r;return i||(i=0),r.FromArrayToRef(t,i,n),n},r.FromArrayToRef=function(t,i,r){for(var n=0;n<16;n++)r.m[n]=t[n+i]},r.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;o++)n.m[o]=t[o+i]*r},r.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},r.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},r.prototype.setRow=function(t,i){if(t<0||t>3)return this;var r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},r.FromValues=function(t,i,n,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new r;return z.m[0]=t,z.m[1]=i,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,z.m[6]=h,z.m[7]=a,z.m[8]=u,z.m[9]=m,z.m[10]=y,z.m[11]=c,z.m[12]=p,z.m[13]=f,z.m[14]=x,z.m[15]=l,z},r.Compose=function(t,i,n){var o=r.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),e=r.Identity();return i.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),o},r.Identity=function(){return r.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},r.IdentityToRef=function(t){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},r.Zero=function(){return r.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},r.RotationX=function(t){var i=new r;return r.RotationXToRef(t,i),i},r.Invert=function(t){var i=new r;return t.invertToRef(i),i},r.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,i.m[1]=0,i.m[2]=0,i.m[3]=0,i.m[4]=0,i.m[7]=0,i.m[8]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationY=function(t){var i=new r;return r.RotationYToRef(t,i),i},r.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,i.m[1]=0,i.m[3]=0,i.m[4]=0,i.m[6]=0,i.m[7]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationZ=function(t){var i=new r;return r.RotationZToRef(t,i),i},r.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,i.m[2]=0,i.m[3]=0,i.m[6]=0,i.m[7]=0,i.m[8]=0,i.m[9]=0,i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0},r.RotationAxis=function(t,i){var n=r.Zero();return r.RotationAxisToRef(t,i,n),n},r.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},r.RotationYawPitchRoll=function(t,i,n){var o=new r;return r.RotationYawPitchRollToRef(t,i,n,o),o},r.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},r.Scaling=function(t,i,n){var o=r.Zero();return r.ScalingToRef(t,i,n,o),o},r.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.Translation=function(t,i,n){var o=r.Identity();return r.TranslationToRef(t,i,n,o),o},r.TranslationToRef=function(t,i,n,o){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,n,1,o)},r.Lerp=function(t,i,n){for(var o=r.Zero(),e=0;e<16;e++)o.m[e]=t.m[e]*(1-n)+i.m[e]*n;return o},r.DecomposeLerp=function(t,i,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);i.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return r.Compose(c,p,f)},r.LookAtLH=function(t,i,n){var o=r.Zero();return r.LookAtLHToRef(t,i,n,o),o},r.LookAtLHToRef=function(t,i,n,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},r.LookAtRH=function(t,i,n){var o=r.Zero();return r.LookAtRHToRef(t,i,n,o),o},r.LookAtRHToRef=function(t,i,n,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},r.OrthoLH=function(t,i,n,o){var e=r.Zero();return r.OrthoLHToRef(t,i,n,o,e),e},r.OrthoLHToRef=function(i,r,n,o,e){var s=n,h=o,a=2/i,u=2/r,m=2/(h-s),y=-(h+s)/(h-s);t.Matrix.FromValuesToRef(a,0,0,0,0,u,0,0,0,0,m,0,0,0,y,1,e)},r.OrthoOffCenterLH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterLHToRef=function(i,r,n,o,e,s,h){var a=e,u=s,m=2/(r-i),y=2/(o-n),c=2/(u-a),p=-(u+a)/(u-a),f=(i+r)/(i-r),x=(o+n)/(n-o);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,0,f,x,p,1,h)},r.OrthoOffCenterRH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterRHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterRHToRef=function(t,i,n,o,e,s,h){r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h.m[10]*=-1},r.PerspectiveLH=function(i,n,o,e){var s=r.Zero(),h=o,a=e,u=2*h/i,m=2*h/n,y=(a+h)/(a-h),c=-2*a*h/(a-h);return t.Matrix.FromValuesToRef(u,0,0,0,0,m,0,0,0,0,y,1,0,0,c,0,s),s},r.PerspectiveFovLH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovLHToRef(t,i,n,o,e),e},r.PerspectiveFovLHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,1,0,0,p,0,e)},r.PerspectiveFovRH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovRHToRef(t,i,n,o,e),e},r.PerspectiveFovRHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=-(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,-1,0,0,p,0,e)},r.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-(i+r)/(r-i),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(2*r*i)/(r-i)},r.GetFinalMatrix=function(t,i,n,o,e,s){var h=t.width,a=t.height,u=t.x,m=t.y,y=r.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return i.multiply(n).multiply(o).multiply(y)},r.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},r.GetAsMatrix3x3=function(t){return new Float32Array([t.m[0],t.m[1],t.m[2],t.m[4],t.m[5],t.m[6],t.m[8],t.m[9],t.m[10]])},r.Transpose=function(t){var i=new r;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},r.Reflection=function(t){var i=new r;return r.ReflectionToRef(t,i),i},r.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},r.FromXYZAxesToRef=function(t,i,r,n){n.m[0]=t.x,n.m[1]=t.y,n.m[2]=t.z,n.m[3]=0,n.m[4]=i.x,n.m[5]=i.y,n.m[6]=i.z,n.m[7]=0,n.m[8]=r.x,n.m[9]=r.y,n.m[10]=r.z,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.FromQuaternionToRef=function(t,i){var r=t.x*t.x,n=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(n+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+r),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(n+r),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},r}();u._tempQuaternion=new a,u._xAxis=e.Zero(),u._yAxis=e.Zero(),u._zAxis=e.Zero(),t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}return t.prototype.asArray=function(){return[this.normal.x,this.normal.y,this.normal.z,this.d]},t.prototype.clone=function(){return new t(this.normal.x,this.normal.y,this.normal.z,this.d)},t.prototype.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},t.prototype.normalize=function(){var t=Math.sqrt(this.normal.x*this.normal.x+this.normal.y*this.normal.y+this.normal.z*this.normal.z),i=0;return 0!==t&&(i=1/t),this.normal.x*=i,this.normal.y*=i,this.normal.z*=i,this.d*=i,this},t.prototype.transform=function(i){var r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,this.d=-(this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z),this},t.prototype.isFrontFacingTo=function(t,i){var r=e.Dot(this.normal,t);return r<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(p=t.Space||(t.Space={}));var f=function(){function t(){}return t}();f.X=new e(1,0,0),f.Y=new e(0,1,0),f.Z=new e(0,0,1),t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=x;var l;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(l=t.Orientation||(t.Orientation={}));var z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?l.CW:l.CCW,this.angle=z.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=w;var v=function(){function t(t,i){this._points=new Array,this._length=0,this.closed=!1,this._points.push(new o(t,i))}return t.prototype.addLineTo=function(t,i){if(closed)return this;var r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new w(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),y+=m}return this},t.prototype.close=function(){return this.closed=!0,this},t.prototype.length=function(){var t=this._length;if(!this.closed){var i=this._points[this._points.length-1],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=v;var d=function(){function r(t,i,r){this.path=t,this._curve=new Array,this._distances=new Array,this._tangents=new Array,this._normals=new Array,this._binormals=new Array;for(var n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.prototype._compute=function(t){var i=this._curve.length;this._tangents[0]=this._getFirstNonNullVector(0),this._raw||this._tangents[0].normalize(),this._tangents[i-1]=this._curve[i-1].subtract(this._curve[i-2]),this._raw||this._tangents[i-1].normalize();var r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=d;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,o,u*a));return new t(h)},t.prototype.getPoints=function(){return this._points},t.prototype.length=function(){return this._length},t.prototype[\"continue\"]=function(i){for(var r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=g;var R=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=R;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=T;var _=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=_;var M=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=M;var A=function(){function t(){}return t}();A.Color3=[r.Black(),r.Black(),r.Black()],A.Vector2=[o.Zero(),o.Zero(),o.Zero()],A.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],A.Vector4=[s.Zero(),s.Zero(),s.Zero()],A.Quaternion=[new a(0,0,0,0),new a(0,0,0,0)],A.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=A}(BABYLON||(BABYLON={}));";
  55563. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  55564. module.exports = BABYLON;
  55565. };